Inspecting Messages in WCF

In WCF (Windows Communication foundation)  you can inpect the messages before sending reply and recieves client request through IDispatchMessageInspector interface. This helps the developer to investigate the message and log somewhere when needed.

In this post i will show the way of implementing IDispatchMessageInspector interface and how it can be applied in the custom behavior extension and configured for that Service behavior.

First of all you have to create a Message inspector class and implement the interface i.e. IDispatchMessageInspector. IDispatchMessageInspector interface provides two methods namely AfterReceiveRequest and BeforeSendReply which you can implement in the implementor class and inspect the messages. As the method named AfterRecieveRequest is called when the request came from the client and BeforeSendReply is called before the service sends the message back to client.

Below code snippet shows the class that implements IDispatchMessageInspector interface

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Channels;
using System.ServiceModel.Configuration;
using System.ServiceModel.Description;
using System.Diagnostics.Eventing;
namespace WCFMain
{
    public class MessageInspector :  IDispatchMessageInspector
    {
        public object AfterReceiveRequest(ref Message request, 
          System.ServiceModel.IClientChannel channel, 
          System.ServiceModel.InstanceContext instanceContext)
        {
            Logger.WriteLogEntry("Inside the AfterRecieveRequest");
            return null;
        }

        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            Logger.WriteLogEntry("Inside Before Send Reply");
        }
    }
}

Inorder to add this Message Inpector we have to create a custom behavior extension class that derived from BehaviorExtensionElement and implements either IServiceBehavior or IEndpointBehavior. In WCF you can either add behavior at Service level or Endpoint level. In this example i will implement IServiceBehavior.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Channels;
using System.ServiceModel.Configuration;
using System.ServiceModel.Description;
namespace WCFMain
{
    public class MessageBehaviourExtension : BehaviorExtensionElement, IServiceBehavior
    {

        public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
            Logger.WriteLogEntry("Inside the ApplyClientBehavior");
        }

        public override Type BehaviorType
        {
            get { return typeof(MessageBehaviourExtension); }
        }

        protected override object CreateBehavior()
        {
            return this;
        }

        public void AddBindingParameters(ServiceDescription serviceDescription, 
         System.ServiceModel.ServiceHostBase serviceHostBase, 
         System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, 
         BindingParameterCollection bindingParameters)
        {
            Logger.WriteLogEntry("Inside the AddBindingParameters");
        }

        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, 
         System.ServiceModel.ServiceHostBase serviceHostBase)
        {
            Logger.WriteLogEntry("Inside Apply Dispatch Behavior");
            for (int i = 0; i < serviceHostBase.ChannelDispatchers.Count; i++)
            {
                ChannelDispatcher channelDispatcher = serviceHostBase.ChannelDispatchers[i] as ChannelDispatcher;
                if (channelDispatcher != null)
                {
                    foreach (EndpointDispatcher endpointDispatcher in channelDispatcher.Endpoints)
                    {
                        MessageInspector inspector = new MessageInspector();
                        endpointDispatcher.DispatchRuntime.MessageInspectors.Add(inspector);
                    }
                }
            }
        }

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

        }
    }
}

In the above snippet if you see that i have add the custom message inspector object for each endpoints defined for the service. So when the WCF engine calls this method it will add the message inspector for all endpoints defined in the service configuration.

Now, in the web.config file at server side you have to add following entries to configure this custom behavior extension and specify in the service behavior.

WPF Data Binding Options

In this post i will show the different ways of binding WPF control elements with the different sources. WPF provides binding both declarative and imperatively through code. It provides greater flexibility to the developer to bind the target value to source value in the XAML file.

The term data binding describes the process of creating a dependence for the value of one property i.e. the target property to the source property. The target property takes on the value of the source property. In some cases, changes to the source property are transmitted to the target immediately, but in some cases, they are not.

Following are the types of bindings that are the part of this post and mostly used in WPF applications.

1. Binding target value to WPF element.
2. Binding to an Object
3. Binding to Ancestor properties through RelativeSource property.
4. Binding to Data Sources
5. Binding to an Object with ObjectDataProvider

1. Binding Target value to WPF Element:
This type of binding used when you want to bind the target property to any WPF element (control) property. For e.g. you want to bind the Textbox text to the label Content property. When the user write in the textbox it should reflect the change in the label control. In this case, you add a textbox and a label controls in the WPF form. And specify the binding as follows.

Above code snippet shows the binding of Label Content target property with the Textbox Text source property. Now when you run the application and write something on textbox it will directly reflect the changes on the Label.

2. Binding to an Object
When binding to an Object we use Source property to specify the source object. For binding with object, in the Window.Resources tag user has to specify the Resource object. Below code snippet shows the way of binding an Object property with the resource object.

The above code snippet binds the StaticResource to the personObj which was defined in the Window.Resources tag and Path specified the property which holds the value. Now when run the application it will bind the TextBlock text value with the property value. When the form loads it initialize an object and fill the value obtained from that object property. If you want to pull data from some other datasource at runtime then you don’t need to specify the Binding Source property and only have to specify the Path property and in the code behind bind the TextBlock text source to that object value.

You can also specify the StaticResource binding property over Grid level or at container level. So you don’t need to specify the static resource property on every control bindings. All the controls that come under that container will use that datasource. But you need to specify the path which maps the property to that object property. Following snippet shows the way of binding through DataContext property at Container level.

3. Binding to Ancestor properties through RelativeSource property
Using the RelativeSource attribute in the binding you can bind the source to the ancestor property value. For example you have specified the Tag attribute in the Grid container. And you want to bind the Tag property in the Textbox control that comes under grid container. You can do that by using RelativeSource property. Following code snippet shows the way of binding to ancestor properites through RelativeSource property.

4. Binding to Data Sources

This is when you want to bind the Collection controls like Listbox etc. with different datasources.ListBox in WPF contains an ItemSource property which helps to bind the datasource. Normally in business application collection retrieves from database. So you dont need to specify the Source property in the Listbox ItemsSource property and just specify the Binding keyword followed with the DisplayMemberPath which is used to map the object property retrieved from the Collection to the control display item property.

Following code snippet shows the binding.

5. Binding to an Object with ObjectDataProvider

Using ObjectDataProvider class you can bind a WPF element to a method called on an object. You can specify an object type and a method on that type. WPF also provides an option to bind methods that have parameters in its signature and  user can define the method parameters declaratively in XAML with their default values.

Below code snippet shows the way of binding method that contains no parameters in its signature.

In the code above first i created a method named GetText which return some string. And then I have specified the ObjectDataProvider tag and reference it in the TextBlock.

Below code snippet shows the way of binding method that contains two parameters in its signature.

Define method.

Specify ObjectDataProvider in the XAML.

When run the Application and enter the data in two textboxes, the Concat method takes the values from those textboxes and bind the returned concatenated string with the TextBlock as shown below.

Consuming WCF Service in WP7

In this post i will show you the very basic way of calling WCF service in WP7 application and persisting the service url in the isolated storage of mobile. In WCF there are two modes to configure endpoints i.e. Imperative and Declarative. Imperative means developer can configure the endpoints through code whereas in the declarative mode, it is configure in the configuration file.

Whats the problem?
We came to the question that suppose we have provided a WP7 application to one of our client. And that application consumes some WCF service. Suppose the service endpoint address is changed, now how can the client configure the endpoint address on his mobile/device.

Every mobile has their persistence storage media. And each application gets the quota where you can store some configuration settings or data to utilize where applicable. In WP7 there is a class called IsolatedStorage through which developer can get an access to the Application store.

Below i have shown a way to use the Isolated Storage and consume WCF service from WP7 mobile application.

Requirements: WP7 SDK, Visual Studio 2010.

Steps:
1. Open Visual Studio and create a new project of “Windows Phone Application”

2. Add another WCF Service Application Project.

3. Open the WP7 project and in the MainPage.xaml form add two textboxes for defining Server Name and Port, add a button to get the data from WCF service and the textbox to display the Service result.

4. Open the Service Application project and define operation contract named GetData as shown below.

namespace TestService
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
[ServiceContract]
public interface ITestService
{

[OperationContract]
string GetData();
}
}

namespace TestService
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
public class WCFTestService : ITestService
{
public string GetData()
{
return "Hello world!";
}

}
}

5. Add reference to this service in WP7 project

6. Now in the Button click event we need to call the service, following snippet shows the way to store the Server name and port in the isolated storage of mobile device and consume the service.

private void btn_Click(object sender, RoutedEventArgs e)
{
String strUrl = "http://" + txtServerName.Text + ":" + txtPort.Text + "/WCFTestService.svc";

IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();
if (file.FileExists("Sources.res"))
{
file.DeleteFile("Sources.res");

}
IsolatedStorageFileStream fs = file.CreateFile("Sources.res");
System.IO.StreamWriter writer = new System.IO.StreamWriter(fs);
writer.Write(strUrl);
writer.Close();
fs.Close();
fs.Dispose();

System.ServiceModel.EndpointAddress epa = new System.ServiceModel.EndpointAddress(strUrl);
Services.TestService.TestServiceClient client = new Services.TestService.TestServiceClient("BasicHttpBinding_ITestService", epa);
client.GetDataCompleted += new EventHandler(client_GetDataCompleted);
client.GetDataAsync();
}


void client_GetDataCompleted(object sender, Services.TestService.GetDataCompletedEventArgs e)
{
textBox3.Text = e.Result;
}

7. In the MainPage constructor add following snippet to read the Server Name and Port from the isolated saved earlier.

// Constructor
public MainPage()
{
InitializeComponent();
IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();
string[] strArr=file.GetFileNames();
if (file.FileExists("Sources.res"))
{
IsolatedStorageFileStream fs = file.OpenFile("Sources.res", System.IO.FileMode.Open);
System.IO.StreamReader reader = new System.IO.StreamReader(fs);
String str = reader.ReadLine();
textBox1.Text = str.Substring(str.IndexOf("/") + 2, str.LastIndexOf(":") - 1 - str.IndexOf("/") - 1);
textBox2.Text = str.Substring(str.LastIndexOf(":") + 1, 4);
reader.Close();
fs.Close();
fs.Dispose();
}
}

Now run the application, specify the Server Name and Port and then click on the Retrieve Service Data button.

Using Facebook SDK in Desktop Application C#.Net

This post shows the basic way of using Facebook SDK C#.Net in Desktop/Windows based application to authenticate user and enable developers to access the complete data of the logged in user.

First of all developer has to create an application in http://www.facebook.com/developers. This is very simple and can be done in seconds. Following are some basic steps.

1. Login http://www.facebook.com/developers

2. Click on a link named as “Set Up New App”.

3. Specify Application Name, in my case its “Test”. Click on ‘Create App”.

4. Once the application is created select the “Website” tab and note the “Application Key”. This Application Key will be used to connect to the Application using Facebook SDK.

Now we have configured and created an application and perform different operations from our desktop application. Following are the steps to develop a basic desktop application that authenticate user and populates his full name and gender in the text fields.

First of all download the provided at CodePlex forum.

1. Open Visual Studio

2. Create Windows Application

3. Download the Facebook Developer SDK from Facebook Developer SDK and add References to the Facebook Developer Kit, through NuGet (gives you an option to reference third party library packages) or add Facebook.dll and Facebook.WinForms.dll manually.

4. Open Visual Studio and Create a new tab in Toolbox section e.g. “Facebook Control” and click on “Choose Items” and browse the “Facebook.Winforms.dll” file.

5. On selection, It will show the list of controls embedded in that assembly, just click on Ok to add it in your IDE toolbox section.

6. Now drag and drop the FacebookService as shown below.

7. Add a button that performs Authentication first, and then get the User details. Also place two text boxes.

8. Now set the Application Key in the Application Key property of FacebookService control as shown below.

9. Now in the button click event place following snippet that connects to facebook and displays the username and email address on the form.

facebookService1.ConnectToFacebook();
txtUserName.Text = facebookService1.Users.GetInfo().first_name + " " + facebookService1.Users.GetInfo().last_name ;
txtGender.Text = facebookService1.Users.GetInfo().sex;

10. Now when run the application and click on the “Connect to Facebook” button it will show the Facebook login screen, enter valid username and password.

11. On Authentication, it will prompt to allow/don’t allow to use Facebook from Test application. Click Allow.

12. Then it will display the user name and gender of the logged in user.

You can also get friend list, update status, retrieve photos, and bunch of more operation that are provided in the SDK.