Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

Part 3 - Creating a wcf service

Suggested Videos
Part 1 - Introduction to WCF
Part 2 - Creating a remoting service and a web service

This is continuation to Part 2. Please watch Part 2 from WCF video tutorial before proceeding.



In this video, we will discuss 
1. Creating a WCF service
2. Hosting the WCF service using a console application
3. Exposing 2 service endpoints. 
4. Creating a windows and a web Client applications.



Let's take the scenario that we discussed in Part 2
We have 2 clients and we need to implement a service a for them. 
1. The first client is using a Java application to interact with our service, so for interoperability this client wants meesages to be in XML format and the protocl to be HTTP.
2. The second client uses .NET, so for better performance this client wants messages formmated in binary over TCP protocol.

In Part 2,
To meet the requirement of the first client, we implemented a web service and to meet the requirement of the second client we implemented a remoting service.

In this video, we will create a single WCF service, and configure 2 endpoints to meet the requirements of both the clients.

Creating the WCF Service:
1. Create a new Class Library Project and name it HelloService.
2. Delete Class1.cs file that is auto-generated.
3. Add a new WCF Service with name = HelloService. This should automatically generate 2 files (HelloService.cs & IHelloService.cs). Also a reference to System.ServiceModel assembly is added.
4. Copy and paste the following code in IHelloService.cs file
using System.ServiceModel;
namespace HelloService
{
    [ServiceContract(Namespace="http://PragimTech.com/ServiceVersion1")]
    public interface IHelloService
    {
        [OperationContract]
        string GetMessage(string name);
    }
}
5. Copy and paste the following code in HelloService.cs
namespace HelloService
{
    public class HelloService : IHelloService
    {
        public string GetMessage(string name)
        {
            return "Hello " + name;
        }
    }
}

That's it we are done implementing a WCF Service. The next step is to host the service using a console application. A WCF service can also be hosted in a Windows application, or Windows Service or IIS. We will discuss these hosting options in a later video session.

Hosting the WCF service using a console application.
1. Right click on HelloService solution in Solution Explorer and add a new Console Application project with name = HelloServiceHost
2. Add a reference to System.ServiceModel assembly and HelloService project
3. Right click on HelloServiceHost project and add Application Configuration File. This should add App.config file to the project. Copy and paste the following XML. Notice that we have specified 2 endpoints in the configuration. One endpoint uses basicHttpBinding, which communicates over HTTP protocol using XML messages. This endpoint will satisfy the requirement of the first client. The other endpoint uses netTcpBinding, which communicates over TCP protocol using binary messages. This endpoint will satisfy the requirement of the second client. 
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="mexBehaviour">
          <serviceMetadata httpGetEnabled="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service name="HelloService.HelloService" behaviorConfiguration="mexBehaviour">
        <endpoint address="HelloService" binding="basicHttpBinding" contract="HelloService.IHelloService">
        </endpoint>
        <endpoint address="HelloService" binding="netTcpBinding" contract="HelloService.IHelloService">
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8080/" />
            <add baseAddress="net.tcp://localhost:8090"/>
          </baseAddresses>
        </host>
      </service>
    </services>
  </system.serviceModel>
</configuration>
4. Copy and paste the following code in Program.cs file
using System;
namespace HelloServiceHost
{
    class Program
    {
        static void Main()
        {
            using(System.ServiceModel.ServiceHost host = new 
                System.ServiceModel.ServiceHost(typeof(HelloService.HelloService)))
            {
                host.Open();
                Console.WriteLine("Host started @ " + DateTime.Now.ToString());
                Console.ReadLine();
            }
        }
    }
}

Build the solution. Set HelloServiceHost as startup project and run it by pressing CTRL + F5 keys.

Now let's build a web application that is going to consume the WCF service using the endpoint with basicHttpBinding. basicHttpBinding communicates over HTTP protocol using XML messages.
1. Create a new asp.net empty web application and name it HelloWebClient
2. Right click on References folder and select Add Service Reference option. In the address textbox type http://localhost:8080/ and click on GO button. In the namespace textbox type HelloService and click OK. This should generate a proxy class to communicate with the service.
3. Add a new webform. Copy and paste the following HTML in WebForm1.aspx
<div style="font-family:Arial">
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" Text="Get Message" 
        onclick="Button1_Click" />
    <br />
    <asp:Label ID="Label1" runat="server" Font-Bold="true"></asp:Label>
</div>
4. Copy and paste the following code in WebForm1.aspx.cs file
protected void Button1_Click(object sender, EventArgs e)
{
    HelloService.HelloServiceClient client = new 
        HelloService.HelloServiceClient("BasicHttpBinding_IHelloService");
    Label1.Text = client.GetMessage(TextBox1.Text);
}

Now let's build a windows application that is going to consume the WCF service using the endpoint with netTcpBinding. netTcpBinding communicated over TCP protocol using binary messages.
1. Create a new Windows Forms application and name it HelloWindowsClient
2. Right click on References folder and select Add Service Reference option. In the address textbox type http://localhost:8080/ and click on GO button. In the namespace textbox type HelloService and click OK. This should generate a proxy class to communicate with the service.
3. On Form1, drag and drop a textbox, a button and a label control. Double click the button to generate the click event handler.
4. Copy and paste the following code in Form1.cs file
private void button1_Click(object sender, EventArgs e)
{
    HelloService.HelloServiceClient client = new 
        HelloService.HelloServiceClient("NetTcpBinding_IHelloService");
    label1.Text = client.GetMessage(textBox1.Text);
}

wcf tutorial

36 comments:

  1. hi venkat your tutorials are very good informative by interlinking , i have a doubt that what kind of other applications other than windows use tcp Bindings and why?and also heard that wcf gives more flexibility in terms of security rather than web services .thank you

    ReplyDelete

  2. Hi venkat, I am getting Error "Only one usage of each socket address (protocol/network address/port) is normally permitted" When whosting The Remoting service

    HelloRemotingService.HelloRemotingService RemotingService = new HelloRemotingService.HelloRemotingService();

    TcpChannel Channel = new TcpChannel(8080);
    ChannelServices.RegisterChannel(Channel,true);
    Plz Resolve me

    ReplyDelete
    Replies
    1. I think that port is being used by some other application. Can you try to change the port number and try.

      Delete
    2. run visual studio as administrator

      Delete
  3. th you sir. But I get this error after copy past. Please help me to solv it.
    Additional information: HTTP could not register URL http://+:8080/. Your process does not have access rights to this namespace (see http://go.microsoft.com/fwlink/?LinkId=70353 for details).

    ReplyDelete
    Replies
    1. Run Your Service Host as Administrator

      Delete
    2. how can i run in admin mode? as i am already logged as admin in windows.

      Delete
    3. run your visual studio as an administrator

      Delete
    4. right click on visual studio and run as administrator

      Delete
  4. @Elvin....chek weather your vs open in adminstrator mode or not....if not then open the vs in admin mode thats why you are getting the error ..and remember one thing side side build the project...

    ReplyDelete
  5. Could not find endpoint element with name 'NetTcpBinding_IHelloService' and contract 'HelloService.IHelloService' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this name could be found in the client element.

    When i run this in window form using tcp protocal it generate error

    ReplyDelete
  6. hi venkat, we have created two end points in your wcf session veido 3 with two address at port 8080 and 8090, since while adding the service reference to the client app we specify only one address but still why do we get both the configuration added to client config file

    ReplyDelete
  7. hi venkat, I am getting the error "Only an absolute Uri can be used as a base address."
    but when i am using only httptbinding protocol , I am getting any error please help me

    ReplyDelete
  8. Hi venkat, when i am using two binding nttp and net.tcp then i am getting the error [Only an absolute Uri can be used as a base address.] ..please suggest me

    ReplyDelete
  9. How to get an available port, bcoz I can't fine anything when I type http://localhost:8080/ in the browser.

    ReplyDelete
  10. The type initializer for 'System.ServiceModel.Diagnostics.TraceUtility' threw an exception.

    ReplyDelete
  11. hi venkat sir,
    when i m trying to add service reference in client, it is giving the error like :

    There was an error downloading 'http://localhost:8080/'.
    Unable to connect to the remote server
    No connection could be made because the target machine actively refused it 127.0.0.1:8081
    Metadata contains a reference that cannot be resolved: 'http://localhost:8081/test1'.
    There was no endpoint listening at http://localhost:8081/test1 that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.
    Unable to connect to the remote server
    No connection could be made because the target machine actively refused it 127.0.0.1:8081
    If the service is defined in the current solution, try building the solution and adding the service reference again.

    Please help me how can i solve above error

    ReplyDelete
  12. Hi sir, i am new to WCF.

    in this part 3[creating a wcf service], how do i know the WSDL http url.

    For ex : You have given http url in baseaddress section. May i know how to get that path in wcf service.

    Suppose If i have used web services, then i can get the wsdl url while pressing F5 it will generate web services screen to test the functions.

    ReplyDelete
  13. Hello Venkat...

    I am getting below error when i try to open Service host.

    using (ServiceHost host = new ServiceHost(typeof(HelloService.HelloService)))
    {
    host.Open();

    Console.ReadLine();

    Service 'HelloService.HelloService' has zero application (non-infrastructure) endpoints. This might be because no configuration file was found for your application, or because no service element matching the service name could be found in the configuration file, or because no endpoints were defined in the service element.

    Any help...

    ReplyDelete
  14. I was getting the below error:
    Service 'HelloService.HelloService' has zero application (non-infrastructure) endpoints. This might be because no configuration file was found for your application, or because no service element matching the service name could be found in the configuration file, or because no endpoints were defined in the service element.

    I resolved it by adding the namespace to the service name in app.config file

    ReplyDelete
    Replies
    1. where exactly did u define a namespace in App.cfg file?

      Delete
  15. Error:-HTTP could not register URL http://+:8080/. Your process does not have access rights to this namespace (see http://go.microsoft.com/fwlink/?LinkId=70353 for details).
    How to register this url, Please anybody help.

    ReplyDelete
    Replies
    1. hi manish;
      please let us know if your problem is resolved; and share us the solution;
      thnaks
      Arun

      Delete
  16. Hi Venkat;

    My app is throwing this error message; could not come out of it, [ i thought by changing port number would resolve my problem but not]

    {"HTTP could not register URL http://+:8090/. Your process does not have access rights to this namespace (see http://go.microsoft.com/fwlink/?LinkId=70353 for details)."}

    Could you provide me a solution on this;

    thanks;
    Arun

    ReplyDelete
  17. right click on visual studio and run as administrator

    ReplyDelete
  18. How do we call a wcf web service by http web request??

    ReplyDelete
  19. Where can we find the source code of the tutorial?

    ReplyDelete
  20. Hello Sir,
    I am not able to browse WSDL in browser. I am getting 404/page not available for http://localhost:8080/
    But when I debug the console application WCF service connection is open and service is running and I can see those 2 base url under baseAddresses property in host object.
    As WCF service is not hosted or not available on that port I can't add service reference of WCF service to any project.

    Please suggest

    ReplyDelete
    Replies
    1. Try to open Visual studio as an administrator " Run as Administrator"...I hope this will work.

      Delete
    2. I tried to run as Administrator, even though getting same error

      Delete
  21. Hai

    In the above Example "HelloService" WCF service is created but there is no end points for that services.we create end points in console application not WCF service how is it possible. with out endpoints how to communicate to WCF Services

    ReplyDelete
  22. I AM not able to get get the wsdl in the browser.instead i am getting svcutil.exe http://localhost:50918/mex what should i do.

    ReplyDelete
  23. I have a question, in both the project we have added service reference to the projects but what about android how can I added service reference to the android project.

    ReplyDelete
  24. Hi Venkat, I am getting following exception on ServiceHost object creation.
    "Could not find a base address that matches scheme http for the endpoint with binding BasicHttpBinding. Registered base address schemes are []."
    please advice

    ReplyDelete
  25. Hello everyone

    I am not getting intellisense in app.config. How to get intellisense while typing in app.config?

    ReplyDelete

If you like this website, please share with your friends on facebook and Google+ and recommend us on google using the g+1 button on the top right hand corner.