Tuesday, July 8, 2014

Create WCF Service in class project - Part 2

Once the service is hosted service can be called using Ajax call.

 function RedirectHyperlink(link) {  
   var base_url = "http://" + window.location.host + "/RedirectService.svc/RedirectHyperlink";  
   var NewLink = "http://" + window.location.host + link;  
   var value = $('#hfVal').val();  
   var data = '{"url":"' + link + '","id":"' + value + '"}';  
   $.ajax({  
     cache: false,  
     url: base_url,  
     type: "POST",  
     async: false,  
     data: data,  
     success: function (data, textStatus, jqXHR) {  
       window.location.href = NewLink;  
     },  
     error: function (xhr, status, error) {  
     }  
   });  
 }  

In here I created base_url for service call. this will always create correct path for service. (other wise if your page is located inside a folder then url can be differ.


In service return type is System.ServiceModel.Channels.Message then it need to change as follows:

   [ServiceContract(SessionMode = SessionMode.Allowed)]  
   public interface IBusinessLogicService   
   {  
     [OperationContract]  
     [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "{CurrentURL}/{stateId}/RenderBusinessLogic")]  
     System.ServiceModel.Channels.Message RenderBusinessLogic(string CurrentURL, string Id);  
   }  

Class implementation as follows:

   [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]  
   [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]  
   public class BusinessLogicService : IBusinessLogicService , IStateContext  
   {  
     public System.ServiceModel.Channels.Message RenderBusinessLogic(string CurrentURL, string Id)  
     {  
       try  
       {  
         if (HttpContext.Current.User.Identity.IsAuthenticated)  
         {  
           //Get state ID  
           string datasetInJsonString = // Add what ever you want  
           return H2JSONServiceHelper.JsonStringToMessage(datasetInJsonString);  
         }  
       }  
       catch (Exception ex)  
       {  
         LogManagerOnServer.HandleException(new H2ServerException(ex.Message) { ClientMessage = "Error in RenderBusinessLogic.", PageName = "H2ReactBusinessLogicService.cs" });  
       }  
       return null;  
     }  
     public static System.ServiceModel.Channels.Message JsonStringToMessage(string jsonString)  
     {  
       //transform the string to stream  
       MemoryStream memoryStream = new MemoryStream(new UTF8Encoding().GetBytes(jsonString));  
       //Set position to 0  
       memoryStream.Position = 0;  
       //return Message  
       return WebOperationContext.Current.CreateStreamResponse(memoryStream, "application/json");  
     }  
   }  

If we browse this service in browser we can't see publish version and it display error. To avoid that it needs to add
 [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]  
to class coding.

even though you can call service as follows:


     var ID =GetStateID();   
     var url = GetUrl();  
     var obj = {};  
     // Call the service method to get the json based business logic  
     var base_url = 'BusinessLogicService.svc/' + url + "/" + ID + "/RenderBusinessLogic";  
     debugger;  
     $.ajax({  
       cache: false,  
       url: base_url,  
       type: "GET",  
       async: false,        
       data: obj,  
       contentType: "application/json",  
       success: function (data, textStatus, jqXHR) {   
         // debugger;  
           },  
       error: function (xhr, status, error) {  
         debugger;  
       }  
     });  




Monday, June 2, 2014

Create WCF Service in class project - Part 1

In normal scenario when we need to host service we add separate WCF project to the solution. My Solution architecture is as follows:

In this scenario I need to add WCF service to the Business Layer and I need to host that service when web application is hosted (self hosted).

So I used following steps to implement above scenario.
  • Added Interface to Business Layer.
  [ServiceContract]  
   public interface IRedirectService  
   {   
     [OperationContract]  
     [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "RedirectHyperlink")]  
     void RedirectHyperlink(System.IO.Stream jsonString);       
   }  

  • Added Class to Business Layer  as follows and write the implementation.
   [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]  
   public class RedirectService : IRedirectService  
   {  
     public void RedirectHyperlink(System.IO.Stream jsonString)  
     {  
       string val = JsonSteamToString(jsonString);  
       string JsonVal = val.Replace("\"", "'");  
       var json_serializer = new JavaScriptSerializer();  
       TestJsonStateObject myobj = json_serializer.Deserialize<H2JsonStateObject>(JsonVal);  
      
     }  
     public string JsonSteamToString(Stream jsonStream)  
     {  
       StreamReader reader = new StreamReader(jsonStream);  
       return reader.ReadToEnd();  
     }     
   }  
In this method jsonString contain string value of object. In order to deserialize the object I have used JavaScriptSerializer class. It can be found in System.Web.Script.Serialization namespace.

 using System.Web.Script.Serialization;  
after deserialize it can be conver into object which you have declared.

  public class TestJsonStateObject  
   {  
     public string url { get; set; }  
     public string Id { get; set; }  
   }  

  • Modify Web application Web.config file in order to communicate with wcf service.
  <system.serviceModel>  
   <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true">  
    <serviceActivations>  
     <add factory="System.ServiceModel.Activation.ServiceHostFactory" relativeAddress="./RedirectService.svc" service="BusinessLayerProjectName.RedirectService" />  
    </serviceActivations>     
   </serviceHostingEnvironment>  
   <services>  
    <service behaviorConfiguration="ServiceBehaviour" name="BusinessLayerProjectName.RedirectService">  
     <endpoint address="" behaviorConfiguration="web" binding="webHttpBinding" contract="BusinessLayerProjectName.IRedirectService" />  
    </service>  
   </services>  
   <behaviors>  
    <endpointBehaviors>  
     <behavior name="web">  
      <webHttp />  
     </behavior>  
    </endpointBehaviors>  
    <serviceBehaviors>  
     <behavior name="ServiceBehaviour">  
      <serviceMetadata httpGetEnabled="true" />  
      <serviceDebug includeExceptionDetailInFaults="true" />  
     </behavior>  
    </serviceBehaviors>  
   </behaviors>  
  </system.serviceModel>  

then once you hosted your site you can see hosted wcf service by providing correct URL.

 http://localhost:50594/RedirectService.svc