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;  
       }  
     });