Ramani Sandeep's Blog

DotNetting – Fast , Easy Way of Developing Applications

Archive for the ‘WCF’ Category

Inheritance in WCF

Posted by Ramani Sandeep on May 19, 2013

As a WCF developer you always get question from interviewer : “Can we implement Inheritance in WCF ServiceContract?

Answer will be:

YES we can have Contract Inheritance in WCF. In other words in WCF one ServiceContract can inherit other ServiceContract.

Let us take an example which explain us how to achieve it.

You have a ServiceContract named IParentService as given below :


 [ServiceContract]
 public interface IParentService
 {
    [OperationContract]
    string ParentMessage(string message);
 }

Another ServiceContract named IChildService can inherit IParentService as following :


 [ServiceContract]
 public interface IChildService : IParentService
 {
   [OperationContract]
   string ChildMessage(string message);
 }

Next you need to decide on implemention of Service. Single Service class can implement both contract by implementing bottom most ServiceContract in hierarchy. In this case bottom most ServiceContract is IChildService Service can be implemented as following in a single service class:


 public class Service1 : IChildService
 {
   public string ChildMessage(string message)
   {
     return "Hello " + message + "from Child Service";
   }

   public string ParentMessage(string message)
   {
     return "Hello " + message + "from Parent Service";
   }
 }

Now you have choice that either you can expose whole hierarchy as single EndPoint or different EndPoints for different Service Contract. To expose contract hierarchy create EndPoint with bottom most ServiceContract. In this case we are creating EndPoint with Service Contract IChildService . At the client side operations from whole hierarchy could be invoked.

Hope this will help !!!

Jay Ganesh

About these ads

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

Method Overloading in WCF

Posted by Ramani Sandeep on May 19, 2013

Method or Operation overloading is one of the most important feature of OOPS. In programming languages like C, C++ and C#, this feature is heavily used by developers. While writing Service definition you may come across when you need to overload operations.

Let us go ahead and write Service with overloaded function as following. In below ServiceContract I am creating two methods and overloading them with different parameters. To achieve overloading at Service side I set Name parameter of both function as follows:


  [OperationContract(Name = "GetIntegerData")]
  string GetData(int value);

  [OperationContract(Name = "GetStringData")]
  string GetData(string value);

So to consume service in my client application, you need to use the method name you specified in the Name attribute. The code in my client application will be:


  ServiceReference1.Service1Client client = new Client.ServiceReference1.Service1Client();
  Console.WriteLine(client.GetIntegerData(5));
  Console.WriteLine(client.GetStringData("pranay"));

Summary : You can easily use method overloading in WCF service with the help of Name field in OperationContract attribute.

Hope this will help !!!

Jay Ganesh

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

Add Custom Message Header in WCF 4 Calls

Posted by Ramani Sandeep on March 22, 2012

Often, we want to pass some data to some or maybe all our service operations. This data is usually context data such as user tokens, or environmental preferences of the user or machine.

In simple web service we can pass custom header information using Attribute called “[SoapHeaderAttribute ("ServiceHeader", Direction=SoapHeaderDirection.In)]” along with Web Method signatures.

But in WCF, we cannot use the same attribute.

One way would be to pass it as an additional request parameter. But, each and every method call needs to have this parameter(s) repeatedly. Not a very clean solution. Also, if the data type of this parameter changes, all the method signatures and their calls need to be changed.

A nice and easy way to pass that data is to use Message Headers.

In WCF, to pass the custom header information along with method call, we need to implement custom inspector for client and service which will implement the BeforeSendRequest and AfterRecieveRequest methods to inject the custom header.

In order to do this we need following objects/classes:

  1. Soap Header
  2. Message Inspector
  3. Client Context and Server Context class
  4. Custom Behavior

Let’s start creating these classes one by one.

1) Soap Header:

CustomHeader class is used to create custom header for service in which we want to pass header information along with method call. CustomHeader class contains the information that we want to pass along with method call. You can define the structure as per your needs.


    [DataContract]
    public class ServiceHeader
    {

        [DataMember]
        public string EmployeeID { get; set; }

        [DataMember]
        public string WindowsLogonID { get; set; }

        [DataMember]
        public string KerberosID { get; set; }

        [DataMember]
        public string SiteminderToken { get; set; }

    }

    public class CustomHeader : MessageHeader
    {
        private const string CUSTOM_HEADER_NAME = "HeaderName";
        private const string CUSTOM_HEADER_NAMESPACE = "YourNameSpace";

        private ServiceHeader _customData;

        public ServiceHeader CustomData
        {
            get
            {
                return _customData;
            }
        }

        public CustomHeader()
        {
        }

        public CustomHeader(ServiceHeader customData)
        {
            _customData = customData;
        }

        public override string Name
        {
            get { return (CUSTOM_HEADER_NAME); }
        }

        public override string Namespace
        {
            get { return (CUSTOM_HEADER_NAMESPACE); }
        }

        protected override void OnWriteHeaderContents(System.Xml.XmlDictionaryWriter writer, MessageVersion messageVersion)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(ServiceHeader));
            StringWriter textWriter = new StringWriter();
            serializer.Serialize(textWriter, _customData);
            textWriter.Close();

            string text = textWriter.ToString();

            writer.WriteElementString(CUSTOM_HEADER_NAME, "Key", text.Trim());
        }

        public static ServiceHeader ReadHeader(Message request)
        {
            Int32 headerPosition = request.Headers.FindHeader(CUSTOM_HEADER_NAME, CUSTOM_HEADER_NAMESPACE);
            if (headerPosition == -1)
                return null;

            MessageHeaderInfo headerInfo = request.Headers[headerPosition];

            XmlNode[] content = request.Headers.GetHeader<XmlNode[]>(headerPosition);

            string text = content[0].InnerText;

            XmlSerializer deserializer = new XmlSerializer(typeof(ServiceHeader));
            TextReader textReader = new StringReader(text);
            ServiceHeader customData = (ServiceHeader)deserializer.Deserialize(textReader);
            textReader.Close();

            return customData;
        }
    }

As you can see it is a type inheriting from MessageHeader class. Notice the OnWriteHeaderContents override, which is invoked by WCF infrastructure to serialize the SOAP Header, and the ReadHeader static method that we will use later.

2) Message Inspector:

SOAP Header needs to be added by the consumer and read by the service. To do this we need a Message Inspector like the following one:


    /// <summary>
    /// This class is used to inspect the message and headers on the server side,
    /// This class is also used to intercept the message on the client side, before/after any request is made to the server.
    /// </summary>
    public class CustomMessageInspector : IClientMessageInspector, IDispatchMessageInspector
    {
        #region Message Inspector of the Service

        /// <summary>
        /// This method is called on the server when a request is received from the client.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="channel"></param>
        /// <param name="instanceContext"></param>
        /// <returns></returns>
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            // Create a copy of the original message so that we can mess with it.
            MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue);
            request = buffer.CreateMessage();
            Message messageCopy = buffer.CreateMessage();

            // Read the custom context data from the headers
            ServiceHeader customData = CustomHeader.ReadHeader(request);

            // Add an extension to the current operation context so that our custom context can be easily accessed anywhere.
            ServerContext customContext = new ServerContext();

            if (customData != null)
            {
                customContext.KerberosID = customData.KerberosID;
                customContext.SiteminderToken = customData.SiteminderToken;
            }
            OperationContext.Current.IncomingMessageProperties.Add("CurrentContext", customContext);
            return null;
        }

        /// <summary>
        /// This method is called after processing a method on the server side and just
        /// before sending the response to the client.
        /// </summary>
        /// <param name="reply"></param>
        /// <param name="correlationState"></param>
        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            // Do some cleanup
            OperationContext.Current.Extensions.Remove(ServerContext.Current);
        }

        #endregion

        #region Message Inspector of the Consumer

        /// <summary>
        /// This method will be called from the client side just before any method is called.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="channel"></param>
        /// <returns></returns>
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            // Prepare the request message copy to be modified
            MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue);
            request = buffer.CreateMessage();

            ServiceHeader customData = new ServiceHeader();

            customData.KerberosID = ClientContext.KerberosID;
            customData.SiteminderToken = ClientContext.SiteminderToken;

            CustomHeader header = new CustomHeader(customData);

            // Add the custom header to the request.
            request.Headers.Add(header);

            return null;
        }

        /// <summary>
        /// This method will be called after completion of a request to the server.
        /// </summary>
        /// <param name="reply"></param>
        /// <param name="correlationState"></param>
        public void AfterReceiveReply(ref Message reply, object correlationState)
        {

        }

        #endregion
    }

As you can see from the code sample above, we use the IClientMessageInspector implementation to handle the addition of the header in the consumer-side code, while we use the IDispatchMessageInspector on the service side, to extract the header. It is interesting the FindHeader method of the MessageHeaders collection, as well as the method GetReaderAtHeader, provided by the same collection of Headers. The result of this last method is an XmlDictionaryReader that we use to read our custom header content, through the ReadHeader static method we’ve already introduced.

3) Client Context and Server Context class:

ClientContext class is used to store the header information before calling the method, so when you want to attach the custom header data, you just need to set the values for this ClientContext class. These values get fetched inside BeforeSendRequest method of CustomMessageInspector class and send along with the request made.


    /// <summary>
    /// This class will act as a custom context in the client side to hold the context information.
    /// </summary>
    public class ClientContext
    {
        public static string EmployeeID;
        public static string WindowsLogonID;
        public static string KerberosID;
        public static string SiteminderToken;
    }

At server side, once custom header is received, it will be stored inside this ServerContext class object, so that we can access it anytime once request is received.


    /// <summary>
    /// This class will act as a custom context, an extension to the OperationContext.
    /// This class holds all context information for our application.
    /// </summary>
    public class ServerContext : IExtension<OperationContext>
    {
        public string EmployeeID;
        public string WindowsLogonID;
        public string KerberosID;
        public string SiteminderToken;

        // Get the current one from the extensions that are added to OperationContext.
        public static ServerContext Current
        {
            get
            {
                return OperationContext.Current.Extensions.Find<ServerContext>();
            }
        }

        #region IExtension<OperationContext> Members
        public void Attach(OperationContext owner)
        {
        }

        public void Detach(OperationContext owner)
        {
        }
        #endregion
    }

4) Custom Behavior:

The service will be able to read the Key provided through the custom header simply querying the IncomingMessageProperties dictionary:


OperationContext.Current.IncomingMessageProperties["CurrentContext"];

Of course the Custom Message Inspector needs to be plugged into the WCF pipeline using a custom behavior like the following one.


    /// <summary>
    /// This custom behavior class is used to add both client and server inspectors to
    /// the corresponding WCF end points.
    /// </summary>
    [AttributeUsage(AttributeTargets.Class)]
    public class CustomBehavior : Attribute, IServiceBehavior, IEndpointBehavior
    {
        #region IEndpointBehavior Members

        void IEndpointBehavior.AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
        {
        }

        void IEndpointBehavior.ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
        {
            CustomMessageInspector inspector = new CustomMessageInspector();
            clientRuntime.MessageInspectors.Add(inspector);
        }

        void IEndpointBehavior.ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)
        {
            ChannelDispatcher channelDispatcher = endpointDispatcher.ChannelDispatcher;
            if (channelDispatcher != null)
            {
                foreach (EndpointDispatcher ed in channelDispatcher.Endpoints)
                {
                    CustomMessageInspector inspector = new CustomMessageInspector();
                    ed.DispatchRuntime.MessageInspectors.Add(inspector);
                }
            }
        }

        void IEndpointBehavior.Validate(ServiceEndpoint endpoint) { }

        #endregion

        #region IServiceBehavior Members

        void IServiceBehavior.AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
        {
        }

        void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription desc, ServiceHostBase host)
        {
            foreach (ChannelDispatcher cDispatcher in host.ChannelDispatchers)
            {
                foreach (EndpointDispatcher eDispatcher in cDispatcher.Endpoints)
                {
                    eDispatcher.DispatchRuntime.MessageInspectors.Add(new CustomMessageInspector());
                }
            }
        }

        void IServiceBehavior.Validate(ServiceDescription desc, ServiceHostBase host) { }

        #endregion
    }

Implement the IEndpointBehavior interface to modify, examine, or extend some aspect of endpoint-wide execution at the application level for either client or service applications.

  • Use the AddBindingParameters method to pass custom data at runtime to enable bindings to support custom behavior.
  • Use the ApplyClientBehavior method to modify, examine, or insert extensions to an endpoint in a client application.
  • Use the ApplyDispatchBehavior method to modify, examine, or insert extensions to endpoint-wide execution in a service application.
  • Use the Validate method to confirm that a ServiceEndpoint meets specific requirements. This can be used to ensure that an endpoint has a certain configuration setting enabled, supports a particular feature and other requirements.

Implement IServiceBehavior to modify, examine, or extend some aspect of service-wide execution at the application level:

  • Use the ApplyDispatchBehavior method to change run-time property values or insert custom extension objects such as error handlers, message or parameter interceptors, security extensions, and other custom extension objects.
  • Use the Validate method to examine the description before constructs the executing service to confirm that it can execute properly.
  • Use the AddBindingParameters method to pass to a binding element the custom information for the service so that it can support the service correctly.

Adding Behavior to the Runtime

When you construct a ServiceHost or client-side ChannelFactory, the runtime reflects over the service types, reads the configuration file, and starts building an in-memory description of the service. Within ServiceHost, this description is made available to you via the Description property (of type ServiceDescription). Within ChannelFactory, it’s made available via the Endpoint property (of type ServiceEndpoint); the client-side description is limited to the target endpoint.

The ServiceDescription contains a full description of the service and each endpoint (ServiceEndpoint), including contracts (ContractDescription) and operations (OperationDescription). ServiceDescription provides a Behaviors property (a collection of type IServiceBehavior) that models a collection of service behaviors. Each ServiceEndpoint also has a Behaviors property (a collection of type IEndpointBehavior) that models the individual endpoint behaviors. Likewise, ContractDescription and OperationDescription each have an appropriate Behaviors property.

These behavior collections are automatically populated during the ServiceHost and ChannelFactory construction process with any behaviors that are found in your code (via attributes) or within the configuration file (more on this shortly). You can also add behaviors to these collections manually after construction. The following example shows how to add the CustomBehavior to the host as a service behavior:


WCFServiceClient ws = new WCFServiceClient();
ws.ChannelFactory.Endpoint.Behaviors.Add(new CustomBehavior());

Adding Behavior with Attribute

During the ServiceHost/ChannelFactory construction process, the runtime reflects over the service types and configuration file and automatically adds any behaviors it finds to the appropriate behavior collections in the ServiceDescription.


  /// <summary>
    /// Summary description for WCFService
    /// </summary>
    [CustomBehavior]
    public class WCFService : IWCFService
    {
    }

That’s all! Enjoy your custom header passing using behavior specified.

Hope this will help!!!

Jay Ganesh

Posted in CodeProject, WCF | Tagged: , , , , , | 1 Comment »

No more pain to configure WCF 4 services

Posted by Ramani Sandeep on November 18, 2011

Developer who has worked with ASP.NET Web Services (ASMX) and WCF always feels that using predecessor was much more easier. It just because WCF configuration is much more complex as compare to ASP.NET Web Service.

WHY ??????

With ASMX, you were able to define a [WebMethod] operation and the runtime automatically provided a default configuration for the underlying communications. When moving to WCF 3.x, on the other hand, developers have to know enough about the various WCF configuration options to define at least one endpoint.

In an effort to make the overall WCF experience just as easy as ASMX, WCF 4 comes with a new “default configuration” model that completely removes the need for any WCF configuration. If you don’t provide any WCF configuration for a particular service, the WCF 4 runtime automatically configures your service with some standard endpoints and default binding/behavior configurations. This makes it much easier to get a WCF service up and running, especially for those who aren’t familiar with the various WCF configuration options.

Let’s discuss some of the standard configuration options that WCF 4 support :

1) Default Endpoints
2) Default Protocol Mapping
3) Default Binding Configurations
4) Default Behavior Configurations

1) Default Endpoints

With WCF 3.X, if you try to host a service without configured endpoints, ServiceHost instance will throw an exception informing you that you need to configure at least one endpoint. With WCF 4, this is no longer the case because the runtime automatically adds one or more ‘default endpoints’ for you.

Now question comes in mind, How this is done by WCF 4?

Answer to Question is like : When Host application calls Open method on ServiceHost instance, it build internal service description from the application configuration file. Than it check the count of configured endpoints. if it is still zero than it will call “AddDefaultEndpoints” public method and method will adds one default endpoint per base address for each service contract implemented by the service.

Clear or Confused ??

Lets take one example to be more clear on it.

If the service implements two service contracts and you configure the host with a single base address, AddDefaultEndpoints will configure the service with two default endpoints (one for each service contract). However, if the service implements two service contracts and the host is configured with two base addresses (one for HTTP and one for TCP), AddDefaultEndpoints will configure the service with four default endpoints.

I Hope now its clear….if still not…please go thru the link provided for more details on it.

-> New Features in WCF 4 that Will Instantly Make You More Productive
(http://www.code-magazine.com/Article.aspx?quickid=1006061)

2) Default Protocol Mapping

In .Net 4.0 framework, default protocol mapping between transport protocol schemes and the built in WCF bindings are as follows :


   <protocolMapping>
      <add scheme="http" binding="basicHttpBinding" bindingConfiguration="" />
      <add scheme="net.tcp" binding="netTcpBinding" bindingConfiguration=""/>
      <add scheme="net.pipe" binding="netNamedPipeBinding" bindingConfiguration=""/>
      <add scheme="net.msmq" binding="netMsmqBinding" bindingConfiguration=""/>
   </protocolMapping>

You can override these mappings at machine level by adding this section to machine.config file and modify the bindings as per your needs.

If you want to override this mappings at application level than you can override the above section in application/web configfile.

3) Default Binding Configurations

In WCF 3.x , binding can be done like this :


<configuration>
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicBindingMtom" messageEncoding="Mtom"/>
      </basicHttpBinding>
    </bindings>
    <services>
      <service name="HelloService">
        <endpoint address="mtom" binding="basicHttpBinding"
                  bindingConfiguration="BasicBindingMtom"
                  contract="IHello"/>
      </service>
    </services>
  </system.serviceModel>
</configuration>

Here “BasicBindingMtom” binding configuration overrides the defaults for BasicHttpBinding by changing the message encoding to “Mtom”. However this binding will effect only when you apply it to a specific endpoint thru “bindingConfiguration” attribute.

With WCF 4, binding can be done like this :


      <basicHttpBinding>
        <binding messageEncoding="Mtom"/>
      </basicHttpBinding>

No name attribute required. This feature gives you a simple mechanism to define a standard set of binding defaults that you can use across all your services without imposing any complexities of binding configurations.

4) Default Behavior Configurations

With WCF 4, it is possible to define default behavior configurations for services and endpoints.


    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>

Above configuration turns on the metadata for any service that doesn’t come with explicit behavior configuration.

In WCF 4, Behavior configuration also support inheritance model. It means that if application defines a behavior using same name as one already defined in machine.config, the application specific behavior configuration will get merged with machine configuration.

With these new additions in the WCF 4, it will be easier for developers to configure the services. I am sure that many developers will feel relaxed by having these new features in WCF and also start using it. Thats all from my side for this post.

Hope this will help !!!

Jay Ganesh ……

Posted in CodeProject, WCF, Web Services | Tagged: , , , , , , , , | 2 Comments »

DataContract Vs MessageContract

Posted by Ramani Sandeep on October 19, 2011

1. Comparison:

Data Contracts:

WCF data contracts provide a mapping function between .NET CLR types that are defined in code and XML Schemas Definitions defined by the W3C organization (www.w3c.org/) that are used for communication outside the service.

you can say “Data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged”. That is, to communicate, the client and the service do not have to share the same types, only the same data contracts. A data contract precisely defines, for each parameter or return type, what data is serialized (turned into XML) to be exchanged.

Message Contracts:

Message contracts describe the structure of SOAP messages sent to and from a service and enable you to inspect and control most of the details in the SOAP header and body. Whereas data contracts enable interoperability through the XML Schema Definition (XSD) standard, message contracts enable you to interoperate with any system that communicates through SOAP.

Using message contracts gives you complete control over the SOAP message sent to and from a service by providing access to the SOAP headers and bodies directly. This allows use of simple or complex types to define the exact content of the SOAP parts.

2. Why use MessageContract when DataContract is there?

Data contracts are used to define the data structure. Messages that are simply a .NET type, lets say in form of POCO (plain old CLR object), and generate the XML for the data you want to pass.

Message contracts are preferred only when there is a need to “control” the layout of your message(the SOAP message); for instance, adding specific headers/footer/etc to a message.

sometimes complete control over the structure of a SOAP message is just as important as control over its contents. This is especially true when interoperability is important or to specifically control security issues at the level of the message or message part. In these cases, you can create a message contract that enables you to use a type for a parameter or return value that serializes directly into the precise SOAP message that you need.

3. Why we use MessageContract to pass SOAP headers ?

Passing information in SOAP headers is useful if you want to communicate information “out of band” from the operation signature.

For instance, session or correlation information can be passed in headers, rather than adding additional parameters to operations or adding this information as fields in the data itself.

Another example is security, where you may want to implement a custom security protocol (bypassing WS-Security) and pass credentials or tokens in custom SOAP headers.

A third example, again with security, is signing and encrypting SOAP headers, where you may want to sign and/or encrypt some or all header information. All these cases can be handled with message contracts. The downside with this technique is that the client and service must manually add and retrieve the information from the SOAP header, rather than having the serialization classes associated with data and operation contracts do it for you.

4. Can’t mix datacontracts and messagecontracts.

Because message-based programming and parameter-based programming cannot be mixed, so you cannot specify a DataContract as an input argument to an operation and have it return a MessageContract, or specify a MessageContract as the input argument to an operation and have it return a DataContract. You can mix typed and untyped messages, but not messageContracts and DataContracts. Mixing message and data contracts will cause a runtime error when you generate WSDL from the service.

Hope this will help !!!

@@@ Happy Diwali @@@

Posted in CodeProject, WCF, Web Services | Tagged: , , , , | Leave a Comment »

ServiceContractGenerator vs ServiceDescriptionImporter

Posted by Ramani Sandeep on October 13, 2011

Recently, I have worked with WCF. During this , I have developed one tool that help us to run any web service (.asmx) and wcf service (.svc) by just using URL of it. It was totally dynamic process. In this process, I have learn how to fetch method list , parameter names and how to invoke method dynamically. During this process I came across the terms called ServiceDescriptionImporter and ServiceContractGenerator. So I feel that I should share what these terms means and difference between them with my readers. so here it goes…

ServiceDescriptionImporter :

The ServiceDescriptionImporter class allows you to easily import the information contained in a WSDL description into a System.CodeDom.CodeCompileUnit object.

By adjusting the value of the Style parameter, you can instruct a ServiceDescriptionImporter instance either to generate a client proxy class that provides the functionality of the Web service by transparently calling it or to generate an abstract class that encapsulates the functionality of the Web service without implementing it.

The code in the resulting CodeCompileUnit object can then either be called directly or exported in the language of your choice.

ServiceContractGenerator:

The System.ServiceModel.Description.ServiceContractGenerator type generates service contract code and binding configurations from System.ServiceModel.Description.ServiceEndpoint description objects.

ServiceContractGenerator vs ServiceDescriptionImporter:

–>ServiceDescriptionImporter is the class that is used by the “Add Web Reference” dialog in VS and the “wsdl.exe” tool in the SDK to generate “asmx” style client web service proxies.

ServiceContractGenerator is the WCF equivalent, for the “Add Service Reference” dialog in VS and the “svcutil.exe” tool in the SDK.

–> ServiceDescriptionImporter uses the asmx client infrastructure (System.Web.Services.Protocols.SoapHttpClientProtocol and friends).

ServiceContractGenerator uses the WCF client infrastructure (System.ServiceModel.ClientBase and friends).

Hope this will help !!!

Posted in CodeProject, WCF, Web Services | Tagged: , , | 3 Comments »

Consuming WCF / ASMX / REST service using JQuery By Sridhar Subramanian

Posted by Ramani Sandeep on February 22, 2010

In this article I will explain how to consume a WCF / ASMX service using jQuery.  The scope of the article is limited to creating &  consuming different kind of services using jQuery. I have segregated this article into 7 topics based on the service consumption.

  1. Calling ASMX Web service using jQuery
  2. Calling WCF service using jQuery and retrieving data in JSON Format
  3. Calling WCF service using jQuery and retrieving data in XML Format
  4. Calling WCF service using jQuery and retrieving data in JSON Format (pass multiple input parameters) & ( Get multiple objects as output using DataContract)
  5. Calling WCF service using jQuery[ Get Method] and retrieving data in JSON Format
  6. Calling REST based WCF service using jQuery
  7. Streaming an image through WCF and request it through HTTP GET verb..

If you have never heard about jQuery or WCF or JSON, please learn it before dwelling into this article. The scope  is limited to service creation and consumption.

Read more

Hope this will help

Jay Ganesh

Posted in JQuery, WCF, Web Services | Tagged: , , , | 3 Comments »

Web Service Vs WCF

Posted by Ramani Sandeep on November 12, 2009

Introduction

ASP.NET Web services were developed for building applications that send and receive messages by using the Simple Object Access Protocol (SOAP) over HTTP. The structure of the messages can be defined using an XML Schema, and a tool is provided to facilitate serializing the messages to and from .NET Framework objects. The technology can automatically generate metadata to describe Web services in the Web Services Description Language (WSDL), and a second tool is provided for generating clients for Web services from the WSDL.

WCF is for enabling .NET Framework applications to exchange messages with other software entities. SOAP is used by default, but the messages can be in any format, and conveyed by using any transport protocol. The structure of the messages can be defined using an XML Schema, and there are various options for serializing the messages to and from .NET Framework objects. WCF can automatically generate metadata to describe applications built using the technology in WSDL, and it also provides a tool for generating clients for those applications from the WSDL.

Protocol Support

WCF Supports following protocol: HTTP, TCP, Named Pipes, MSMQ, Custom, UDP.

Web Service Support only HTTP Protocol.

Hosting Support

Web Service can be hosted only with Http Runtime on IIS. WCF component can be hosted in any kind of environment in .NET 3.0, such as a console application, Windows application, or IIS.

WCF services are known as ‘services’ as opposed to web services because you can host services without a web server.

Self-hosting the services gives you the flexibility to use transports other than HTTP.

Backwards Compatibility

The purpose of WCF is to provide a unified programming model for distributed applications.

WCF takes all the capabilities of the existing technology stacks while not relying upon any of them.

Applications built with these earlier technologies will continue to work unchanged on systems with WCF installed.

Existing applications are able to upgrade with WCF

Integration

WCF can use WS-* or HTTP bindings to communicate with ASMX pages

Advantage of WCF or Limitations of ASMX

An ASMX page doesn’t tell you how to deliver it over the transports and to use a specific type of security. This is something that WCF enhances quite significantly.

ASMX has a tight coupling with the HTTP runtime and the dependence on IIS to host it. WCF can be hosted by any Windows process that is able to host the .NET Framework 3.0.

ASMX service is instantiated on a per-call basis, while WCF gives you flexibility by providing various instancing options such as Singleton, private session, per call.

ASMX provides the way for interoperability but it does not provide or guarantee end-to-end security or reliable communication.

Reference : http://msdn.microsoft.com/en-us/library/aa702755.aspx

Posted in WCF, Web Services | Tagged: , , , | 1 Comment »

What is Windows Communication Foundation?

Posted by Ramani Sandeep on July 21, 2009

.NET 3.0 comes with three main technologies in core: Windows Presentation Foundation, Windows Workflow Foundation and Windows Communication Foundation.

Windows Communication Foundation (WCF), codenamed Indigo in Microsoft, is the last generation of service oriented technologies for development.  It provides all the latest means to help developers build service oriented applications.  The result of service oriented design is a distributed system which runs between services and clients.  Windows Communication Foundation is Microsoft infrastructure for Service Oriented architecture.

You have probably worked with Web Services in .NET 1.x or 2.0 and may have some experiences with Remoting.  Windows Communication Foundation is an enhanced technology to provide the same functionality with better features and reduces the time to develop a distributed system.  Web Services and Services are not identical.  One main difference is Web Services use HTTP protocol, but Services can use any protocol and this is an important difference.

Service Orientation

In recent years, development moved from building centralized local systems to distributed systems which run on several places.  Each part of these systems are hosted somewhere and provide some services.  The idea of having services to answer to common needs through the web became serious and development technologies answered to this need by providing Web Services in their core, but day after day distributed systems became more common and the idea of Service Orientation (SO) was born.

Service Orientation is a complement to Object Orientation.  It means you will not kick Object Orientation out to use Service Orientation.  Service Orientation uses Object Orientation in its core, but there are some distributed scenarios that can be viewed by Object Orientation so you use Service Orientation to describe these scenarios.

In Service Orientation you think different and describe things via services and divide your system into smaller parts which run as services.  These services can communicate with others via messages.  In each service you can apply Object Orientation to accomplish goals of that service.  One important benefit of Service Orientation is here because you can use different technologies and platforms to design a service by using Object Orientation then use universal formats to build messages and start communication between different pieces of your system.

There are four principles in Service Orientation (you may see them as tenets on other resources):

  • Boundaries are explicit.
  • Services are autonomous.
  • Services share schema and contract, not class.
  • Service compatibility is determined based on policy.

You can read more about these fundamentals (they are important principles) on MSDN.

Generally, you have to change your point of view in Service Oriented design, but this should not change your view for Object Oriented Programming.  You should get enough experience to divide a system to logical independent services then choose appropriate platform to build each piece.  Thankfully, Microsoft helps you in all stages and you can use powerful Microsoft technologies to build your distributed software.

Service Oriented Architecture (SOA) is a concept beyond the scope of these tutorials.  I recommend you to read good books about Service Oriented Architecture to learn more about it.  Having a good understanding of this architecture is an important requirement to be success in this field.

Advantages

Windows Communication Foundation has some important enhancements in comparison with preceding technologies.

  • It merges all older separate technologies in one place and allows you to do things easier.
  • It has rich communication capabilities.
  • It comes with many powerful and ready to use enterprise features.
  • It can be integrated with other technologies and has great interoperability.

Architecture

Architecture of Windows Communication Foundation consists of five layers.  These layers from top to down are:

  • Application  : In this level application is located.
  • Contracts    : In the second layer service, data and message contracts as well as bindings and policies are present.  In this level services describe themselves to clients.
  • Runtime     : Behaviors are located in this layer.  Runtime layer loads all services.
  • Messaging  : Different types of channels as well as encoders are here.  This layer enables communications for services.
  • Hosting  : This layer is where host services in different manners, but there are two common ways to host a service.  You can host a service in Internet Information Services (IIS) which is easier than the second approach and starts and stops your services automatically.  The second approach is to create executable files (.EXE) for services and start and stop them manually by writing more codes.

This layering allows developers to work on Windows Communication Foundation with different skills because each layer needs different skills.

Programming Model

Windows Communication Foundation has simple and easy to write/understand codes.  It has many APIs, but beside this only a small amount of these API’s is common.

There are three programming approaches in Windows Communication Foundation:

  • Imperative                 : You use programming codes in different languages to accomplish a task.
  • Configuration Based  : You use configuration files to do things.
  • Declarative                 : You use attributes to declare something.

In general, you will declare contracts and behaviors using attributes, configure endpoints, security and some other settings in configuration files and will implement service methods logic in codes.

On the other hand, you can use typed services and untyped services.  In typed services you pass normal objects and data types and/or get normal objects and data types, but in untyped services you pass and get messages to work directly with messages at a lower level.

Other useful articles

Posted in WCF | Tagged: , , | 1 Comment »

 
Follow

Get every new post delivered to your Inbox.

Join 124 other followers