Client Additional Parameters using Custom Headers in WCF

When building Service communication applications using Windows Communication Foundation, we often come to a situation where we have multiple clients communicating with WCF Service and we need to pass additional parameters from client to service. This may be due to number of reasons such as sharing a unique customer ID to identify certain elements for that particular client. In such scenarios, for every communication between client and server, you need this unique ID to treat each client accordingly.

Client-Server-Customer-Id-Parameter-WCF

In a typical disconnected environment over the internet you need to pass such data on each call to service and of course passing in each Service Method or Operation Call is confusing and not appropriate.

A good Solution is to pass additional parameters in SOAP headers utilizing with the help of Custom headers in WCF. A SOAP envelope contains a header and a body. Method call and its parameters are transformed to SOAP body whereas SOAP header usually contains application-specific information (like authentication etc.)

 image

A simple way to achieve this in WCF is to add MessageHeader in your proxy class as in code snippet below:

public partial class TestServiceClient : ClientBase<Client.ServiceProxy.ITestService>, Client.ServiceProxy.ITestService
{
    public TestServiceClient()
    {
        var header = new MessageHeader<string>("Customer Unique Id: 12345");
        var untyped = header.GetUntypedHeader("Identity", "http://www.adilmughal.com");
        OperationContext.Current.OutgoingMessageHeaders.Add(untyped);
    } 
    //Other constructors and Service Method Calls
}

However this is really NOT a suitable approach as if you would be generating proxy using svcutil.exe or using Visual Studio then it will replace your proxy code.

A Better Solution to solve this problem is to utilize custom behavior extension in WCF to pass additional parameters in SOAP Message header. Following are the steps required on client:

1) Implement IClientMessageInspector to create custom message inspector

public class MyMessageInspector : IClientMessageInspector
{
    public void AfterReceiveReply(ref Message reply,object correlationState)
    {
       Console.WriteLine("SOAP Response: {0}", reply.ToString());
    }
        
    public object BeforeSendRequest(ref Message request,IClientChannel channel)
    {
       var header = new MessageHeader<string>("Customer Unique Id: 12345");
       var untyped = header.GetUntypedHeader("Identity", "http://www.adilmughal.com");
       request.Headers.Add(untyped);Console.WriteLine("SOAP Request: {0}", request.ToString());
       return null;
    } 
}

2) Create a custom behavior class implementing IEndPointBehavior and BehaviorExtensionElement. Then add the custom message inspector in runtime in ApplyClientBehavior method as shown in code snippet below:

public class CustomBehavior : BehaviorExtensionElement, IEndpointBehavior
{
    public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
    {
    }

    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
        clientRuntime.MessageInspectors.Add(new MyMessageInspector());
    }

    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
    {
    }

    public void Validate(ServiceEndpoint endpoint)
    {
    }

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

    protected override object CreateBehavior()
    {
        return new CustomBehavior();
    }
}

3) Finally, register behavior in .config under

<behaviors>
 <endpointBehaviors>
 <behavior>
 <customInspector />
 </behavior>
 </endpointBehaviors>
</behaviors>
<extensions>
 <behaviorExtensions>
 <add name="customInspector" type="Client.CustomBehavior, Client, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
 </behaviorExtensions>
</extensions>

That is all you have to do on client end to pass additional parameter in SOAP header using Custom Behavior in WCF.

To retrieve parameter passed in header on server side, you need to use OperationContext object

MessageHeaders headers = OperationContext.Current.IncomingMessageHeaders;
string customParameter = headers.GetHeader&lt;string&gt;("Identity", "http://www.adilmughal.com");
return string.Format("You entered: {0}", customParameter);

This would achieve the objective. Following is the detail of SOAP Envelope:

SOAP Request:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Header>
<Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://tempuri.org/ITestService/GetDataAction>
<Identity xmlns="http://www.adilmughal.com">Customer Unique Id: 12345Identity>
s:Header>
<s:Body>
<GetData xmlns="http://tempuri.org/">
<value>123value>
GetData>
s:Body>
SOAP Response:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Header />
<s:Body>
<GetDataResponse xmlns="http://tempuri.org/">
<GetDataResult>You entered: Customer Unique Id: 12345GetDataResult>
GetDataResponse>
s:Body>
s:Envelope>

In this post we saw how to create custom SOAP header in WCF to pass parameter from client to server using WCF behavior extension. Hope this helps.




As A Good Technical Lead

/* DISCLAIMER: This blog post is purely based on my personal observation and experience. The views expressed are mine alone */
Whether you call it Technical Lead or Dev Lead or Team Lead or Lead Programmer, this blog post is about the role and some of the characteristics Good Technical Lead must have.

A Central Role

Trust me, Dear Reader, if you are a technical lead or in a similar role you really have a central and significant position in the overall software development life cycle. Being the owner of the technical solution, your job is to ensure the smooth execution of development activities at least till the project is handed over for production.

 You are not only face to the management but also a bridge between different groups such as software developers, architects, Testers, End users etc. You are also responsible for compliance of standards such as coding and design standards.
However, a reality is that this job role is more towards management and less towards technical.
As a Good Technical Lead…
 
To discuss the must have attributes of a good technical lead, let’s divide the title “Technical Lead” into two areas:
  • Technology
  • Leadership

Technology

Know the every bit of the solution you are working on. Dive deep and understand the big picture of the technical solution and the customers’ need. This will help you contribute not only in the features/functionality proposed but also you will be able to guide developers in a better way.
Okay you neither have time in hand nor cost, the only thing you have in your hand is project/feature scope! Rule it!!!
Act as true mentor. Yes you did well when you was developer, now it’s time to share your knowledge with juniors, try to replicate your knowledge, your experience. Help them in managing themselves and their day to day development tasks.
Embrace new technologies and believe in continuous improvement. As a technical lead, you are required to always look for continuous improvement in software construction. Adapt new tools to improve approach and productivity over time. This will help develop learning agility in the team.
Ensure better design. Try to make good design and coding habit of your team.
Delegate the overall development tasks effectively. However, at times, it is suggested to do some percentage of coding as well. This will add more respect in front of your team.  
Your passion towards technology counts! after all it’s software engineers you are leading.

Leadership

You will be interacting with different set of people with different attitude, different temper and different background. As an good leader you should have strong ability to listen people and listen them very well. Be clam and humble to hear their concerns and resolve them in best possible way.
As a lead developer, your every act should be inspiring for your team members. Also, It is important to walk your talk. We would definitely not like managers who does not act upon his own principles.
Know your team, their interests, their concerns, their strengths, their weaknesses and their growth.
Encourage team work and discourage blame game at least within the team. This will help people focus on the ultimate goal and will forgive each others mistake. Let them realize that they all win together and they all lose together.
Your ability to look in the cloudy future will reflect your proactive approach. Looking ahead of time and think what can go wrong will help you prepare for better execution tomorrow.
Maintain a positive environment and ethics within your team.
**********************************************************************************************************************************
These are some of the attributes I think as a good technical lead one should posses. Please feel free to comment your experience or what you believe a good lead should have?

Microsoft Application Platform at a Glance

“To stay on the map you’ve got to keep showing up.” — Peter Gallagher

Periodically I create a map of the Microsoft application platform. Making the map helps me stay on top of the platform, identify potential changes to architecture and design strategies, and anticipate trends.  It also helps me figure out where to invest my time and energy.  It also helps me see potential customer confusion.

Here is my latest map of the Microsoft application platform by category:

Application Infrastructure

  • .NET Framework

  • Base Class Libraries (BCL)

  • Common Language Runtime (CLR)

  • Language Integrated Query (LINQ)

ALM (Application Life-Cycle Management)

  • Visual Studio Team System
  • Visual Studio Team Foundation Server

App Frameworks / Extensions

  • Enterprise Library
  • Managed Extensibility Framework (MEF)

Cloud

  • Windows Azure
  • Windows Azure DataMarket (“Dallas”)
  • Windows Azure Tools for Microsoft Visual Studio
  • App Fabric
  • SQL Azure

Collaboration / Integration / Workflow

  • Windows Workflow Foundation (WF)
  • Microsoft Office SharePoint Server (MOSS)
  • Microsoft BizTalk Server

Data Access

  • ADO.NET Core
  • ADO.NET Entity Framework
  • ADO.NET Sync Framework
  • LINQ to SQL
  • OData
  • WCF Data Services
  • WCF RIA Services

Database Server / Storage

  • SQL Azure
  • SQL Server
  • SQL Server Compact

Desktop

  • WPF (Windows Presentation Foundation)
  • Silverlight (Out-of-Browser)
  • Windows Forms

Developer Tools

  • Microsoft Visual Studio
  • Microsoft Expression Studio
  • Microsoft Visual Studio Express
  • Microsoft Visual Studio LightSwitch
  • Microsoft Visual Studio Team Foundation Server

Games

  • XNA
  • D3D
  • Win32

Identity

  • WIF (Windows Identity Foundation) (Geneva)
  • Active Directory Federation Services (Geneva Server)
  • Card Space

Languages

  • Common Language Runtime (CLR)
  • Dynamic Language Runtime
  • Visual Basic
  • Visual C#
  • Visual C++
  • F#
  • Iron Python
  • IronRuby

LINQ

  • LINQ to Entities
  • LINQ to SQL
  • LINQ to XML
  • LINQ to DataSet
  • LINQ to Objects

Manageability

  • Systems Center Operations Manager (SCOM)

Office

  • Office 2010
  • Visual Studio Office Development Projects
  • Office 2010 PIA (Primary Interop Assemblies)

Parallel

  • F#
  • Parallel Extensions for .NET
  • PLINQ
  • Task Library

Phone

  • Silverlight for Windows Phone
  • XNA Framework
  • Windows Phone Developer Tools

Services

  • Windows Communication Foundation (WCF)
  • WCF Data Services (ADO.NET Data Services, Astoria)
  • WCF Web APIs
  • WCF RIA Services
  • ASP.NET Web Services (ASMX)

SharePoint

  • SharePoint Server

Web

  • ASP.NET Web Forms
  • ASP.NET Web Pages (WebMatrix)
  • ASP.NET MVC
  • Silverlight
  • CSS
  • HTML / HTML 5.0
  • Internet Explorer
  • JavaScript (Jscript) / JavaScript (as of IE 9)

Web Server

  • Internet Information Services (IIS)
  • IIS Express
  • Web Farm Framework

Windows Server

  • Windows Server
  • Windows Server App Fabric (Dublin + Velocity)

This post is taken from http://blogs.msdn.com/b/jmeier/