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

How to read namespace based xml using Linq

In this post,I will show you how to read xml with namespace.For this demo,I will use following xml

structure

<?xml version="1.0" encoding="utf-8" ?>
<accounts xmlns="urn:account">
  <account>1001</account>
  <account>1002</account>
</accounts>

 

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

namespace XLinq
{
    class Program
    {
        static void Main(string[] args)
        {
            var doc = XDocument.Load("accounts.xml");
            var query = from x in doc.Descendants("{urn:account}account")
                        select x;
            foreach (var item in query)
            {
                Console.WriteLine(item);
            }
        }
    }
}

How to send request from CURL command tool to wcf reset service

In this post,I will show you how to test your rest service from command prompt using CURL tool.
What is CURL:A command line tool for getting or sending files using URL syntax.

For this demo I have created a simple reset service which contains three method as below

Download Source Code

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


[ServiceContract(SessionMode = SessionMode.NotAllowed)]
public interface ICurlService
{
    [WebGet(UriTemplate = "date/{year}/{month}/{day}", ResponseFormat = WebMessageFormat.Xml)]
    [OperationContract]
    string GetDate(string day, string month, string year);

    [WebGet(UriTemplate = "greet", ResponseFormat = WebMessageFormat.Json)]
    [OperationContract]
    string Greeting();

    [WebInvoke(Method = "POST", UriTemplate = "submit", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
    [OperationContract]
    string Save(string data);

}
[ServiceType]

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

public class ServiceType : ICurlService
{
    public string GetDate(string day, string month, string year)
    {
        return new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), Convert.ToInt32(day)).ToString("dddd, MMMM dd, yyyy");
    }
   public string Greeting()
    {
        return "Hello World";
    }
   public string Save(string data)
   {
       return data + "Has been saved!";
   }
}

Let's send request to first method


 [WebGet(UriTemplate = "date/{year}/{month}/{day}", ResponseFormat = WebMessageFormat.Xml)]
    [OperationContract]
    string GetDate(string day, string month, string year);

Go to command prompt and type following code

curl http://localhost:12576/CurlDemo/Service.svc/date/2012/1/12

Let's send request to second method from curl



  [WebGet(UriTemplate = "greet", ResponseFormat = WebMessageFormat.Json)]
    [OperationContract]
    string Greeting();


curl http://localhost:12576/CurlDemo/Service.svc/greet

Now,let's send a post request to service from command prompt




  [WebInvoke(Method = "POST", UriTemplate = "submit", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
    [OperationContract]
    string Save(string data);


curl  -H "Content-Type: application/json" -H "Accept: application/json" -X POST -d '{"data":"dummy data"}' http://localhost:12576/CurlDemo/Service.svc/submit


How to call python generator in c#

In this post,I will show you how to call python generator in c#.Create a console Application and then right click on the project and add new file fib.py and add following code
class Fib:

    def __init__(self,num):

        self.a=0

        self.b=1

        self.num=num

        self.index=0

    def __iter__(self):

        return self

    def next(self):

        if self.index > self.num:

            raise StopIteration

        else:

            self.index +=1

            self.a,self.b=self.b,self.a+self.b

            return self.a

Open Progrm.cs and add following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Scripting.Hosting;
namespace IronPython_Tut1
{
        class Program
    {
        static void Main(string[] args)
        {
        //Create runtime
            ScriptRuntime runtime = IronPython.Hosting.Python.CreateRuntime();
        //excute 
            ScriptScope scope = runtime.ExecuteFile(@"Fib.py");
        //get the Fib object
            dynamic Fib = scope.GetVariable("Fib");
        foreach (var item in Fib(10))
            {
                Console.WriteLine(item);
            }
          
        }
    }
}


How to call python class in c#

In this post,I will show you how to call python class in c#,Create a new python class named Person.py and paste following code


class Person:
    def __init__(self,firstName,lastName,age):
        self.firstName=firstName
        self.lastName=lastName
        self.age=age
   
    def __str__(self):
        return self.firstName +","+self.lastName+","+self.age
    def get_full_name(self):
        return "%s,%s" % (self.firstName, self.lastName)
   
   


Open program.cs and add following code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Scripting.Hosting;
namespace IronPython_Tut1
{
    class Program
    {
    static void Main(string[] args)
        {
    //Create runtime
            ScriptRuntime runtime = IronPython.Hosting.Python.CreateRuntime();
    //excute 
            ScriptScope scope = runtime.ExecuteFile(@"Person.py");
    //get the Person object
            dynamic Person = scope.GetVariable("Person");
    //Create instanc of Person class.
            dynamic personObject = Person("santosh", "singh", 24);
    //call  the get_full_name method on person instancw
            Console.WriteLine(personObject.get_full_name());
            Console.ReadLine();
        }
    }
}

IronPython and C#


What is IronPython

IronPython is an open-source implementation of the Python programming language which is tightly integrated with the .Net Framework.
IronPython can use the .Net Framework and python libraries,and other .NET languaages can use Python code just as easily

In this post I will show you how to call Python method in c#.


Create a new Console application and visual studio
Right click on the project and click on Manage Nuget Packages and search for IronPython

After installing IronPython import following namespaces
using Microsoft.Scripting.Hosting;

Right click on project and add new file Calculator.py and add following python code


def add(a,b):
    return a+b

Open Program.cs file and add following code


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Scripting.Hosting;
namespace IronPython_Tut1
{
    class Program
    {
    static void Main(string[] args)
        {
    //Create runtime
            ScriptRuntime runtime = IronPython.Hosting.Python.CreateRuntime();
    //excute 
            dynamic scope = runtime.ExecuteFile(@"Calculator.py");
    //call the python method
            Console.WriteLine("Sum={0}", scope.add(1, 2));
            Console.ReadLine();
        }
    }
}