b

Saturday, 26 May 2012

REST & JSON format(Hosting in IIS7 in WCF)


Build Basic WCF Service.

Step 1)  Create a Class Library (name it as wcftest)
                    Add reference System.ServiceModel  


            add 4 files   1)  Interface file 
                                2) Implementation File
                                3) SVC file
                                4) Web config file
Interface file


File name :  interface1.cs


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

namespace restapi
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IService1
    {

        [WebGet(RequestFormat=WebMessageFormat.Json,ResponseFormat = WebMessageFormat.Json, UriTemplate = "/GetPerson")]
        [OperationContract]
        Person getPersoninJSON();
        [WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "/GetData")]
        [OperationContract]
        String  GetData();

    }

[DataContract]
    public class Person
{
    [DataMember]
    public String Name;
    [DataMember]
    public int Age;
    [DataMember]
    public string color;
    public Person(string n,int a,string c)
    {
        Name = n;
        Age = a;
        color = c;
    }
}
}



Implementation file

file name is intImpl.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Runtime.Serialization;
using System.ServiceModel.Activation;
namespace restapi
{
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service1 : IService1
    {
        //Person p = new Person();
        public Person getPersoninJSON()
        {
            
            //p.Age = 38; p.color = "medium"; p.Name = "sitapati";
            
            return new Person("sirpatai",38,"medium");
        }

        public string GetData()
        {
            return "getting JSON data";
        }
    }
}



Add  SVC file
file name is wcftest.svc

<%@ ServiceHost Service="restapi.Service1"  Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>



Add   Web/application config file
file name:  web.config



<?xml version="1.0"?>
<configuration>

  <system.web>
    <compilation debug="true"/>
  </system.web>
  <!-- When deploying the service library project, the content of the config file must be added to the host's 
  app.config file. System.Configuration does not support config files for libraries. -->
  <system.serviceModel>
    <standardEndpoints>
      <webHttpEndpoint>
        <standardEndpoint helpEnabled="true" automaticFormatSelectionEnabled="true">
          
        </standardEndpoint>
      </webHttpEndpoint>
    </standardEndpoints>
    <services>
      <service name="restapi.Service1" behaviorConfiguration="webbeh">
        <endpoint contract="restapi.IService1" binding="webHttpBinding" ></endpoint>
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="jsonbe">
          <webHttp helpEnabled="true" automaticFormatSelectionEnabled="true" defaultOutgoingResponseFormat="Json"/>
        </behavior> 
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="webbeh">
          <!-- 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="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

<startup><supportedRuntime version="v2.0.50727"/>
</startup>
</configuration>


Build Class Library-> dll will be produced.



Now hosting WCF Service in IIS 7.0


Step 1)  Runt  Inetmgr.msc from run command


Step 2)   Add new Site as shown below


Step 3)   add site name as mywcfone, create folder with same or different in c:\inetpub\wwwroot\wcfone
Step 4)  Click on Connect as...   button and provide ur system's administrator name and password
               to test connection Click on Test Settings Button...(testing purpose only)
Step 5)  Add port as 8080   or some unused port from 1025-65535. Click OK


Step 6)  Previously Created WCF files copy to c:\inetput\wwwroot\wcfone  folder

Step 7)   create a bin folder in wcfone
                    copy   wcftest.dll to bin folder only (not to debug folder)
                  copy  svc file and   web.config file to    c:\inetput\wwwroot\wcfone  folder.

folders & files
 c:\inetput\wwwroot\wcfone\bin  has wcftest.dll
c:\inetput\wwwroot\wcfone   has  wcftest.svc and web.config files

open browser type 

http://localhost:7070/RestJSON.svc/GetData
http://localhost:7070/RestJSON.svc/GetPerson
following output will come for GetPerson method. similar thing for GetData also

Friday, 18 May 2012

How to host rest wcf service iis 7.0

Build Basic WCF Service.

Step 1)  Create a Class Library (name it as wcftest)
                    Add reference System.ServiceModel  


            add 4 files   1)  Interface file 
                                2) Implementation File
                                3) SVC file
                                4) Web config file
Interface file


File name :  interface1.cs


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

namespace wcftest
{
    [ServiceContract]
    interface InterfaceOne
    {
        [OperationContract]
        [WebGet]
        int add(int x, int y);

        [OperationContract]
         [WebGet]
        string getUserName(string user);
    }
}


Implementation file

file name is intImpl.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Runtime.Serialization;
using System.ServiceModel.Activation;
namespace wcftest
{
    [AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]
    public class intImpl : InterfaceOne
    {
        public int add(int x, int y)
        {
            return x + y;
        }

        public string getUserName(string user)
        {
            return string.Format("U entered {0} is:",user);
        }
    }
}



Add  SVC file
file name is wcftest.svc

<%@ ServiceHost Service="wcftest.intImpl"  Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>


Add   Web/application config file
file name:  web.config



<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MyserBehaviour">
          <serviceDebug includeExceptionDetailInFaults="true" />
          <serviceMetadata httpGetEnabled="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service name="WcfService2.Service1" behaviorConfiguration="MyserBehaviour">
        <endpoint contract="WcfService2.IService1" binding="webHttpBinding" bindingConfiguration="myweb"></endpoint>

      </service>
    </services>
    <bindings>
      <webHttpBinding>
        <binding name="myweb">
          <security mode="None">
          </security>
        </binding>
      </webHttpBinding>
    </bindings>
  </system.serviceModel>
</configuration>


Build Class Library-> dll will be produced.



Now hosting WCF Service in IIS 7.0


Step 1)  Runt  Inetmgr.msc from run command


Step 2)   Add new Site as shown below


Step 3)   add site name as mywcfone, create folder with same or different in c:\inetpub\wwwroot\wcfone
Step 4)  Click on Connect as...   button and provide ur system's administrator name and password
               to test connection Click on Test Settings Button...(testing purpose only)
Step 5)  Add port as 8080   or some unused port from 1025-65535. Click OK


Step 6)  Previously Created WCF files copy to c:\inetput\wwwroot\wcfone  folder

Step 7)   create a bin folder in wcfone
                    copy   wcftest.dll to bin folder only (not to debug folder)
                  copy  svc file and   web.config file to    c:\inetput\wwwroot\wcfone  folder.

folders & files
 c:\inetput\wwwroot\wcfone\bin  has wcftest.dll
c:\inetput\wwwroot\wcfone   has  wcftest.svc and web.config files

open browser type http://localhost:8088/WcfTest.svc/add?x=10&y=20
following output will come.


            

Wednesday, 9 May 2012

Basic Authentication in IIS host WCF service

Step 1)   Create  WCF Service
Step 3)   Host in IIS 7.0
Step 4)  Open Web.confg file

Add following code . i.e Transport credentials with basic authentication.


    <bindings>
      <basicHttpBinding>
        <binding name="Basicone">
          <security mode="Transport">
            <transport clientCredentialType="Basic"></transport>
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>

Provide this binding name in Service endpoint section 

<endpoint contract="ur choice" binding="basicHttpBinding" bindingConfiguration="Basicone"></endpoint>


Note: For Adding SSL certicate /Hosting WCF service in IIS.Please refer other articles.

Before Testing , Disable Anonymous Authentication, Enable Basic Authentication,  As shown below


     In this  Select  WCF Site i.e WCFOne(in this case)--> Features View-->in IIS category(Authentication)--> Double Click on it. 

Here  1)Disable Anonymous Authentication (i.e Disable)
          2) Enable Basic Authentication . 


SSL with WCF Service in Windows 2008 64-bit

Step 1)  Open Inetmanager by typying
               
Step 2)  Select server name in this case : SP2010  
                  Then double click on Server Certificates 




Click  on "Create-self-signed" certificate   enter certificate name  in this case "Mywcfcert1"  ,Click on OK.


Your certificate will be created.


Step 3)  Now goto  WCF Service hosted in IIS 


                In this case WCFONE    select   Edit Style--> Bindings



Click on Bindings 


                   Assign certificate as shown below





ABC of wcf

ABC in WCF
          A-->   Address
          B --> Binding
          C --> Contract

for ex WCF url:   http://localhost:111/myServiceHots.svc

localhost:111/myServiceHots.svc--> Address i.e server ,port and endpoint

http  is Binding,  Binding protocol,  it can be http,https, net.tccpip, net.msmq, net.pipe.
Contract  -->  its a mutual agreement between client and wcf service
                                  Contracts can be DataContract
                                                            ServiceContract
                                                            MessageContract.

Step By Step Process to develop Simple WCF Service

Step 1)  Create WCF Service Application as shown below




It will create WcfService1 project
                     All files
                 IService1.cs --> interface declaration
                 Service1.svc --> WCF service activation code & service implementation code.
             Delete these 2 files

Step2)   Now Add  new 3 files
              1) MyInterface.cs
              2)MyInterfaceImpl.cs
              3) ServiceHostone.svc

    2.1) Creating interface file(MyInterface.cs) as shown below
 
FileName: MyInterface.cs



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
namespace WcfService1
{
   
    [ServiceContract]
    interface MyInterface
    {
        [OperationContract]
        int Add(int x, int y);


        [OperationContract]
        string getUsername();
        
    }
}


 2.2)  Creating  new class  MyInterfaceImpl.cs. This is interface/service implementation file

FileName:MyInterfaceImpl.cs


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

namespace WcfService1
{
    public class MyInterfaceImpl : MyInterface
    {
        public int Add(int x, int y)
        {
            return x + y;
        }

        public string getUsername()
        {
            return "My Name is john peter paul";
        }
    }
}


3.1) Create  SVC file  , for hosting WCF service in IIS hosting configuration.
     1)  Create text file name it as  ServiceHostone.svc

    in   ServiceHostOne.SVC

add following statement
                 <%@ ServiceHost Service="WcfService1.MyInterfaceImpl" %>

In this  WcfService1 is a  namespace
            MyInterfaceImpl is a interface implemented class,


Step 3) Build the Project/ F5 
           It will launch the WcfTestClient where our service will be loaded automatically

           3.1) Double click on each method.
           Right side  for Add method requires two params x & y  enter those value --> click on Invoke
result is shown below.




   3.2) Do Same thing for getUsername method.

That's it.

Sunday, 6 May 2012

host wcf service in windows service

Step 1)  Create Windows Service Application As shown below

Step 2)  Add references
                 1) System.ServiceModel
                 2) System.ServiceProcess

Step 3)  Add new class WsHost.cs (for wcf interface + implementation)

  FileName: wsHost.cs


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


namespace WindowsService1
{
    [ServiceContract]
    interface IOrder1
    {
        [OperationContract]
        int GetOrderCount();
        [OperationContract()]
        string getCustomername();

    }
    public     class wsHost:IOrder1
    {
        public int GetOrderCount()
        {
            return 100;
        }

        public string getCustomername()
        {
            return "Customer Name is jhon peter paul";
        }
    }
}

Step 4) Implement Service host in derived ServiceBase class
FileName:Service1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.ServiceModel;
namespace WindowsService1
{
    public partial class Service1 : ServiceBase
    {
        ServiceHost host = null;
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            if (host != null) host.Close();

            host = new ServiceHost(typeof(wsHost),
                new Uri("http://localhost:111/wsHost"));
            host.Open();
        }

        protected override void OnStop()
        {
            if (host != null) host.Close();
            host = null;
        }
    }
}

Step 5) Implement Installer class

After adding installer.cs

replace with the following content
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using System.ServiceProcess;

namespace WindowsService1
{
    [RunInstaller(true)]
    public partial class Installer1 : System.Configuration.Install.Installer
    {
        ServiceProcessInstaller process;
        ServiceInstaller service;
        public Installer1()
        {
            InitializeComponent();
            process = new ServiceProcessInstaller();
            process.Account = ServiceAccount.LocalSystem;

            service = new ServiceInstaller();
            service.ServiceName = "WCF host in Windows Service";
            service.Description = "Hosting wcf service in Windows Service";
            service.StartType = ServiceStartMode.Automatic;

            Installers.Add(process);
            Installers.Add(service);
        }
    }
}



Step 6)  Add application config & change copy to output directory option as shown below.


replace  app.config content
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MyserBehaviour">
          <serviceDebug  includeExceptionDetailInFaults="true"/>
          <serviceMetadata httpGetEnabled="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service name="WindowsService1.wsHost" behaviorConfiguration="MyserBehaviour">
        <endpoint contract="WindowsService1.IOrder1" binding="basicHttpBinding"></endpoint>

      </service>
    </services>
  </system.serviceModel>
</configuration>



Step 7)  Open VS2010 Command Prompt
  got application folder bin directory  in this case "c:\users\administrator\documents\visual studio 2010\Projects\WindowsService1\WindowsService1\bin\debug"


c:\Users\Administrator\Documents\Visual Studio 2010\Projects\WindowsService1\Win
dowsService1\bin\Debug>installutil WindowsService1.exe


Installutil.exe is used for installing Windows Services 


Step 8)  Goto Service Manager as shown below
It will display all services in the system, select "Wcf Host in Windows Service"  and start the service


Step 9) Open Browser  and type "http://localhost:111/wshost"

OUTPUT



TEST  ALL METHODS WITH   WCFTESTCLIENT

Open VS2010 command prompt type 
WcfTestClient

i.e c:>  wcftestclient.exe

and then  give above url/add service  http://localhost:111/wshost




Hosting WCF in IIS 7.0

Build Basic WCF Service.

Step 1)  Create a Class Library (name it as wcftest)
                    Add reference System.ServiceModel  


            add 4 files   1)  Interface file 
                                2) Implementation File
                                3) SVC file
                                4) Web config file
Interface file


File name :  interface1.cs


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

namespace wcftest
{
    [ServiceContract]
    interface InterfaceOne
    {
        [OperationContract]
        int add(int x, int y);

        [OperationContract]
        string getUserName(string user);
    }
}


Implementation file

file name is intImpl.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Runtime.Serialization;
using System.ServiceModel.Activation;
namespace wcftest
{
    [AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]
    public class intImpl : InterfaceOne
    {
        public int add(int x, int y)
        {
            return x + y;
        }

        public string getUserName(string user)
        {
            return string.Format("U entered {0} is:",user);
        }
    }
}



Add  SVC file
file name is wcftest.svc

<%@ ServiceHost Service="wcftest.intImpl"  %>


Add   Web/application config file
file name:  web.config


<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MyserBehaviour">
          <serviceDebug  includeExceptionDetailInFaults="true"/>
          <serviceMetadata httpGetEnabled="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service name="wcftest.intImpl" behaviorConfiguration="MyserBehaviour">
        <endpoint contract="wcftest.InterfaceOne" binding="basicHttpBinding"></endpoint>
     
      </service>
    </services>
  </system.serviceModel>
</configuration>


Build Class Library-> dll will be produced.



Now hosting WCF Service in IIS 7.0


Step 1)  Runt  Inetmgr.msc from run command


Step 2)   Add new Site as shown below


Step 3)   add site name as mywcfone, create folder with same or different in c:\inetpub\wwwroot\wcfone
Step 4)  Click on Connect as...   button and provide ur system administrator name and password
               to test connection Click on Test Settings Button...(testing purpose only)
Step 5)  Add port as 8080   or some unused port from 1025-65535. Click OK


Step 6)  Previously Created WCF files copy to c:\inetput\wwwroot\wcfone  folder

Step 7)   create a bin folder in wcfone
                    copy   wcftest.dll to bin folder only (not to debug folder)
                  copy  svc file and   web.config file to    c:\inetput\wwwroot\wcfone  folder.

folders & files
 c:\inetput\wwwroot\wcfone\bin  has wcftest.dll
c:\inetput\wwwroot\wcfone   has  wcftest.svc and web.config files

open browser type http://localhost:8088/WcfTest.svc
following output will come.


            

Saturday, 5 May 2012

WCF Introduction

Windows Communication Foundation(WCF)- Set of APIs for building Service oriented applications.
WCF designed using Service  Oriented Principle to support distributed computing.
Services are loosely coupled,Services typically have WSDL interface(Web Service Description Language).

With WCF User can build SOA & ROA applictaions.
i.e WCF supports SOAP format as well as XML & JSON format.

SOAP envelops are simple XML form that makes WCF platform independent. i.e WCF hosted in WIndows machine, can be accessed by linux, macintosh  etc., clients.