Monday, November 26, 2012

WCF : A simple WCF service exmaple

This post shows a very simple WCF example. Here are summarized steps.
 
(1) Run Visual Studio
(2) New Project - WCF - [WCF Service Application]
(3) Delete IService1.cs and Service1.svc
(4) Add New Item - [WCF Service] item. Name it SimpleService.svc.
 
(5) Write WCF interface in ISimpleService.cs as follows.
  • - WCF client only can see interface (or class) with ServiceContract attribute.
  • - WCF client only can use methods with OperationContract attribute. Properties, indexer, event cannot be used.
  • - WCF can only use primitive data type and DataContract type.
  • Regular CLR object reference cannot be used.
 
namespace SimpleWcfService
{    
    using System.Runtime.Serialization;
    using System.ServiceModel;

    [ServiceContract]
    public interface ISimpleService
    {
        [OperationContract]
        string SayHello(string name);

        [OperationContract]
        Customer UpdateCustomer(Customer customer);
    }

    [DataContract]
    public class Customer
    {
        [DataMember]
        public int ID { get; set; }

        [DataMember]
        public string Name { get; set; }
    }
}
 
(6) Write WCF service class that implements the interface.
// SimpleService.svc.cs
namespace SimpleWcfService
{
    public class SimpleService : ISimpleService
    {
        public string SayHello(string name)
        {
            string v = "Hello " + name;
            return v;
        }

        public Customer UpdateCustomer(Customer customer)
        {
            customer.Name += "#";
            return customer;
        }
    }
}
 
(7) Review SimpleService.svc file. Please note that Service name (SimpleWcfService.SimpleService) in this file. When wrong service name is specified here, service cannot be called. Developer often renames exisiting interface and class name but does not change this service name, which result in runtime error.(doubleclicking .svc in VS always often .svc.cs; so you have to use notepad to edit the file)
 
<%@ ServiceHost Language="C#" Debug="true" Service="SimpleWcfService.SimpleService" CodeBehind="SimpleService.svc.cs" %>
 
(8) web.config - by default httpGetEnabled is enabled which means you can use http get url to see meta data. Below is the default web.config.
<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>          
          <serviceMetadata httpGetEnabled="true"/>          
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>    
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
</configuration>
 
(9) WCF service can be hosted in IIS hosting, self-hosting (console application, windows application, service application, etc) or WAS. (8) To host WCF service in IIS, create a Site from IIS Manager. In this example, we add a new site called Simple with binding port 8088. So the service can be accessed by using http://localhost:8088/.
 
 
 

 
Click [Application Pools] and change .NET Framework version to v4.0 for the Simple website if it is not already set.
 
(10) To check to see if the WCF service is running, open web browser and type http://localhost:8088/SimpleService.svc
The following output will be shown when the WCF service is well hosted in IIS.
 

 
(11) Metadata : There are two ways to enable MetaData - Http Get URL and MEX endpoint. If serviceMetadata is specified under behavior node in web.config, meta data service is created.
 
A. If httpGetEnabled is set to true in serviceMetadata node, HTTP URL can be used to get WSDL meta data.
  <system.serviceModel>
    <services>
      <service name="SimpleWcfService.SimpleService" behaviorConfiguration="behavior1">
      </service>
    </services>            
    <behaviors>
      <serviceBehaviors>
        <behavior name="behavior1">
          <serviceMetadata httpGetEnabled="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
 
How to get metadata from HTTP GET
In web browser, type http://localhost:8088/SimpleService.svc?wsdl
 
B. MEX endpoint can be added in web.config to setup MEX.
 
Note: It is important to specify endpoint address correctly. Specifying incorrect url such as http://localhost:8088/ here can throw an exception. (See more details)
 
  <system.serviceModel>
    <services>      
      <service name="SimpleWcfService.SimpleService" behaviorConfiguration="behavior1">
        <endpoint address="http://localhost:8088/SimpleService.svc" binding="basicHttpBinding"
 contract="SimpleWcfService.ISimpleService"></endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>
      </service>
    </services>
            
    <behaviors>
      <serviceBehaviors>
        <behavior name="behavior1">
          <serviceMetadata />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
 
How to get metadata from MEX endpoint
 
C:\Temp>svcutil.exe http://localhost:8088/SimpleService.svc/mex
Microsoft (R) Service Model Metadata Tool
[Microsoft (R) Windows (R) Communication Foundation, Version 4.0.30319.1]
Copyright (c) Microsoft Corporation.  All rights reserved.

Attempting to download metadata from 'http://localhost:8088/SimpleService.svc/mex' using WS-Metadata Exchange or DISCO.
Generating files...
C:\Temp\SimpleService.cs
C:\Temp\output.config
 
(12) To test WCF service call from WCF client, run WcfTestClient.EXE. (C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\WcfTestClient.exe)
Select File - [Add Service] and type WCF service URL. To call WCF service method, double a method from left pane and input any parameter and then click [Invoke] button. This makes a SOAP-based WCF service call and the response will be shown below pane.
 

 

 
(13) WCF trace log (.svclog) : WCF trace log is very useful when looking into any WCF problem you might run into. To enable WCF logging, add the following to web.config under Configuration node. The log file location is specified in initializeData attribute.
 
  <system.diagnostics>
    <sources>
      <source name="System.ServiceModel" switchValue="All" propagateActivity="true">
        <listeners>
          <add type="System.Diagnostics.DefaultTraceListener" name="Default">
            <filter type="" />
          </add>
          <add name="xml">
            <filter type="" />
          </add>
        </listeners>
      </source>
      <source name="System.ServiceModel.MessageLogging" switchValue="All">
        <listeners>
          <add type="System.Diagnostics.DefaultTraceListener" name="Default">
            <filter type="" />
          </add>
          <add name="xml">
            <filter type="" />
          </add>
        </listeners>
      </source>
      <source name="XMLService.dll" switchValue="Warning, ActivityTracing">
        <listeners>
          <add type="System.Diagnostics.DefaultTraceListener" name="Default">
            <filter type="" />
          </add>
          <add name="xml">
            <filter type="" />
          </add>
        </listeners>
      </source>
    </sources>
    <sharedListeners>
      <add initializeData="C:\Temp\mywcf.svclog"
        type="System.Diagnostics.XmlWriterTraceListener, System, Version=4.0.0.0,
 Culture=neutral, PublicKeyToken=b77a5c561934e089"
        name="xml" traceOutputOptions="LogicalOperationStack, DateTime, Timestamp, ProcessId, ThreadId, Callstack">
        <filter type="" />
      </add>
    </sharedListeners>
    <trace autoflush="true" />
  </system.diagnostics>

No comments:

Post a Comment