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

Tuesday, January 24, 2012

Reading and Updating WCF Configuration file

It had been very long since I had blogged. I had a peculiar requirement where I needed to parse the configuration of a WCF Service. that is the <System.ServiceModel> tag in the configuration file.
I finally came to know that there was a dedicated  namespace System.ServiceModel.Configuration,
Following is code that helps read and update the configuration file

 using system.ServiceModel;
 using system.ServiceModel.Configuration;

Configuration c = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

//Read the Service Model Tag
ServiceModelSectionGroup SvCGroup =      System.ServiceModel.Configuration.ServiceModelSectionGroup.GetSectionGroup(c);

//get the count of the number of Services and the service Model
Console.WriteLine("Number of Services: " + SvCGroup.Services.Services.Count);
Console.WriteLine("Number of ServiceBehaviours: " + SvCGroup.Behaviors.ServiceBehaviors.Count);

//iterate through the services in the config file
foreach (ServiceElement ele in SvCGroup.Services.Services)
{

       //Name of the Service
    Console.WriteLine("Service Name -" + ele.Name);
               

     //The Host Tag
     HostElement hele = ele.Host;
        
        //iterate through the list of base addresses
     foreach (BaseAddressElement belement in hele.BaseAddresses)
     {
       Console.WriteLine(" Base Address -" + belement.BaseAddress);
     }

   
       //get the endpoint details
  foreach (ServiceEndpointElement sep in ele.Endpoints)
    {
     Console.WriteLine("------Endpoint -----------");
     Console.WriteLine("Address -" + sep.Address.ToString());
     Console.WriteLine("Binding -" + sep.Binding.ToString());
     Console.WriteLine("Contract -" + sep.Contract);
     Console.WriteLine("Changing Contract to IService2");
     sep.Contract = "IService2";
     Console.WriteLine("DNS -: " + sep.Identity.Dns.Value);
     Console.WriteLine();

     }
}
      // get the list of ServiceBehaviour elements
foreach (ServiceBehaviorElement behavelement in SvCGroup.Behaviors.ServiceBehaviors)
{

       Console.WriteLine("-------------ServiceBehaviour--------------");         
       foreach (BehaviorExtensionElement extele in behavelement)
          {
              

                 //get the service metadata element
        if (extele is ServiceMetadataPublishingElement)
          {

     Console.WriteLine("---------------------------MetaData Behaviour------------------");
    ServiceMetadataPublishingElement behaviour1 = extele as ServiceMetadataPublishingElement;
    Console.WriteLine("Behaviour Name: " + behaviour1.ConfigurationElementName);
    Console.WriteLine("Property HttpGetEnabled: " + behaviour1.HttpGetEnabled);

     }

}

you can also set back the properties and call the configuration.Save(); to change the config file
 c.SaveAs("ConsoleApplication1.exe.config", ConfigurationSaveMode.Modified);
 this saves on the modified parts of the configuration class. how ever 2 other overloads are    provided.



          

Sunday, November 27, 2011

Extending ClientBase to Create a WCF Service Proxy

I was trying to explore different ways of creating a proxy to use the service. I knew 3 ways to doing it
1.using SVCUtil.exe
2.using Add Service Reference
3.using ChannelFactory<T> and DuplexChannelFactory<T> classes
As and when I explored that we could also create a proxy by using a wonderful class ClientBase<T>
Here are the steps I followed to create a Proxy using ClientBase<T>
1.Created a Sample service and Hosted in IIS
2.Copy the Service Interface to Client Code
3.Extend the ClientBase<T>
4. Create the proxy in the client and use

1.The Service Interface is as follows
[ServiceContract]
    public interface IService1
    {

        [OperationContract]
        string GetData(int value);


        // TODO: Add your service operations here
    }


The Implementation is as follows
  public class Service1 : IService1
    {
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

    
    }


2. I copied the Service interface  to the Client Code
3. Extended the ClientBase<T> as Follow
    
    class ServiceClient:ClientBase<IService1>,IService1
    {

        public ServiceClient(BasicHttpBinding binding, EndpointAddress address
            ):base(binding,address)
        {

        }
        protected override IService1  CreateChannel()
{
        return base.CreateChannel();
}
   
public string  GetData(int value)
{
       return base.Channel.GetData(value); 
}
}
}


4.We can Invoke the custom handcoded proxy as follows
class Program
    {
        static void Main(string[] args)
        {
            ServiceClient client = new ServiceClient(new BasicHttpBinding(BasicHttpSecurityMode.None), new EndpointAddress("http://mycomputer:61468/Service1.svc"));
            Console.WriteLine(client.GetData(10));
            Console.ReadLine();
        }
    }



Sunday, October 2, 2011

Use of MSMQ Binding provided by WCF.For Centralized Reliable logging Mechanism.




Msmq Binding is used to communicate to the Service using Microsoft Message Queuing. I have used this binding for transferring log messages. This way we can build a centralised logging system.
For this I followed the steps mentioned below

   1.   Installed Microsoft Message Queuing
   2.   Create a message Queue with Transaction Enabled
   3.   Create a Service


    [ServiceContract]
    public interface ILogService
    {


        [OperationContract(IsOneWay =true )]
        void Log(string Message);


    } 


  Note:if we use NetMsmqBinding we have to mark all operations with in the service contract as OneWay.


  4.Define the implementation


public class MathService:ILogService
    {


        public void Log(string message)
        {


            File.AppendAllText(@"C:\logFolder\AppMessages.txt", message +      Environment.NewLine);


           
        }


    }
  5.Host the Service I have used Self Hosting.




            //Address of the message Queue in the machine -
            // use public with active directory installation
            // in case of Active directory integration . other machines can also access
            // the Queue
            Uri uri = new Uri(@"net.msmq:\\mycomputer\private\testQueue");
         
            //Create Msmq binding with impersonate
            // you may need need to do some thing more if you desire security
            NetMsmqBinding messageQueueBinding = new NetMsmqBinding(NetMsmqSecurityMode .None);


            ServiceHost host = new ServiceHost(typeof(ILogService), uri);
            host.AddServiceEndpoint(typeof(ILogService), messageQueueBinding,uri .AbsoluteUri  );


            //host the WCF Service
            host.Open();




6.Design a Logging Client Application I have used Simple Console Application to demonstrate the same.


class Program
    {
        static void Main(string[] args)
        {


            Uri uri = new Uri ("net.msmq:\\mycomputer\private\testQueue");
            EndpointAddress  address = new EndpointAddress (uri.AbsoluteUri );
            NetMsmqBinding binding =new NetMsmqBinding (NetMsmqSecurityMode.None );
            ChannelFactory <ILogService> SerChannel = new ChannelFactory<ILogService> (binding ,address );
           
            ILogService client = SerChannel.CreateChannel ();
            client.Log (" This is a log message");
            Console.ReadLine ();
        }
    }