Modifying SOAP Header WCF.

October 9, 2015 Leave a comment

While Working on a project , I had a requirement to communicate with a service hosted in non Microsoft environment, so the service did not like the way SOAP security header was being sent it.

SO I had to modify the SOAP security header , wow..

it was really pain in my neck , ha ha ha.. so modify it.

following steps helped me to modify it.

1) Change the binding to custom binding.

<binding name="CustomSoapBinding">
<security includeTimestamp="false" authenticationMode="UserNameOverTransport" defaultAlgorithmSuite="Basic256" requireDerivedKeys="false" messageSecurityVersion="WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10"/>
<textMessageEncoding messageVersion="Soap11"/>
<httpsTransport maxReceivedMessageSize="2000000000"/>


Things to note, Service did not like the timestamp in security header , so I had to exclude it, also note below joke..


ohh..what on the earth does that mean…ha ha ha.try to remember it.. Smile

2)  before calling the service , make the changes.

   1: ws.ChannelFactory.Endpoint.Behaviors.Remove<System.ServiceModel.Description.ClientCredentials>();

   2: ws.ChannelFactory.Endpoint.Behaviors.Add(new CustomCredentials());

   3: ws.ClientCredentials.UserName.UserName = ConfigReader.GetConstantValue("UserID");

   4: ws.ClientCredentials.UserName.Password = ConfigReader.GetConstantValue("Password");


things to note

Line 1 :  removes the Client Credentials node from SOAP Security header.

Line 2 : Added a class[which we will see in a bit, which performs all the actions which are required to build custom security header node ].

Line 3, Line 4 : added some custom credentials.

3)  Custom Credential Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel.Description;
using System.ServiceModel;
using System.ServiceModel.Security;
using System.Text;
using System.Security.Cryptography;
using System.IdentityModel.Tokens;

namespace MedImpactServicesClient
public class CustomCredentials : ClientCredentials
public CustomCredentials()
{ }

protected CustomCredentials(CustomCredentials cc)
: base(cc)
{ }

public override System.IdentityModel.Selectors.SecurityTokenManager CreateSecurityTokenManager()
return new CustomSecurityTokenManager(this);

protected override ClientCredentials CloneCore()
return new CustomCredentials(this);

public class CustomSecurityTokenManager : ClientCredentialsSecurityTokenManager
public CustomSecurityTokenManager(CustomCredentials cred)
: base(cred)
{ }

public override System.IdentityModel.Selectors.SecurityTokenSerializer CreateSecurityTokenSerializer(System.IdentityModel.Selectors.SecurityTokenVersion version)
return new CustomTokenSerializer(System.ServiceModel.Security.SecurityVersion.WSSecurity11);

public class CustomTokenSerializer : WSSecurityTokenSerializer
public CustomTokenSerializer(SecurityVersion sv)
: base(sv)
{ }

protected override void WriteTokenCore(System.Xml.XmlWriter writer,
System.IdentityModel.Tokens.SecurityToken token)

UserNameSecurityToken userToken = token as UserNameSecurityToken;

string tokennamespace = "o";

DateTime created = DateTime.UtcNow;
string createdStr = created.ToString("yyyy-MM-ddTHH:mm:ss.fffZ");

// unique Nonce value - encode with SHA-1 for 'randomness'
// in theory the nonce could just be the GUID by itself
//string phrase = Guid.NewGuid().ToString();
byte[] nonce = GetNonce();
string nonceStr = Convert.ToBase64String(nonce);

// in this case password is plain text
// for digest mode password needs to be encoded as:
//string PasswordAsDigest = GetSHA1String(userToken.Password);
// and profile needs to change to
string password = CreateHashedPassword(nonce, createdStr, userToken.Password);

//string password = userToken.Password;

"<{0}:UsernameToken u:Id=\"" + token.Id +
"\" xmlns:u=\"\">" +
"<{0}:Username>" + "WSPAHUM" + "</{0}:Username>" +
"<{0}:Password Type=\"\">" +
password + "</{0}:Password>" +
"<{0}:Nonce EncodingType=\"\">" +
nonceStr + "</{0}:Nonce>" +
"<u:Created>" + createdStr + "</u:Created></{0}:UsernameToken>", tokennamespace));

private string CreateHashedPassword(byte[] nonce, string created, string password)
byte[] createdBytes = Encoding.UTF8.GetBytes(created);
byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
byte[] combined = new byte[createdBytes.Length + nonce.Length + passwordBytes.Length];
Buffer.BlockCopy(nonce, 0, combined, 0, nonce.Length);
Buffer.BlockCopy(createdBytes, 0, combined, nonce.Length, createdBytes.Length);
Buffer.BlockCopy(passwordBytes, 0, combined, nonce.Length + createdBytes.Length, passwordBytes.Length);
return Convert.ToBase64String(SHA1.Create().ComputeHash(combined));

internal static byte[] GetNonce()
byte[] nonce = new byte[0x10];
RandomNumberGenerator generator = new RNGCryptoServiceProvider();
return nonce;



Things to Note:

Most of the work is done in WriteTokenCore function and just copy everything related to Nounce, it took me around 1 week to figure out correct CreateHashedPassword algo.Smile


That’s it you are done.

let me know if you get stuck somewhere.

Categories: C#, WCF Tags: , ,

Launching WCF Test client From Service Application.

October 9, 2015 Leave a comment

When we create a WCF Service Application , and when we try to debug service application you will find that sometimes it launches browser instead of WCF test client.

its very easy to fix this problem.

open you solution and right click on the SVC file and set it as a start page.



then run the project you will be happy to see your test client.



Happy weekend.. Smile

Storing Multiple Values in Dictionary C#

October 9, 2015 Leave a comment

We All know the famous Dictionary

Dictionary<string,string> myDictionary

Its normally used for storing Key, Value pair.

Sometimes we want to store something like Key,Value,value.

for eg.

Dictionary<string,string,string> myDictionary

Unfortunately we don’t such structure in .Net, but there is workaround for such situation.

Create a Class or Struct and use it as Value.

for eg.

public class MyClass
public string Value1 { get; set; }
public string Value2 { get; set; }

Dictionary<string, MyClass> myDictionary


Hope this helps.

Categories: C#, Tips Tags: , ,

Modify Content Query webpart data programmatically

December 26, 2012 Leave a comment

when ever we want to modify some data from content query webpart either we use out of the box XSLT functions or XSLT extensions.

but sometimes XSLT functions can not help us to achieve desired functionality and some times , some..times…XSLT extensions are not allowed, so what do to do in such scenario.

yes …YES..we have a way..we can modify the data of the content query webpart pro-grammatically.

lets see how..and how easy it is as compared to XSLT extensions.

I have a custom  list which has two columns

1) Title

2) LastName

and we have a need to combine Title with Title, lets see how this can be achieved by modifying content query webpart data programmatically.

List Data


    public class ExtendedContentQueryDemoWebpart : ContentByQueryWebPart

        protected override void OnInit(EventArgs e)
            this.ProcessDataDelegate += new ProcessData(modifyData);

        private DataTable modifyData(DataTable dt)
            foreach (DataRow item in dt.Rows)
                item["Title"] = item["Title"].ToString() + " " + item["LastName"].ToString();
            return dt;


Inherit your webpart class by ContentByQueryWebPart .

ContentByQueryWebPart class is present it Microsoft.SharePoint.Publishing.WebControls namespace which is present in Microsoft.SharePoint.Publishing.dll  which is located at C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI\Microsoft.SharePoint.Publishing.dll

this.ProcessDataDelegate : aha..this is the key, to this delegate we can attach a function which takes datatable as input and returns datatable as output.

Now I have deployed the webpart as a farm solution , also added it to the webpart page, basic configurations for content query webpart.

List from which we need to show the data


Fields to display [content query webpart, will query and bring these fields from the list.]


Click Ok..Aha we are easy

it looks as below.


let me know if you have any questions.

Categories: Sharepoint2010

Import Excel sheet as SharePoint List

October 22, 2010 14 comments

Today I stumbled upon new feature of SharePoint 2010, Uploading excel spread sheet as SharePoint list.

I found it quite interesting and useful.

Here is how its done.

We will create a excel sheet having two columns[coutryname and countrycode] and  upload it in SharePoint as SharePoint list , along with data.

Open excel[i,m using office 2010]

Click on Insert Tab

Click on very first cell of excel and then click on table , a popup  window[create table] will come up, tick the checkbox next to my table has headers.

Below screen will come up

Rename column1 to countryname add one more column , name it as countrycode

And enter some dummy data.

Save your excel sheet .Name it as country.

Now click on site actions tab, then click on more options.

A popup window for create will come up select on import spreadsheet then click on create.

Below screen will come up, click on browse to select saved excel sheet.



Enter the name of list[this name will appear as list name in sharepoint]

When you click on import. below screen will come up,

Keep the range Type as Table Range and Click on select range and select Sheet1!Table1 from drop down list.

Click on import , a window asking your credentials will pop up, provide user name and password

Data gets imported and you can see SharePoint list created in your site.

We are simple ..yet so gr8

Categories: Excel, Lists, Sharepoint2010 Tags:

List Definition using sandbox in sharepoint 2010

October 21, 2010 5 comments

I wanted to create list definition in 2010, like every developer the first thing which came up in my mind was Google.

This are two thread which came up

But there were drawback of these approaches

1) They were deployed as farm solution, I wanted sandbox solution

2) They require content type, so when you create list definition a content type gets created in your Site, I wanted columns to come from metadata not from content type.

So after doing good amount of RND I found how to create list definition using sandbox solution.

I will explain step by step how to do it

Open Visual studio and select sharepoint tab, select 2010 and using Empty SharePoint project template create a project.

Enter the site name where you want to deploy the list definition; we will deploy it as sandbox solution.

Click finish, project will be created.

Now click on Add new item to project. Select list definition, provide the name and click on Add.

When you will click on Add below window will come up, provide name of list definition[this name will come up as list definition name in your SharePoint site], In this case we are going to create custom list so we will select custom list as list definition type.

Click Finish, VS will add features, package, list instance automatically; your project should look like below screen shot.

Open Schema.xml file under SampleListDef level.

If you open content types section you will see this

Remove ContentTypeRef ID=”0x01” section, your content type structure will look like this

Now Add new contentType [don’t add ContentTypeRef] provide it with ID and all the attributes.

ID should be given as follows


Now we need to add Custom columns which we need to add to our SampleList in FieldRefs section.

Each fieldRef should have ID and Name

After Adding fieldRef in content type , we need to Add those fields with additional attributes in <Fields></Fields Section.

Now we need to add Custom columns which we need to add to our SampleList in FieldRefs section.

Each fieldRef should have ID and Name

After Adding fieldRef in content type , we need to Add those fields with additional attributes in <Fields></Fields Section.

Sample Fields

<Field Type=”Text” DisplayName=”Country Code” Required=”FALSE” EnforceUniqueValues=”FALSE” Indexed=”FALSE” MaxLength=”255″ ID=”{26da1ec9-b18b-4b9e-9c41-ed060038de6e}” StaticName=”Country_Code” Name=”Country_Code” ColName=”nvarchar4″ RowOrdinal=”0″ />

<Field Type=”Number” DisplayName=”SortOrder” Required=”FALSE” EnforceUniqueValues=”FALSE” Indexed=”FALSE” ID=”{8f35d3fe-0c20-4b5d-b970-d1630a0c5519}” StaticName=”SortOrder” Name=”SortOrder” ColName=”float1″ RowOrdinal=”0″ />

Note : ID of this field and ID of fieldref in contenttype should be same. Your shema.xml should look like this.

Now Add Those fields in Viewfields section as shown below

That’s it , just right click on project and then deploy it.

Once it is deployed you will be able to see sampleListDef-ListInstance 1, List instance created in your site.There is no need to reset IIS as this is sandbox solution.

This name is coming from

Let go and check how our list looks

looks good..what say..lets click add new

i,m impressed with that dialoge box, lets save the data

its working, now the last and most important..lets see if List definition was created. there…

let me know if you have any questions.

Categories: Lists, Sharepoint2010