WCF by example on netNamedPipeBinding

netNamedPipeBinding is the best binding for interprocess communication which crosses process boundaries on the same machine.

With netNamedPipeBinding the security can be achieved only through transport level security as it does not support message level security. However, messages are secured as only the same machine can call the service operations.

The reason netNamedPipeBinding is the best binding because it gives you the default security and best possible performance boost. To test the performance of netNamedPipeBinding we called the below service code in a loop for 10 seconds from client console application using different bindings. See When to use which WCF binding

    
public string WelcomeGuest(string guestName)
{
    return "Welcome " + guestName; 
}
            
     

Here is the Client Code that calls above WCF Operation.

    
int i = 0; 
DateTime n = DateTime.Now;

while((DateTime.Now.Second - n.Second) <= 10)
{
i++;
Console.WriteLine(Service.WelcomeGuest("ABC")); 
}

Console.WriteLine(i.ToString());  
    
     

And below is amazing statistics.

WSDualHttpBinding best for duplex contracts, executed for 1823 times.

WSHttpBinding best when addressing WS-* specifications, executed for 2797 times.

BasicHttpBinding best when you just want to convert your ASMX web services to WCF, executed for 18974 times.

NetTcpBinding best when clients are only from the intranet, executed for 41457 times.

NetNamedPipeBinding processed for 49789 times.

Step by step implementation of WCF service using netNamedPipeBinding

  1. Create a WCF Service library

    We will start with Create a new WCF service library and test using WCFTestClient. This article will give you basic service implementation.

  2. Add Customer ServiceContract

    Add new ServiceContract by right click on NorthwindServices service library project -> Select New Item -> Select Interface -> Name it as ICustomer.

                
    namespace NorthwindServices
    {
        [ServiceContract]
        public interface ICustomer
        {
    
        }
    }           
               
  3. Add OperationContracts

    Add a reference to System.ServiceModel. Add OperationContract for Customer Service. The operation contract GetCustomerName and GetCustomerCount can be called by service clients.

                
    namespace NorthwindServices
    {
        [ServiceContract] 
        public interface ICustomer
        {
            [OperationContract]
            string GetCustomerName(int CustomerID);
    
            [OperationContract]
            int GetCustomerCount();
        }
    }
                
  4. Customer DataAccess using XML file

    We will use an XML file as Customer data store. Create a new XML and add below elements to it.

                
        <?xml version="1.0" standalone="yes"?>
        <DocumentElement>
          <Customer>
            <CustomerID>1</CustomerID>
            <CompanyName>Let's Stop N Shop</CompanyName>
            <City>Mumbai</City>
          </Customer>
          <Customer>
            <CustomerID>2</CustomerID>
            <CompanyName>Hungry Coyote Import Store</CompanyName>
            <City>Mumbai</City>
          </Customer>
          <Customer>
            <CustomerID>3</CustomerID>
            <CompanyName>John Steel</CompanyName>
            <City>Pune</City>
          </Customer>
          <Customer>
            <CustomerID>4</CustomerID>
            <CompanyName>Andy's Seasoning</CompanyName>
            <City>Delhi</City>
          </Customer>
          <Customer>
            <CustomerID>5</CustomerID>
            <CompanyName>Kountry Store</CompanyName>
            <City>Pune</City>
          </Customer>
        </DocumentElement>
                        
                
  5. Implement ICustomer ServiceContract

    Implement the interface ICustomer and add business logic to the operation contracts.

    The OperationContract GetCustomerName will return the CompanyName based on CustomerID from Customers.xml

    The OperationContract GetCustomerCount will return the total number of Customers from Customers.xml

                
    namespace NorthwindServices
    {
        public class CustomerService : ICustomer
        {
            public string GetCustomerName(int CustomerID)
            {
                XDocument doc = XDocument.Load("C:\\Customers.xml");
    
                string companyName =
                    (from result in doc.Descendants("DocumentElement")
                    .Descendants("Customer")
                        where result.Element("CustomerID").Value 
                            == CustomerID.ToString()
                        select result.Element("CompanyName").Value)
                    .FirstOrDefault<string>();
    
                return companyName;
            }
    
            public int GetCustomerCount()
            {
                XDocument doc = XDocument.Load("C:\\Customers.xml");
    
                return doc.Descendants("Customer").Count();   
            }
        }
    }
            
  6. Service Endpoint

    Open NorthwindServices wcf service library's app.config file. Add service endpoint for customer service under <system.serviceModel><services> tag.

    Note that the address we are using is with net.pipe://localhost/

    If you are using only one endpoint with netNamedPipeBinding for service mark the httpGetEnabled as false from respective serviceBehaviors.

                
        <system.serviceModel>
        <services>
          <service
               name="NorthwindServices.CustomerService"
               behaviorConfiguration="ServiceBehavior">
    
            <host>
              <baseAddresses>
                <add baseAddress="net.pipe://localhost/NorthwindServices/" />
              </baseAddresses>
            </host>
    
            <endpoint address="CustomerService"
                      binding="netNamedPipeBinding"
                      contract="NorthwindServices.ICustomer" />
            
            <endpoint address="CustomerService/mex"
                      binding="mexNamedPipeBinding"
                      contract="IMetadataExchange" />
            
          </service>
        </services>
        
        <behaviors>
          <serviceBehaviors>
            <behavior name="ServiceBehavior">
              <serviceMetadata httpGetEnabled="False"  />
              <serviceDebug includeExceptionDetailInFaults="False" />
            </behavior>
          </serviceBehaviors>
        </behaviors>
        </system.serviceModel>
                
                        
  7. Host Customer Service in Windows Service Or in IIS

    Go through the article hosting WCF service in Windows service to host your Customer Service in windows services.

    The <system.serviceModel> tag of app.config file from Windows service should be the same as the tag from the WCF service library application.

    For hosting it in IIS check the article hosting wcf service with nettcpbinding or netnamedpipebinding in IIS

    So you will have to add host for CustomerService and its endpoint details in Windows service application as there are for ProductService. Add the endpoint with net.pipe://localhost/ just like you added in NorthwindServices.

  8. WCF CustomerService reference to the client application

    Create a client application as suggested in the previous step. Add a service reference to the customer service by right click on client application -> Add Service Reference.

    Add WCF service reference for NetNamedPipeBindings

  9. Execute CustomerService

    Write the below code in client application to execute Service operations.

                
    class Program
    {
        static void Main(string[] args)
        {
            int customerID = 2;
            CustomerClient client = new CustomerClient();
            string companyName = client.GetCustomerName(2);
            Console.WriteLine(string.Format("Company name for Customer ID {0} is {1}",
                    customerID,  companyName));
            Console.WriteLine(string.Format("Total number of customers are {0} : ", 
                client.GetCustomerCount()));
            Console.Read();
        }
    }
        

    And below is the output

    Output for WCF service with NetNamedPipeBindings


Quick Note : While using code from this article make sure you mention the right path for Customers.xml

Source code on Git hub Source Code on Github

Speak your mind
Please login to post your comment!


Blog Search





If you like my content please feel free to buy me coffee. Buy Me A Coffee