A day with .Net

My day to day experince in .net

Archive for the ‘WCF’ Category

WCF Cross Domain Call With Jquery and JSONP

Posted by vivekcek on June 5, 2015

In this post i will show you how to enable cross domain call in WCF.
I am using Visual Studio 2010.
1. Create a WCF project.
Create Service Contract and Data Contract

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

namespace CQRS
{
 [DataContract]
 public class Customer
 {
 [DataMember]
 public string Name;

 [DataMember]
 public string Address;
 }

 [ServiceContract]
 public interface IService1
 {
 [OperationContract]
 [WebGet(BodyStyle = WebMessageBodyStyle.Bare,
 RequestFormat = WebMessageFormat.Json,
 ResponseFormat = WebMessageFormat.Json)]
 Customer GetCustomer();

 }

}

Implement the service contract as below

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

namespace CQRS
{

 [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
 public class Service1 : IService1
 {
 [WebGet(ResponseFormat = WebMessageFormat.Json)]
 public Customer GetCustomer()
 {
 return new Customer() { Name = "vivek", Address = "ps" };
 }
 }

}

Go to the mark up of Service1.svc and add Factory reference

<%@ ServiceHost Language="C#" Debug="true" Service="CQRS.Service1" CodeBehind="Service1.svc.cs"
Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory" %>

Now edit your web.config

<?xml version="1.0"?>

<configuration>

 <system.serviceModel>
 <behaviors>
 <endpointBehaviors>
 <behavior name="webHttpBehavior">
 <webHttp />
 </behavior>
 </endpointBehaviors>
 </behaviors>
 <bindings>
 <webHttpBinding>
 <binding name="webHttpBindingWithJsonP" crossDomainScriptAccessEnabled="true" />
 </webHttpBinding>
 </bindings>
 <services>
 <service name="CQRS.Service1">
 <endpoint address="" binding="webHttpBinding"
 bindingConfiguration="webHttpBindingWithJsonP" contract="CQRS.IService1"
 behaviorConfiguration="webHttpBehavior"/>
 </service>
 </services>
 </system.serviceModel>

 <system.web>
 <compilation debug="true" targetFramework="4.0" />
 </system.web>
 <system.webServer>
 <modules runAllManagedModulesForAllRequests="true"/>
 </system.webServer>

</configuration>

2. Create an ASP.NET project
Inside an aspx page add the below code.

 <script type="text/javascript">
 
 
 $(document).ready(function () {
 GetEmployee();
 //GetEmployee1();
 });


 //using getJson
 function GetEmployee() {

 $.getJSON('http://localhost:55973/Service1.svc/GetCustomer?callback=?', null, function (customers) {
 alert(customers.Name);
 });
 }

 //using ajax

 function GetEmployee1() {
 $.ajax({
 url: 'http://localhost:55973/Service1.svc/GetCustomer?callback=?',
 type: "GET",
 data: "{}",
 dataType: "jsonp",
 jsonpCallback: "localJsonpCallback"
 });
 }

 function localJsonpCallback(json) {
 alert('From ajax'+json.Name); 
 }
 

 </script>

Posted in WCF | Tagged: , , , | Leave a Comment »

Caching in ASP.NET MVC with Repository Pattern and WCF

Posted by vivekcek on June 25, 2014

In this post i will show you, how to implement caching in an asp.net mvc application.
This MVC application use repository pattern and consumes a WCF service.

1. Define an interface for our caching provider.

 public interface ICacheProvider
    {
        object Get(string key);
        void Set(string key, object data, int cacheTime);
        bool IsSet(string key);
        void Invalidate(string key);

    }

2. Implement this interface, dont forget to add reference for System.Runtime.Caching

 public class DefaultCacheProvider : ICacheProvider
    {
        private ObjectCache Cache { get { return MemoryCache.Default; } }

        public object Get(string key)
        {
            return Cache[key];
        }

        public void Set(string key, object data, int cacheTime)
        {
            CacheItemPolicy policy = new CacheItemPolicy();
            policy.AbsoluteExpiration = DateTime.Now + TimeSpan.FromMinutes(cacheTime);

            Cache.Add(new CacheItem(key, data), policy);
        }

        public bool IsSet(string key)
        {
            return (Cache[key] != null);
        }

        public void Invalidate(string key)
        {
            Cache.Remove(key);
        }
    }

3. In your repository add this code.

public class DVDRepository : IRepository
    {
        protected DVDStoreService.DVDServiceClient serviceClient;
        protected ICacheProvider cache;
        public DVDRepository(DVDStoreService.DVDServiceClient client, ICacheProvider cache)
        {
            if (client == null)
            {
                throw new ArgumentNullException("client");
            }
            serviceClient = client;
            this.cache = cache;
        }

        public List<DVDStoreService.Movie> GetAll()
        {
            List<DVDStoreService.Movie> movies = cache.Get("movies") as List<DVDStoreService.Movie>;
            if (movies == null)
            {
                movies = serviceClient.GetAllData().ToList();
                cache.Set("movies", movies, 60);
            }
            return movies;
        }
      }

Posted in MVC, WCF | Tagged: , , | Leave a Comment »

Using AutoMapper with WCF

Posted by vivekcek on June 24, 2014

1. Create WCF application.

2. Through Nuget add AutoMapper.

3. Now we will create a bootstrap class to initialize automapper.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AutoMapper;
using MoviesLibrary;

namespace DVDService
{
    public class AutomapBootstrap
    {
        public static void InitializeMap()
        {
            Mapper.CreateMap<Movie, MovieData>();
            Mapper.CreateMap<MovieData, Movie>();
            
        }
    }

}

4. To call this bootstrap when you call the service, we will create a service behavior attribute.

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.Web;

namespace DVDService
{
    public sealed class AutomapServiceBehavior : Attribute, IServiceBehavior
    {
        public AutomapServiceBehavior()
        {
        }


        public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase,
            Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
        {
            AutomapBootstrap.InitializeMap();
        }

        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
        {

        }

        public void Validate(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
        {

        }

        
    }

}

5. Now decorate your service with this attribute.

[AutomapServiceBehavior]
    [ServiceErrorBehavior(typeof(ElmahErrorHandler))]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class DVDService : IDVDService
    {
        MovieDataSource dataSource = null;

        public List<Movie> GetAllData()
        {
            try
            {
                List<MovieData> movies = dataSource.GetAllData();
                List<Movie> mappedMovies = Mapper.Map<List<MovieData>, List<Movie>>(movies);
                return mappedMovies;
            }
            catch (Exception ex)
            {
                throw new FaultException(ex.Message);
            }
        }

Posted in WCF | Tagged: | 1 Comment »

WCF Logging with ELMAH

Posted by vivekcek on June 24, 2014

In this post, i will show you how to use ELMAH for WCF logging.

1. Create a WCF application.

2. Through Nuget add ELMAH EveryWhere. (Link)

3. Download ELMAH’s SQL Script and create a database. (Link)

4. Create a class ElmahErrorHandler which implementIErrorHandler.

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Dispatcher;
using System.Web;

namespace DVDService
{
    public class ElmahErrorHandler : IErrorHandler
    {
        public bool HandleError(Exception error)
        {
            return false;
        }

        public void ProvideFault(Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)
        {
            if (error == null)
            {
                return;
            }
            if (HttpContext.Current == null)
            {
                return;
            }
            Elmah.ErrorSignal.FromCurrentContext().Raise(error);
        }
    }
}

5. Create a Service behaviour attribute ServiceErrorBehaviorAttribute.

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.Web;

namespace DVDService
{
    public class ServiceErrorBehaviorAttribute : Attribute, IServiceBehavior
    {
        private readonly Type errorHandlerType;

        public ServiceErrorBehaviorAttribute(Type errorHandlerType)
        {
            this.errorHandlerType = errorHandlerType;
        }
        
        public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
        {
            
        }

        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
        {
            IErrorHandler errorHandler;
            errorHandler = Activator.CreateInstance(errorHandlerType) as IErrorHandler;
            if (errorHandler != null)
            {
                foreach (ChannelDispatcherBase dispatcher in serviceHostBase.ChannelDispatchers)
                {
                    ChannelDispatcher cd = dispatcher as ChannelDispatcher;
                    cd.ErrorHandlers.Add(errorHandler);
                }
            }
        }

        public void Validate(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
        {
            
        }
    }
}

6. In Web.config just after add the below tags. Update your connection string.

<configSections>
    <sectionGroup name="elmah">
      <section name="errorLog" requirePermission="false"
                                           type="Elmah.ErrorLogSectionHandler, Elmah"/>
    </sectionGroup>
  </configSections>
  <connectionStrings>
    <add name="elmah" connectionString="Data Source=.\sqlexpress;Initial Catalog=ELMAH;Integrated Security=True"/>
  </connectionStrings>
  <elmah>
    <errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="elmah"/>
  </elmah>

7. In Web.config under add the tags below.

<handlers>
      <add name="ELMAH" verb="POST,GET,HEAD" path="elmah/default.aspx" type="Elmah.ErrorLogPageFactory, Elmah"/>
    </handlers>
    <modules runAllManagedModulesForAllRequests="true">
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah"/>
    </modules>

8. Under make sure this is correct.

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

9. Now implement your service

 [ServiceErrorBehavior(typeof(ElmahErrorHandler))]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class DVDService : IDVDService
    {
      public List<Movie> GetAllData()
        {
            throw new ApplicationException("TEST");
        }
    }

10. To view your exceptions http://localhost/YourService.svc/elmah/default.aspx

Posted in WCF | Tagged: , , | Leave a Comment »

SOAP Message inspector for SOAP WCF Web service proxy

Posted by vivekcek on October 31, 2012

I hope you know how to create a WCF proxy using SVCUTIL.EXE.
You can refer my old post ‘Create proxy of WCF web service with svcutil

Add the proxy class to your project and add reference to System.ServiceModel namespace.
use the below namespace’s in your project.

using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Security;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Description;

Now add a class MessageViewerInspector as a nested class.

internal class MessageViewerInspector : IEndpointBehavior, IClientMessageInspector
        {

            #region Properties
            public string RequestMessage { get; set; }
            public string ResponseMessage { get; set; }
            #endregion

            #region IEndpointBehavior Members
            public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
            {

            }

            public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
            {
                // adds our inspector to the runtime
                clientRuntime.MessageInspectors.Add(this);
            }

            public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
            {

            }

            public void Validate(ServiceEndpoint endpoint)
            {

            }
            #endregion

            #region IClientMessageInspector Members
            void IClientMessageInspector.AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
            {
                this.ResponseMessage = reply.ToString();
            }

            object IClientMessageInspector.BeforeSendRequest(ref System.ServiceModel.Channels.Message request, IClientChannel channel)
            {
                this.RequestMessage = request.ToString();
                return null;
            }
            #endregion
        }

Now create your proxy object as below.

MessageViewerInspector inspector = new MessageViewerInspector();
ServiceSoapClient _Client=new ServiceSoapClient()
_Client.Endpoint.EndpointBehaviors.Add(inspector);

the inspector object have 2 properties ‘RequestMessage’ and ‘ResponseMessage’ contain SOAP request and response after you called any operations through proxy.

Posted in WCF | Leave a Comment »

WCF REST Service accepting Raw Xml- WebContentTypeMapper

Posted by vivekcek on June 14, 2012

My Problem
———-

I want to develop a WCF-REST service that accept XML through POST method. Process the xml and send an xml response back. Different types of xml string are posted to my service. My service need to accept any format like text/xml,appilcation/xml etc.

How i am going to solve
————————————–

I am planning to use .NET 4.0 for my WCF service. In .NET 4.0 WCF support Raw data in the form of Stream.

To Code
——-

1. Create a WCF Service application.

2. In the Service contract write below code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;
using System.IO;
using System.Xml.Linq;
namespace RestRaw
{    
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "Push",
               RequestFormat = WebMessageFormat.Xml,
               ResponseFormat = WebMessageFormat.Xml,
               BodyStyle = WebMessageBodyStyle.Bare)]
        XElement DoWork(Stream xml);
    }
}

3. In the Service implementation write the following code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.IO;
using System.Xml.Linq;
namespace RestRaw
{
   
    public class Service1 : IService1
    {
        public XElement DoWork(Stream xml)
        {
            StreamReader reader = null;
            XDocument xDocRequest = null;
            string strXmlRequest = string.Empty;
            reader = new StreamReader(xml);
            strXmlRequest = reader.ReadToEnd();
            xDocRequest = XDocument.Parse(strXmlRequest);
            string response = "<Result>OK</Result>";
            return XElement.Parse(response);
        }
    }
}

4. Now create a class named RawContentTypeMapper.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Channels;
namespace RestRaw
{
    public class RawContentTypeMapper : WebContentTypeMapper
    {
        public override WebContentFormat GetMessageFormatForContentType(string contentType)
        {

            if (contentType.Contains("text/xml") || contentType.Contains("application/xml"))
            {

                return WebContentFormat.Raw;

            }

            else
            {

                return WebContentFormat.Default;

            }
        }
    }
}

5. Change your Web.config as below.

<configuration>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <services>
      <service behaviorConfiguration="" name="RestRaw.Service1">
        <endpoint address="" behaviorConfiguration="web" contract="RestRaw.IService1" binding="customBinding" bindingConfiguration="RawReceiveCapable"></endpoint>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception 

information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
    <bindings>
      <customBinding>
        <binding name="RawReceiveCapable">
          <webMessageEncoding webContentTypeMapperType="RestRaw.RawContentTypeMapper, RestRaw, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
          <httpTransport manualAddressing="true" maxReceivedMessageSize="524288000"
           transferMode="Streamed" />
        </binding>

      </customBinding>
    </bindings>
  </system.serviceModel>
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
  
</configuration>

6. Code to test service

 private static string PostXml(string xml, string url)
        {
            // Restful service URL
            //string url = txtURL.Text;

            // declare ascii encoding
            ASCIIEncoding encoding = new ASCIIEncoding();
            string strResult = string.Empty;
            // sample xml sent to Service & this data is sent in POST
            string SampleXml = xml;
            string postData = SampleXml.ToString();
            // convert xmlstring to byte using ascii encoding
            byte[] data = encoding.GetBytes(postData);
            // declare httpwebrequet wrt url defined above
            HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
            // set method as post
            webrequest.Method = "POST";
            // set content type
            webrequest.ContentType = "text/xml";
            // set content length
            webrequest.ContentLength = data.Length;
            // get stream data out of webrequest object
            Stream newStream = webrequest.GetRequestStream();
            newStream.Write(data, 0, data.Length);
            newStream.Close();
            // declare & read response from service
            HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();

            // set utf8 encoding
            Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
            // read response stream from response object
            StreamReader loResponseStream =
        new StreamReader(webresponse.GetResponseStream(), enc);
            // read string from stream data
            strResult = loResponseStream.ReadToEnd();
            // close the stream object
            loResponseStream.Close();
            // close the response object
            webresponse.Close();

            return strResult;
        }

Solution

DOWNLOAD

http://sdrv.ms/M0AunA

Posted in WCF | Tagged: , , | 19 Comments »

Create proxy of WCF web service with svcutil

Posted by vivekcek on April 27, 2011

So dear friends today i am writing about how to consume a real world WCF service in your application.Below i am listing the steps you must follow.

1.Get the URL of our web service,like http://demo.myservice.com/Service/MyWebService.svc.

2.Open the visual studio command prompt type the following command

svcutil.exe http://demo.myservice.com/Service/MyWebService.svc?wsdl

3.Go to your visual studio command directory like (d:\Program Files\Microsoft Visual Studio 2008\VC).

4.You can find a c sharp class file named MyWebService.cs and an output.config file.

5.Add MyWebService.cs file to your project,Refer this in your classes.

6.The following name spaces should be needed in your consuming class.

using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Security;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Description;

7.Open the output.config file you obtained through svcutil.An output.config file is given below

<configuration>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_ICarService" closeTimeout="00:01:00"
                    openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                    allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                    maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                    messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
                    useDefaultWebProxy="true">
                    <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                    <security mode="None">
                        <transport clientCredentialType="None" proxyCredentialType="None"
                            realm="" />
                        <message clientCredentialType="UserName" algorithmSuite="Default" />
                    </security>
                </binding>
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://demo.myservice.com/Service/MyWebService.svc"
                binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IMyService"
                contract="IMyService" name="BasicHttpBinding_IMyService" />
        </client>
    </system.serviceModel>
</configuration>

8.Note the enpoint address here is http://demo.myservice.com/Service/MyWebService.svc

9.Binding is BasicHttpBinding.

10.Create binding using the following code.

            BasicHttpBinding binding = new BasicHttpBinding();
            binding.Name = "BasicHttpBinding_IMyService";
            binding.CloseTimeout = TimeSpan.FromMinutes(1);
            binding.OpenTimeout = TimeSpan.FromMinutes(1);
            binding.ReceiveTimeout = TimeSpan.FromMinutes(10);
            binding.SendTimeout = TimeSpan.FromMinutes(1);
            binding.AllowCookies = false;
            binding.BypassProxyOnLocal = false;
            binding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
            binding.MaxBufferSize = 65536;
            binding.MaxBufferPoolSize = 524288;
            binding.MessageEncoding = WSMessageEncoding.Text;
            binding.TextEncoding = System.Text.Encoding.UTF8;
            binding.TransferMode = TransferMode.Buffered;
            binding.UseDefaultWebProxy = true;

            binding.ReaderQuotas.MaxDepth = 32;
            binding.ReaderQuotas.MaxStringContentLength = 8192;
            binding.ReaderQuotas.MaxArrayLength = 16384;
            binding.ReaderQuotas.MaxBytesPerRead = 4096;
            binding.ReaderQuotas.MaxNameTableCharCount = 16384;

            binding.Security.Mode = BasicHttpSecurityMode.None;
            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
            binding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
            binding.Security.Transport.Realm = "";
            binding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
            binding.Security.Message.AlgorithmSuite = SecurityAlgorithmSuite.Default;

11.Create an endpoint.

EndpointAddress ed = new EndpointAddress("http://demo.myservice.com/Service/MyWebService.svc");

12.Create a web service client of the proxy class using the binding and endpoint we created.

ServiceClient _client = new ServiceClient(binding, ed);

Posted in WCF | 1 Comment »