Showing posts with label WCF. Show all posts
Showing posts with label WCF. Show all posts

How to host wcf service in IIS using Tcp protocol

In this post I am going to show you how to host WCF service in IIS using TCP protocol.By default, the TCP WCF activation service is not enabled on your machine. You can follow these steps to enable the TCP activation for WCF services:
  1. Go to Control Panel | Programs | Turn Windows features on or off.
  2. Expand the Microsoft .Net Framework 3.5.1 node on Windows 7
  3. Check the checkbox for Windows Communication Foundation Non-HTTP Activation on Windows 7
getfile
Next,Create the IIS application to host the WCF application using TCP protocol.Follow these steps
  1. Open run command and type inetmgr
  2. Create a new application and point to physical folder.
  3. Select the DefaultAppPoll  and make sure your default app pool is a .NET 4.0.X application pool.
  4. Right-click on web application, select Manage Application | Advanced Settings, and then add net.tcp to Enabled Protocols.(Make sure you use all lowercase letters and separate it from the existing HTTP protocol with a comma)
image
Now the service is hosted in IIS using the TCP protocol.

Understand WebMessage Format


In this post I will show how how to use WebMessageBodyStyle parameter attribute in REST Service.WebMessageBodyStyle is an enumeration that specifies whether to wrap parameter and return values.WebMessageBodyStyle contains four member.

I have listed down all the members and there discription in following table.

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

namespace RestLoginService
{

    [ServiceContract]
    public interface ILoginService
    {

        [OperationContract]
        [WebInvoke(Method = "POST",
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.Bare)]
        AuthResult Login(User user);
    }


}


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

namespace RestLoginService
{
    public class LoginService : ILoginService
    {

        public AuthResult Login(User user)
        {
            if (user.UserName == "john" && user.Password == "password")
            {
                return new AuthResult { UserName = user.UserName, IsAuthenticated = true };

            }
            return new AuthResult { UserName = user.UserName, IsAuthenticated = false };
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RestLoginService
{
   public class User
    {
        public string UserName { get; set; }
        public string Password { get; set; }
    }
}


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

namespace RestLoginService
{
    [DataContract]
    public class AuthResult
    {
        [DataMember]
        public string UserName { get; set; }
        [DataMember]
        public bool IsAuthenticated { get; set; }
    }
}

Web.Config

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

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <protocolMapping>
      <add binding="webHttpBinding" scheme="http"/>
    </protocolMapping>
    <behaviors>
      <endpointBehaviors>
        <behavior>
          <webHttp/>
        </behavior>
      </endpointBehaviors>
      <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="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

</configuration>

How to post array of hashes in wcf

In this post I will show you how to post json array hashes in wcf rest service.Before going to code snippet let's discuss some basic terminology.

What is Array of Hashes
Array of hashes is a data structure in which each record itself contains key/value pairs. Arrays of hashes are used less frequently than the other structures.Below is example of array of hashes
AoH = (
    {
       husband  => "barney",
       wife     => "betty",
       son      => "bamm bamm",
    },
    {
       husband => "george",
       wife    => "jane",
       son     => "elroy",
    },

    {
       husband => "homer",
       wife    => "marge",
       son     => "bart",
    },
  );
JSON String

When we enclosed the json data into quote then we called this string is JSON string
var jsonString='[{ "x": 10, "y": 20, "z": 30 }, { "x": 12, "y": 21, "z": 33 }, { "x": 13, "y": 23, "z": 35}]';

Object literal
When we don't enclosed string in quote then we called this as JSON object literals
var jsonObject= [{ "x": 10, "y": 20, "z": 30 }, { "x": 12, "y": 21, "z": 33 }, { "x": 13, "y": 23, "z": 35}];

For this demo I am going to use JSON.NET library.First go to nuget package manager and install json lib.After that create a simple REST service shown as below.
https://images-blogger-opensocial.googleusercontent.com/gadgets/proxy?url=http://3.bp.blogspot.com/-pxgGPGCnpAE/UfqRQKBLOMI/AAAAAAAACis/VwfcmWb2BWc/s640/newton.png&container=blogger&gadget=a&rewriteMime=image/*

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using Newtonsoft.Json;
namespace WcfService2
{

    public class Service1 : IService1
    {
        public string GetData(string value)
        {
            StringBuilder stringBuilder = new StringBuilder();
            dynamic data = JsonConvert.DeserializeObject(value);
            foreach (var item in data)
            {
                stringBuilder.Append(item.x);
            }
            return stringBuilder.ToString();
        }

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

namespace WcfService2
{

    [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        [WebInvoke(Method = "POST")]
        string GetData(string value);

    }

}

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WcfService2.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-2.0.2.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#id").click(function () {
                var d = '[{ "x": 10, "y": 20, "z": 30 }, { "x": 12, "y": 21, "z": 33 }, { "x": 13, "y": 23, "z": 35}]';
                $.ajax({
                    type: 'POST',
                    url: "http://localhost:1449/Service1.svc/GetData",
                    data: JSON.stringify(d),
                    contentType: "application/json",
                    success: function (data) {
                    },
                    complete: function () {
                    }
                });
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="button" value="S" id="id" />
    </div>
    </form>
</body>
</html>

How to stream video in asp.net using WCF rest service

In this post I will show you how to stream video in asp.net using WCF rest service.The techniques used here is as we don't know the exact content lenght of the data so we used Content-Encoding transfer encoding allows a server to maintain an HTTP persistent connection for dynamically generated content. In this case the HTTP Content-Length header cannot be used to delimit the content and the next HTTP request/response, as the content size is as yet unknown. Chunked encoding has the benefit that it is not necessary to generate the full content before writing the header, as it allows streaming of content as chunks and explicitly signaling the end of the content, making the connection available for the next HTTP request/response..
  • Open visual studio and create a simple wcf service.
  • Add a new class and add following code into it

How to read incoming and outgoing message in wcf

 

In this post,I will show you how to read outgoing and incoming message in wcf.

Create a new console application and add following assembly reference in the project

using System.ServiceModel;
using System.ServiceModel.Description;

and paste following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace WCF_MessageInspector
{
    [ServiceContract]
    public interface IHelloService
    {
        [OperationContract]
        string Greet(string name);
    }
    [ConsoleServiceBehavior]
    [ServiceBehavior]
    public class HelloService : IHelloService
    {
        public string Greet(string name)
        {
            return "Hello ," + name;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            string baseUrl = "http://localhost:12345";
            ServiceHost host = new ServiceHost(typeof(HelloService), new Uri(baseUrl));
            host.AddServiceEndpoint(typeof(IHelloService), new BasicHttpBinding(), "basic");
            // Check to see if the service host already has a ServiceMetadataBehavior
            ServiceMetadataBehavior smb = host.Description.Behaviors.Find<ServiceMetadataBehavior>();
            // If not, add one
            if (smb == null)
                smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
            host.Description.Behaviors.Add(smb);

            host.Open();
            Console.WriteLine("Service is ready");
            Console.Read();
        }
    }
}
Create a new class named  ConsoleMessageInspector and inherit it from following interfaces
IClientMessageInspector
IDispatchMessageInspector
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Channels;

namespace WCF_MessageInspector
{
    public class ConsoleMessageInspector : IClientMessageInspector, IDispatchMessageInspector
    {
        public Message CreateMessage(Message message)
        {
            MessageBuffer buffer = message.CreateBufferedCopy(Int32.MaxValue);
            var messageCopy = buffer.CreateMessage();
            Console.WriteLine(messageCopy.ToString());
            return buffer.CreateMessage();

        }
        public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
        {
            request = CreateMessage(request);
            return null;
        }

        public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            reply = CreateMessage(reply);
        }

        public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            reply = CreateMessage(reply);
        }

        public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
        {
            request = CreateMessage(request);
            return null;
        }
    }
}
Create a new class named ConsoleEndpointBehavior and inherit it from following iterface
IEndpointBehavior
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Description;

namespace WCF_MessageInspector
{
   public class ConsoleEndpointBehavior:IEndpointBehavior
    {

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

        public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
        {
            clientRuntime.MessageInspectors.Add(new ConsoleMessageInspector());
        }

        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)
        {
            endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new ConsoleMessageInspector());
        }

        public void Validate(ServiceEndpoint endpoint)
        {
            
        }
    }
}
Now it’s time to apply custom inspector to the service.For this create a new class named  ConsoleServiceBehavior and inherit it from Attribute and IServiceBehavior
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Description;

namespace WCF_MessageInspector
{
   public class ConsoleServiceBehavior:Attribute,IServiceBehavior
    {
        public void AddBindingParameters(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
        {
            
        }

        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
        {
            foreach (var item in serviceHostBase.Description.Endpoints)
            {
                item.Behaviors.Add(new ConsoleEndpointBehavior());
            }
        }

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

Create a new Project named client and add service reference

Untitled

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Client
{
    class Program
    {
        static void Main(string[] args)
        {
            Proxy.HelloServiceClient client = new Proxy.HelloServiceClient();
            Console.WriteLine(client.Greet("Bill"));
        }
    }
}

 

Run both the application,and you will show that incoming and outgoing messages are captured

 

output

Complete code

Calling cross domain wcf service using Jquery

In this post,I will show you how to call cross domain service using jquery.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.IO;
using System.ServiceModel.Web;
using System.Runtime.Serialization.Json;

namespace CorssDomainService
{
    [DataContract]
    public class Order
    {
        [DataMember]
        public int ID { get; set; }
        [DataMember]
        public DateTime OrderDate { get; set; }
        [DataMember]
        public string Name { get; set; }

    }
    [ServiceContract]
    public interface IOrderService
    {
        [OperationContract]
        [WebInvoke(Method = "GET", UriTemplate = "/",
           ResponseFormat = WebMessageFormat.Json
   )]
        string ProcessOrder();

    }
    [ServiceBehavior]
    public class OrderService : IOrderService
    {
        [OperationBehavior]
        public string ProcessOrder()
        {
            Order order = new Order
            {
                ID = 1,
                OrderDate = DateTime.Now,
                Name = "Laptop"

            };

            DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(Order));
            MemoryStream stream = new MemoryStream();
            json.WriteObject(stream, order);
            return Encoding.UTF8.GetString(stream.ToArray());

        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            ServiceHost host = new ServiceHost(typeof(OrderService));
            host.Open();
            Console.WriteLine("Service is ready");
            Console.ReadLine();
        }
    }
}
<?xml version="1.0"?>
<configuration>
  <system.serviceModel>
    <services>
      <service name="CorssDomainService.OrderService" behaviorConfiguration="serviceBehave">
        <endpoint address="rest" bindingConfiguration="crossDomain"  behaviorConfiguration="enableScriptBehaviour"
                  binding="webHttpBinding"
                  contract="CorssDomainService.IOrderService"></endpoint>
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:9090/"/>
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="serviceBehave">
          <serviceMetadata httpGetEnabled="true" httpGetUrl="mex"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="enableScriptBehaviour">
          <webHttp></webHttp>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <bindings>
      <webHttpBinding>
        <binding name="crossDomain" crossDomainScriptAccessEnabled="true"></binding>
      </webHttpBinding>
    </bindings>
  </system.serviceModel>
</configuration>
Now,create a website in visual studio,and paste following code into it
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $.getJSON("http://localhost:9090/Rest?callback=?", null, function (data) {
                alert(data);
            });

        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>

How to create self signed certificate using makecert

In this post,I will show you how to create self signed certificate for wcf application.For this,I will used the utility makecert.MakeCert.exe allows you to (for test/dev purposes) generate both a trusted root certificate and a certificate signed by that trusted root certificate for encryption purposes (also for signature purposes.


Open visual studio command prompt (Admin mode) and type following command 
    C:\cert>makecert -pe -n "CN=RootCA" -ss My -sr LocalMachine -a sha1 -sky signatu re -r "RootCA.cer"
  • -pe Marks the generated private key as exportable. This allows the private key to be included in the certificate.
  • -Specifies the subject's certificate name. This name must conform to the X.500 standard. The simplest method is to specify the name in double quotes, preceded by CN=; for example, "CN=myName".
  • -ss Specifies the subject's certificate store name that stores the output certificate.
  • sr >localmachine
  • -a Specifies the signature algorithm. Must be either 
  • -sky Specifies the subject's key type, which must be signatureexchange, or an integer that represents a provider type. By default, you can pass 1for an exchange key and 2 for a signature key.
  • -r Creates a self-signed certificate.


Above command will create a certificate named RootCA.cer in the cert directory ,and also placed this certificate into Person folder
After executing the above command do the following steps


  • Start/Run/MMC

  • File/Add-Remove Snap-In

  • Click Add


  • Select Certificates and click Add

  • Select Computer Account and hit Next

  • Select Local Computer

  • Click Close

  • Click OK
Go back to the certificates snap-in, right-click the "RootCA" certificate and copy it to the "Trusted Root Certification Authorities" node. Once done, if you expand this node, and then select certificates your newly created root cert should be present.

Now,It's time to create the server certificate.Type the following command and press enter
    C:\cert>makecert -pe -n "CN=santosh-pc" -ss My -sr LocalMachine -sky exchange -a

 sha1 -in "RootCA" -is My -ir LocalMachine -sy 12 santosh-pc.cer



How to upload/Download file from wcf service

In this post,I will show you how to stream (upload and download) data through wcfservice.


  • Create a new website
  • Right click on the website and add new wcf service named FileStream.svc
  • Open the IFileStream.cs and add following code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.IO;
[ServiceContract]
public interface IFileStream
{
    [OperationContract]
    string Upload(Stream inputStream);
    [OperationContract]
    Stream Download(string fileId);
    [OperationContract]
    string[] GetAvailableFiles();
}

Open FileStream.cs file and add following code inside it


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.IO;
using System.Web;
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service" in code, svc and config file together.
public class FileStream : IFileStream
{
    private const string FILEPATH = @"C:\temp\download";
    private string GetDirectoryPath()
    {
    return FILEPATH;
    }
    public string Upload(System.IO.Stream inputStream)
    {
    string fileID = string.Format(@"{0}\{1}.txt", GetDirectoryPath(), Guid.NewGuid().ToString());
        StreamReader reader = new StreamReader(inputStream);
    string contents = reader.ReadToEnd();
        File.WriteAllText(fileID, contents);
    return fileID;
    }
    public System.IO.Stream Download(string fileId)
    {
        MemoryStream stream = new MemoryStream();
    byte[] buffer = File.ReadAllBytes(fileId);
        stream.Write(buffer, 0, buffer.Length);
        stream.Position = 0;
    return stream;
    }
    public string[] GetAvailableFiles()
    {
    return new DirectoryInfo(GetDirectoryPath()).GetFiles().Select(x => x.FullName).ToArray();
    }
}

Now,It's time to configure the service.There are two way to configure the service.First through the code ,and second through the config file.I will followlatter approach.Open web.config and go to section and add following code

<?xml version="1.0"?>
<configuration>
    <system.web>
    <compilation debug="true" targetFramework="4.0"/>
    </system.web>
    <system.serviceModel>
    <services>
    <service behaviorConfiguration="streamServiceBehaviour" name="FileStream">
    <endpoint address="" binding="basicHttpBinding" contract="IFileStream" bindingConfiguration="streamBindingConfig"/>
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
    </service>
    </services>
    <behaviors>
    <serviceBehaviors>
    <behavior name="streamServiceBehaviour">
    <serviceDebug includeExceptionDetailInFaults="true"/>
    <serviceMetadata httpGetEnabled="true"/>
    </behavior>
    </serviceBehaviors>
    </behaviors>
    <bindings>
    <basicHttpBinding>
    <binding name="streamBindingConfig" transferMode="Streamed">
    </binding>
    </basicHttpBinding>
    </bindings>
    </system.serviceModel>
</configuration>

In the above configuration,I have used basicHttpBinding and transferMode is Streamed..

Let's consume the service.Right click on the project and add new page and add following code into it


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ServiceExample.aspx.cs" Inherits="ServiceExample" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:FileUpload ID="FileUpload1" runat="server" />
    <asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="Upload" />
    </div>
    <asp:Button ID="btnDownload" runat="server" onclick="btnDownload_Click" 
    Text="Download" />
    <asp:TextBox ID="TextBox1" runat="server" Height="235px" Width="377px"></asp:TextBox>
    </form>
</body>
</html>
using System.Collections.Generic;
using System;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class ServiceExample : System.Web.UI.Page
{
    StreamService.FileStreamClient client = new StreamService.FileStreamClient();
    string fileId = string.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
 
     fileId=client.Upload(new MemoryStream(FileUpload1.FileBytes));
     Session["fileID"] = fileId;
    }
    protected void btnDownload_Click(object sender, EventArgs e)
    {
        Stream stream = client.Download((String)Session["fileID"]);
        StreamReader reader = new StreamReader(stream);
        TextBox1.Text = reader.ReadToEnd();
    }
}

How to:Create wcf application without using config file

In this post i am going to show you how to create wcf application without using config file. Let's start the tutorial.
  • Open visual studio and create a new console application
  • Right click on the project and add reference to following assembly
        using System.ServiceModel;

  • Open Program.cs file and paste following code

[ServiceContract]
    interface IService
    {
        [OperationContract]
        string HelloWorld(string strMessage);
    }
    public class ServiceImp : IService
    {
        [OperationBehavior]
        public string HelloWorld(string strMessage)
        {
            return ("Hello " + strMessage + "!");
        }
    }

  • Now Add following code inside main method


static void Main(string[] args)
        {
            //Create a URI to serve as the base address
            Uri httpUrl = new Uri("http://localhost:8090/MyService");
            //Create ServiceHost
            ServiceHost host = new ServiceHost(typeof(ServiceImp), httpUrl);
            //Add a service endpoint
            host.AddServiceEndpoint(typeof(IService), new WSHttpBinding(), "");
            //Enable metadata exchange
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            host.Description.Behaviors.Add(smb);
            Binding mexBinding = MetadataExchangeBindings.CreateMexHttpBinding();
            //Adding metadata exchange endpoint
            host.AddServiceEndpoint(typeof(IMetadataExchange), mexBinding, "mex");
            //Start the Service
            host.Open();
            Console.WriteLine("Host is running... Press  key to stop");
            Console.ReadLine();

        }

Now press F5 and see the message.If everything is fine then you will see a message "Host is running ...Press key to stop" 


Now it's time to create Client application
  • Right click on solution and create a new console application named WcfClient
  • Open the Program.cs file and paste the following code


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

namespace WCFClient
{
    [ServiceContract]
    interface IService
    {
        [OperationContract]
        string HelloWorld(string strMessage);


    }
    class Program
    {
        static void Main(string[] args)
        {
            //Create instance of Binding
            WSHttpBinding myBinding = new WSHttpBinding();
            //Instance of Endpoint address
            EndpointAddress myEndpoint = new EndpointAddress("http://localhost:8090/MyService");
            //Create instance of channel factory
            ChannelFactory<IService> myChannelFactory = new ChannelFactory<IService>(myBinding, myEndpoint);
            // Create a channel.
            IService wcfClient = myChannelFactory.CreateChannel();

            string s = wcfClient.HelloWorld("Wcf");
            Console.WriteLine(s.ToString());
            ((IClientChannel)wcfClient).Close();
            Console.Read();

        }
    }
}







Click below to download complete source code

How to consume WCF service using JQuery

  • Create an ASP.NET Web Application (WCF service)
  • Add a new item, aspx page (Default.aspx)
  • You now have an WCF-service with .svc as extension, and that service implements an Interface. It's in the interface we'll set the attributes needed to return JSON
  • Create a class, Student as below. The attributes "DataContract" and "DataMember" must be defined for the class and the properties that would be returned through the WCF service
[DataContract]
public class Student
{
 [DataMember]
 public int StudentId { get; set; }
 [DataMember]
 public string StudentName { get; set; }
 [DataMember]
 public int Marks1 { get; set; }
 [DataMember]
 public int Marks2 { get; set; }
 [DataMember]
 public string EmailAddress { get; set; }
}
  • Now add a reference to System.ServiceModel.Web this is for WebGet Attribute
  • Add the WebGet-attribute as specified below. The BodyStyle Bare means "Both requests and responses are not wrapped" - we really want nothing more than a true JSON-response. The ResponseFormat should of course be "Json".
[ServiceContract]
public interface IService
{
 [OperationContract]
 [WebGet(UriTemplate = "NewUri/?value={value}", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
 string GetData(int value);
 [WebGet(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
 [OperationContract]
 List<Student> GetStudentList();

}
  • In web config, start with changing "wsHttpBinding" to "webHttpBinding" (we are not working with Web Services now), then add the whole section below with our self-named behavior "JsonBehavior". Now add the behaviorConfiguration="JsonBehavior" attribute to the service-tag.
<system.serviceModel>
 <services>
   <service name="Service" behaviorConfiguration="ServiceBehavior">
     <endpoint address="" binding="webHttpBinding" behaviorConfiguration="JsonBehavior" bindingConfiguration="" contract="IService"/>
   </service>
 </services>
 <behaviors>
   <endpointBehaviors>

     <behavior name="JsonBehavior">
       <webHttp />
     </behavior>
   </endpointBehaviors>
   <serviceBehaviors>
     <behavior name="ServiceBehavior">
       <!-- 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>
 </behaviors>
</system.serviceModel>
</configuration>
Here is the complete source code IService.cs
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;


[ServiceContract]
public interface IService
{
  [OperationContract]
  [WebGet(UriTemplate = "NewUri/?value={value}", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
  string GetData(int value);
  [WebGet(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
  [OperationContract]
  List<Student> GetStudentList();

}
[DataContract]
public class Student
{
  [DataMember]
  public int StudentId { get; set; }
  [DataMember]
  public string StudentName { get; set; }
  [DataMember]
  public int Marks1 { get; set; }
  [DataMember]
  public int Marks2 { get; set; }
  [DataMember]
  public string EmailAddress { get; set; }
}

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

// NOTE: If you change the class name "Service" here, you must also update the reference to "Service" in Web.config and in the associated .svc file.
public class Service : IService
{
  public string GetData(int value)
  {
      return string.Format("You entered: {0}", value);
  }
  /// <summary>
  /// Return List of student.
  /// </summary>
  /// <returns></returns>
  public List<Student> GetStudentList()
  {

      List<Student> students = new List<Student>()
         {  new Student{StudentId=1,StudentName="S#001",Marks1=10,Marks2=20,EmailAddress="student1@st.com"},
             new Student{StudentId=2,StudentName="S#002",Marks1=9,Marks2=30, EmailAddress="student2@st.com"},
             new Student{StudentId=3,StudentName="S#003",Marks1=11,Marks2=20,EmailAddress="student3@st.com"},
             new Student{StudentId=4,StudentName="S#004",Marks1=20,Marks2=30,EmailAddress="student4@st.com"},
             new Student{StudentId=5,StudentName="S#005",Marks1=9,Marks2=40,EmailAddress="student5@st.com"},
             new Student{StudentId=6,StudentName="S#006",Marks1=30,Marks2=50,EmailAddress="student6@st.com"},
         };
      return students;

  }
}
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title></title>

  <script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>

  <script type="text/javascript">
      $().ready(function() {
          $("#btnStudent").click(function() {
              $.getJSON("Service.svc/GetStudentList", function(data) {
                  BuildTable(data);
              });
          });

          $("#myButt").click(function() {
              var num = $("#name").val();
              $.getJSON("Service.svc/NewUri", { value: num }, function(data) {
                  alert(data);
              });
          });
      });
      function BuildTable(data) {
          var table = '<table><thead><tr><th>StudentID</th><th>StudentName</th><th>Marks1</th></thead><tbody>';

          $.each(data, function(i, student) {
              var row = '<tr>';
              row += '<td>' + student.StudentId + '</td>';
              row += '<td>' + student.StudentName + '</td>';
              row += '<td>' + student.Marks1 + '</td>';
              row += '</tr>';
              table += row;
          });
          table += '</tbody></table>';
          $('#Container').html(table);
      }
  </script>

</head>
<body>
  <form id="form1" runat="server">
  <div>
      <input type="button" value="Get values from server" id="myButt" />
      <input type="button" value="GetStudentList" id="btnStudent" />
      <p>
          <input type="text" id="name" value="1" /><br />
      </p>
  </div>
  <div id="Container">
  </div>
  </form>
</body>
</html>
Service.svc
<%@ ServiceHost Language="C#" Debug="true" Service="Service" CodeBehind="~/App_Code/Service.cs" %>