Wednesday, May 29, 2013

Create JSONP WCF Service




  • Open VS2012 , then Click New Project, Select  WCF Service library as  New Project  Template      (File --> New Project à WCF  --> WCF Service Library) and Change the Name and Solution name as “ClacLib” and “MyCalcultor”  



    
  •      Open IService1.cs file and delete everything and paste this
            using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace ClacLib
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string GetData(int value);

    }
}


  • Add “System.ServiceModel.Web” as Reference to WCF Service Lib project.


  •  Open Service1.cs file and delete everything  and paste this

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;

namespace ClacLib
{

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
   
    public class Service1 : IService1
    {

        [Description("Accepts LoginName and Get Employee By Login Name")]
        [WebGet(BodyStyle = WebMessageBodyStyle.Bare,
        RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json,
     UriTemplate = " GetData?value={value}")]

        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }
    }
}

Explanations:

WebGet – Get Method
Request Format and Response Format – accept and return data as JSON Objects
UriTemplate – PostFix of Service URL


  • Modify App.config file

You can delete this file , since we separate the service part from hosting part. But Keep   it As it is. We want only Web.Config file. 

  • Create new project under the same Solution and Select WCF Service Application as Project Template


  • Delete IService1.cs file and delete the cs file. We don’t want those two files since we have separated Service part from hosting part.




  •      Open Service1.svc file and delete ” CodeBehind="Service1.svc.cs"” part and Change the Service value

                                            Service Lib Project Name              Implemented Class Name


  • Add Service lib as Ref to Service Host project



Then click “OK”.

  • Modify the Web.config file

a.       Delete Service Model Section


b. Copy and paste below Section within that space as New Service Model

<system.serviceModel>

    <bindings>
      <webHttpBinding>
        <binding name="webHttpBindingWithJsonP" />
      </webHttpBinding>
    </bindings>

    <behaviors>

      <endpointBehaviors>
        <behavior name="webHttpBehavior">
          <webHttp helpEnabled="true" />
        </behavior>      
      </endpointBehaviors>

      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true"/>
          <serviceThrottling maxConcurrentCalls="100" maxConcurrentSessions="1000" maxConcurrentInstances="1160"/>
          <dataContractSerializer maxItemsInObjectGraph="655360000"/>
        </behavior>
      </serviceBehaviors>

    </behaviors>

    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />

    <services>
      <service name=" ClacLib.Service1">
        <endpoint address="Calc"
                  behaviorConfiguration="webHttpBehavior"
                  binding="webHttpBinding"
                  bindingConfiguration="webHttpBindingWithJsonP"
                  contract=" ClacLib.IService1"/>
      </service>
    </services>
  </system.serviceModel>

Explanations :

Services Tag –   Endpoint settings
Binding Tag -     Binding related Settings
Behaviors Tag - Behaviors related Settings


  •  Debug the application by press F5 or Click “Run”. It will host your service in localhost and open it in default browser. Give the correct URL and check whether it s working or not.

          Or else Use this URL
          http://localhost:8733/Service1.svc/Calc/GetData?value=4


  • Publish the Site and check again (How to Publish the Site ??? – Check here)

          I published the site in http://cd-ksurendran:8001
          Give some test values for {VALUE}

          Result of this URL look like this :



          If you don’t remember full URL  or want some help, Use this URL , it will display all  Operation Contract under specific Service Contract with some details

Result of this URL look like this :





Friday, May 10, 2013

Create Custom Event log for your Project

You can log your custom events from your application/Project to Window Event Viewer. This is mainly used for Debug or Error/Exception handling.

How to create Event Logger ?


public class EventLogger
    {
        string SourceName;  // Source name of an evet receiver
        public EventLogger(string sourcename)
        {
            this.SourceName = sourcename;
        }

        public void WriteToEventLog(string message)
        {
            EventLog elog = new EventLog();

            if (!EventLog.SourceExists(SourceName))
            {
                EventLog.CreateEventSource(SourceName, SourceName);
            }

            elog.Source = SourceName;
            elog.EnableRaisingEvents = true;
            elog.WriteEntry(message);
        }

    }

How to Use it ?

EventLogger eventlog = new EventLogger("MyEventLog");
eventlog.WriteToEventLog("Testing My Event Log!!!");

Where to find our log ?

Start --> Type "EventViewer" --> expand "Applications and Services Logs" and click your EventLog (By SourceName which you gave in the EventLogger Constructor)

How to delete the source from Event Viewer?

[HKEY_LOCAL_MACHINE] --> SYSTEM --> CurrentControlSet --> Services --> Eventlog then select your Event Logger then right click and delete it.

Monday, March 18, 2013

AJAX Supporting Sharepoint Web parts with JSONP WCF Services

What is AJAX ?

AJAX = Asynchronous JavaScript and XML.
AJAX is a technique for creating fast and dynamic web pages.
AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.
Classic web pages, (which do not use AJAX) must reload the entire page if the content should change.
Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs.

Click here for AJAX Tutorial

In this post , we are going to create a share point page with AJAX Supporting web parts which invokes JSONP services to get data from Server.

1. Create JSONP WCF Services(How to create?)


Format of the Result

Link : 
http://ServerName:PorNumber/Service.svc/jsp/GetEmployeMoreDetailsByUserName?method=JsonPCallBack&logInName=User1

Result :

JsonPCallBack(
{
    "DateOfBirth":"\/Date(969042600000+0530)\/",
    "AboutMe":"This is all About Me",
    "CurrentATC":"CMB ATC",
    "Department":"OIG--CMB-VPL-Shared Services-Center Management",
    "Experience":16.2,
    "Interests":["UX Design","SharePoint","Photography"],
    "Languages":[""],
    "NoofPastProjects":33,
    "PermanentATC":"CMB ATC",
    "ReportingManager":"Domain\\UserName",
    "Tier":0,
    "Since":"\/Date(852057000000+0530)\/"
}
);

 
2. Create Empty/Visual Web part project and create web parts.

3. In aspx page create client side controls (Button , Label , text box ...etc)

<div>

Search Employee : <input id="SearchEmpName" type="text" name="SearchEmpName"  value=""/>
<input id="btnWCFREST" type = "button" value = "Search" /><br/>

<b>Reporting Manager:</b> <label id = "EmpReportlbl" ></label><br/>
<b>Department:</b> <label id = "EmpDepartlbl" ></label><br/>
<b>Tier:</b> <label id = "EmpTierlbl" ></label><br/>
<b>Permanent Office:</b> <label id = "EmpPermAtclbl" ></label><br/>
<b>Current Office:</b> <label id = "EmpCurrAtclbl" ></label><br/>
<b>Interests:</b> <label id = "EmpIntelbl" ></label><br/>
<b>Date Of Birth:</b> <label id = "EmpDOBlbl" ></label><br/>
<b>Languages:</b> <label id = "Emplanglbl" ></label><br/>
<b>Experience:</b> <label id = "EmpExpelbl" ></label><br/>

</div>



4. Add reference to the project in order to use JQuery in Web parts

<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.min.js"></script> 

5. Use the JQuery to invoke the WCF Services in AJAX.
Check this for more about JQuery :  JQuery, Write Less, do more

<script type="text/javascript">
    jQuery.support.cors = true;

    $(document).ready(function () {
        $("#btnWCFREST").click(function () {
            $.ajax({
                url: 'http://ServerName:PortNumber/Service.svc/jsp/GetEmployeMoreDetailsByUserName?logInName=' + $("#SearchEmpName").val() + '&method=?',
                type: 'GET',
                dataType: 'jsonp',
                error: function (x, t, r) { alert("Error In Employee More Details"); },
                success: function (data) {
                    document.getElementById('EmpReportlbl').innerText = data.ReportingManager;
                    document.getElementById('EmpDepartlbl').innerText = data.Department;
                    document.getElementById('EmpTierlbl').innerText = data.Tier;
                    document.getElementById('EmpPermAtclbl').innerText = data.PermanentATC;
                    document.getElementById('EmpCurrAtclbl').innerText = data.CurrentATC;
                    document.getElementById('EmpIntelbl').innerText = data.Interests;
                    document.getElementById('EmpDOBlbl').innerText = Date(data.DateOfBirth);  
                    document.getElementById('Emplanglbl').innerText = data.Languages;
                    document.getElementById('EmpExpelbl').innerText = data.Experience;
                }
            });


        });
    });
</script>


6. check whether AJAX is working or not by putting breakpoints in VS project in Page load method and attach appropriate process.

Follow Best Practises On WCF Services

If we organize the creation of WCF Services into this way , it will be efficient and can be changed in future without much efford.

1.  Create ServiceContract
     - Create Interface
2.  Create OperationContract under that ServiceContract
     - 
3.  Create Business Object (eg : employee)
     It has all required business parameters

4.  Return Data Transfer Objects (DTO) (eg : employeeDto)
     it has only the required parameters for that service. every services can have it's own Dto objects.

5.  Create Data Access Objects (DAO) (eg : employeeDao)  
     It is the object directly involve with data layer to get required data then process the data and map  it to business objects.

6. Create Object Mapper class (eg : ObjectMapper) and Mapper functions (eg : EmployeeDaoToDto) between DTO and DAO.
    Before send the objects to client side browser , services must convert the business objects to Data transfer objects. So mapping functions map the Data transfer object with business object.

WCF With JSONP

Before start with JSONP we should know what is REST ? and how it differ from other protocols? - Learn REST

What is JSONP ?

 JSONP or "JSON with padding" is a communication technique used in JavaScript. It provides a method to request data from a server in a different domain, something prohibited by typical web browsers because of the same origin policy.

By default WCF Services will not return JSON objects as result. if we want to get JSON objects , we have to define at Service implementation level.

If you are new to WCF , check this to get basic understanding about WCF!!!  -  Simple Steps to create the WCF Service

1.  Create WCF Library (WCF Service Library Template)

      a. Create Service contracts

          [OperationContract]
          [WebGet(ResponseFormat = WebMessageFormat.Json)]
          [JSONPBehavior(callback = "method")]
      
          EmployeeWorkDto GetEmployeMoreDetailsByUserName(string logInName);

       

      b. Create Service Implementations (Check this for more details)

Create Business object (employee), Data transfer objects (employeeDto), Data access objects  (employeeDao) , object mapper class(CoreObjectMapper) and mapping   functions(EmployeeDaoToDto).

"GetEmployeByUserName" is the function do all processing and return the result as "employee". then mapper function maps the "employee" object with "employeeDto". finally "employeeDto" will be send as response of that Service call.

         public EmployeeWorkDto GetEmployeMoreDetailsByUserName(string logInName)
        {

              // Do all Your implementation here, but return as "EmployeeWorkDto" Data transfer object
              EmployeeDao empDao = new EmployeeDao();
              return  CoreObjectMapper.EmployeeDaoToDto(empDao.GetEmployeByUserName(logInName));

        }


2. Create WCF Hosting Application (WCF Service Application Template)

      a. Modify Web.config

     i. create new end point

      <endpoint address="jsp"
          binding="customBinding"
          bindingConfiguration="jsonpBinding"
          behaviorConfiguration="restBehavior"
          contract="CoreService.IEmployeeService" />


     and specify binding , binding configuration and behavior configuration

     <endpointBehaviors>
           <behavior name="restBehavior">
              <webHttp />
          </behavior>        

    </endpointBehaviors>

    <customBinding>
           <binding name="jsonpBinding" >
               <jsonpMessageEncoding />
              <httpTransport manualAddressing="true"/>
          </binding>

   </customBinding>

and Host the Service and Check whether it is working or not by invoking the services in Browser.
Use the breakpoints for debug the application (Attach appropriate Processes - IIS App pool process and w3wp.exe  )

Service Url: 
http://ServerName:portNumber/Service.svc/jsp/GetEmployeMoreDetailsByUserName?method=JsonPCallBack&logInName=User1

Result :

JsonPCallBack(
{
    "DateOfBirth":"\/Date(969042600000+0530)\/",
    "AboutMe":"This is about Me ",
    "CurrentATC":"CMB ATC",
    "Department":"Delivery",
    "Experience":8.3,
    "Interests":["UX Design","SharePoint","Photography"],
    "Languages":[""],
    "NoofPastProjects":16,
    "PermanentATC":"CMB ATC",
    "ReportingManager":"Domain\\UserName",
    "Tier":2,
    "Since":"\/Date(852057000000+0530)\/"
}
);