Zulfiqar's weblog

Architecture, security & random .Net

Archive for the ‘Uncategorized’ Category

Service Bus Server Install Experience

Posted by zamd on July 17, 2012

Today I installed Service Bus Server Beta release and the overall install experience was fairly smooth until I reached the New-SBFarm step of the ‘Getting started’ tutorial. The cmdlet just seems to hang for few minutes and failed ultimately – I tried on another machine & got same results. After lot of head–scratching I narrowed down the issue to SQL connectivity. Turns out New-SBFarm create 3 different databases, Farm management DB, Gateway DB & the message container database. The first two DBs are created by the cmdlet itself & it uses the Connection String passed into the cmdlet and just replaces the DB name. The message container DB creation is handled by another cmdlet ‘New-SBMessageContainer’ which uses the FQDN of the database server.

When server is identified using FQDN, SQL client code treats the connection as ‘Remote’ and because I was using a named instance – it tries to resolve the name using SQL Browser service which was by default disabled 😦

Hence the cmdlet hanged until connection request timeout – Enabling remote connections on Sql express & starting the SQL Browser service has fixed the issue.

Posted in Uncategorized | Leave a Comment »

WebSockets with WCF

Posted by zamd on November 23, 2011

Notification & “Duplex communication” are important scenario over the internet but firewalls and browser limitations makes them very hard to implement. In the browser world, tricks like long polling is commonly used to implement server-push requirements. For non-browser scenarios relay technologies like Azure Service Bus overcome the lack of inbound connectivity by creating a relay in the cloud where both client & server connects by making an outbound connection. Both long polling & relay works but are not optimum solutions due to latency and the complexity involved.

WebSockets is designed to address some of these limitation. With WebSockets, a client & server can upgrade an existing HTTP connection to a full-duplex TCP/IP connection or setup a new WebSockets connection using an HTTP based handshake. WebSockets uses standard HTTP ports (80, 443) so it’s just works with Firewall & the existing security infrastructure. WebSockets technology bucket has following two parts:

  1. WebSockets Protocol  (Currently being standardized by IETF)
  2. WebSockets JavaScript API (Currently being standardized by W3C)

Windows “8” has native support for WebSockets protocol & there are quite a few API (native & managed) available for programing WebSockets servers & clients on windows. In addition, IE 10 supports both Web Sockets protocol & the JavaScript API.


  • IE 10
  • WinRT


  • Native windows implementation ( >= Windows “8”)
    • IIS 8.0
  • System.Net.WebSockets (Managed Wrapper)
    • HttpListener
  • System.Web (ASP.net)
    • HttpContext
  • System.ServiceModel (WCF)
    • NetHttpBinding

WCF supported duplex services since V1 but these required either a duplex transport binding (netTcpBinding, netNamedPipeBinding) or wsDualHttpBinding which forces a client to have a public URI accessible to service (and to the world Smile)   running on the public internet.

wsDualHttpBinding is not really suitable for internet scenarios due to inbound connectivity issues. NetTcpBinding could also be problematic in tightly-locked down environments allowing only outbound connections to port 80/443.

With the WebSockets support in Windows, WCF introduced a new Binding NetHttpBinding which does binary SOAP messaging over WebSockets protocol and overcome the limitations of existing bindings. Below I created a basic duplex WCF service

Basic Service
public interface IPing
    void Ping(string msg);

class PingService : IPing
    public void Ping(string msg)
        Console.WriteLine("Service: {0}",msg);
        var chnl = OperationContext.Current.GetCallbackChannel<IPing>();

        chnl.Ping(string.Format("You said \"{0}\"?", msg));

Standard WCF hosting code with one endpoint using the new binding (line 5 & 14)

  1. static void Main(string[] args)
  2. {
  3.     var sh = new ServiceHost(typeof(PingService),
  4.         new Uri("http://localhost:9090/&quot;));
  5.     var binding = new NetHttpBinding();
  6.     sh.AddServiceEndpoint(typeof(IPing), binding, "Ping");
  8.     sh.Open();
  10.     Console.WriteLine("Service ready…");
  12.     var cf = new DuplexChannelFactory<IPing>(
  13.         new InstanceContext(new PingBack()),
  14.         binding,
  15.         new EndpointAddress("http://localhost:8080/Ping&quot;));
  17.     var chnl = cf.CreateChannel();
  18.     chnl.Ping("Hello!");
  20.     Console.WriteLine("Finishing…");
  21.     Console.ReadLine();
  22. }

and finally my callback handler class.

Callback handler
public class PingBack : IPing
    public void Ping(string msg)
        Console.WriteLine("Client: {0}",msg);

Running the project I get the expected output.

By default, WebSockets protocol is allowed on NetHttpBinding i.e. if your contract is a Duplex contract NetHttpBinding automatically upgrades to WebSockets protocol. Out of box, this binding does SOAP messaging and encodes SOAP using the WCF binary encoding. You can reuse the WebSockets transport binding element in a custom binding to support other encodings & protocols and I’ll talk about this in a future post.


Posted in Uncategorized | Leave a Comment »

Silverlight Claim-Based-Security Part-2

Posted by zamd on March 23, 2011

In part 1 I talked about a simple approach to combine WCF Routing service and claims-based security and I got some questions about the sample code and routing service configuration. In this post, I’ll explain some additional scenarios and would provide link to the source code. In my original post I used following very simple routing configuration where the RST (Request Security Token) message goes to the STS and everything else goes to the UserService (a business service)

Simple Routing Configuration
  1. <routing>
  2.   <filterTables>
  3.     <filterTable name="SLRouting">
  4.       <add endpointName="stsEndpoint" filterName="matchRST" priority="5"/>
  5.       <add endpointName="serviceEndpoint" filterName="allMessages" priority="1"/>
  6.     </filterTable>
  7.   </filterTables>
  8.   <filters>
  9.     <filter filterType="Action" filterData="http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue" name="matchRST"/>
  10.     <filter filterType="MatchAll" name="allMessages"/>
  11.   </filters>
  12. </routing>


The STS endpoint uses an action filter (line 4) which looks for a WS-Trust RST message and forwards it to the STS. If RST filter doesn’t match, then the routing engine goes and tries the second filter (line 5) which is a match all. So in my simple configuration all non-RST messages are simply sent to the second endpoint. Real world scenarios obviously would require more granular routing but it can easily be enabled using the same pattern. WCF routing configuration is quite powerful and supports composite (AND, OR etc) and custom filters using which you can model any routing logic as you per your needs.

Another interesting scenarios is to support multiple authentication schemes on the STS – windows authentication for the intranet while userName password for the internet. 

To enables this I have exposed the STS functionality using two different endpoints supporting both username/password based authentication as well as windows authentication. 


Because windows authentication is point-point so I relied on impersonation to flow the end-user identity to the STS via the Router. The windows authentication flow looks like this:


For the windows-integrated endpoint,  router is configured to impersonate the client and the outgoing messages is sent under this impersonated context which enables the STS to authenticate the original user using windows authentication.

serviceAuthorization impersonateCallerForAllOperations="true"

When deploying in IIS, both the router endpoint and the STS endpoint needs to be configured for windows-authentication and I have accomplished it by creating a sub-folder (windowsintegrated) under both virtual directories and configuring this for windows-authentication. The main/parent virtual directories still has anonymous access enabled for the userName authentication to work. Note with userName authentication,  the credentials goes inside the SOAP message. My VS setup look like this:


The web.config(s) under the ‘windowsintegrated’ folder overrides the settings to enable windows-authentication. For example, in the STS project the root web.config defines both service endpoints along with a default binding which is configured for UserName authentication over HTTP.

Root web.config: STS
  1. <system.serviceModel>
  2.   <serviceHostingEnvironment>
  3.     <serviceActivations>
  4.       <add relativeAddress="~/issue.svc" service="CustomSecurityTokenServiceConfiguration"
  5.            factory="Microsoft.IdentityModel.Protocols.WSTrust.WSTrustServiceHostFactory"/>
  7.       <add relativeAddress="~/windowsintegrated/issue.svc" service="CustomSecurityTokenServiceConfiguration"
  8.            factory="Microsoft.IdentityModel.Protocols.WSTrust.WSTrustServiceHostFactory"/>
  9.     </serviceActivations>
  10.   </serviceHostingEnvironment>
  12.   <services>
  13.     <service name="Microsoft.IdentityModel.Protocols.WSTrust.WSTrustServiceContract">
  14.       <endpoint address="IWSTrust13"
  15.                 binding="customBinding"
  16.                 contract="Microsoft.IdentityModel.Protocols.WSTrust.IWSTrust13SyncContract"/>
  17.     </service>
  18.   </services>
  20.   <bindings>
  21.     <customBinding>
  22.       <binding>
  23.         <security authenticationMode="UserNameOverTransport" allowInsecureTransport="true"/>
  24.         <httpTransport/>
  25.       </binding>
  26.     </customBinding>
  27.   </bindings>
  28. </system.serviceModel>


The web.config in the ‘windowsintegrated’ changes the default binding to enable windows authentication. I’m using the ‘Simplified WCF Configuration’ here so the final config is very clean as a result.

Overriden default CustomBindin
  1. <system.serviceModel>
  2.   <services/>
  3.   <bindings>
  4.     <customBinding>
  5.       <binding>
  6.         <httpTransport authenticationScheme="Negotiate"/>
  7.       </binding>
  8.     </customBinding>
  9.   </bindings>
  10. </system.serviceModel>

Similar technique is used on the WebSite/Router where I pick different STS endpoint/binding depending on the chosen router endpoint. The root web.config goes to the anonymous STS endpoint (line 2 & 3) and authentication is done using the message credentials (userName).

Root web.config WebSite
  1. <client>
  2.   <endpoint name="stsEndpoint" address="http://localhost/ActiveSTS/issue.svc/IWSTrust13"
  3.             binding="customBinding" bindingConfiguration="outBinding" contract="*">
  4.   </endpoint>
  6.   <endpoint name="serviceEndpoint" address="http://localhost/UserService/Service1.svc"
  7.       binding="customBinding" bindingConfiguration="outBinding" contract="*">
  9.   </endpoint>
  11. </client>


Web.config in the ‘windowsintegrated’ changes the default STS endpoint/binding to match the windows authentication requirements and also enables impersonation to flow windows identity to the STS.

Router config for windows auth
  1. <system.serviceModel>
  2.   <services/>
  3.   <client>
  4.     <remove name="stsEndpoint"/>
  5.     <endpoint name="stsEndpoint" address="http://localhost/ActiveSTS/windowsintegrated/issue.svc/IWSTrust13"
  6.               binding="customBinding" bindingConfiguration="outBinding" contract="*"/>
  7.   </client>
  8.   <bindings>
  9.     <customBinding>
  10.       <binding name="inBinding">
  11.         <httpsTransport authenticationScheme="Negotiate"/>
  12.       </binding>
  14.       <binding name="outBinding">
  15.         <httpTransport authenticationScheme="Negotiate"/>
  16.       </binding>
  18.     </customBinding>
  19.   </bindings>
  20.   <behaviors>
  21.     <serviceBehaviors>
  22.       <behavior>
  23.         <serviceAuthorization impersonateCallerForAllOperations="true"/>          
  24.       </behavior>
  25.     </serviceBehaviors>
  26.   </behaviors>
  27. </system.serviceModel>


Finally make sure to enable integrated windows authentication on the ‘windowsintegrated’ directory in IIS before you run the samples.



Download: Sample solution

Posted in Uncategorized | 6 Comments »

Securing WF 4 Workflow Services

Posted by zamd on February 3, 2011

If you interested in an in-depth understanding of workflow services along with various security options. Then check out my latest MSDN magazine article.


Associated Source code

Posted in Uncategorized | Leave a Comment »

Exposing Workflow Service over Azure Service Bus

Posted by zamd on February 2, 2011

In this post I’ll walk you through the steps of exposing a ‘Windows Server AppFabric’ hosted workflow service over the Azure service bus.  IIS/AppFabric hosted services are message activated so they cannot be visible on the servicebus until they are activated. So in this post, I’ll use the AutoStart feature of AppFabric to make my service available over service bus.

Create a workflow service project using Visual Studio


VS would generate a .xamlx based service and a default web.config file


The generated web.config uses the new WCF 4.0 default configuration option so no <service> tag was generated. If you run the service now, default endpoints would automatically be generated based on the base address of the service provided by the IIS.

Service bus endpoints requires an address in the service bus namespace so I can’t use IIS provided base address which means I can’t use the default endpoints feature. So the first set of changes would to be revert back to the old-style explicit endpoint definition.

      <service name="Service1">
        <endpoint address="http://eval01.servicebus.windows.net/wfappfabric/" binding="ws2007HttpRelayBinding" contract="IService"/>
        <endpoint address="http://eval01.servicebus.windows.net/wfappfabric/mex" binding="ws2007HttpRelayBinding" kind="mexEndpoint"/>

The service name & contract name (‘Service1’ & ‘IService’) can be found from the properties of the workflow and the receive activity respectively.  Because I’m using an absolute address for my endpoint, WCF tells me to disable the multipleSiteBindings by removing the following element.

    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
Next I’ll change the default ws2007HttpRelayBinding to disable security.
          <security mode="None" relayClientAuthenticationType="None" />

Configure the ACS security for the ServiceBus and specify the discovery mode to public so that I can see my service in the registry. All of this is done using a default a endpoint behavior.

          <serviceRegistrySettings discoveryMode="Public" />
          <transportClientEndpointBehavior credentialType="SharedSecret">
              <sharedSecret issuerName="owner" issuerSecret="SECRET=" />

Using the project properties, I’ll configure the service to run under IIS/AppFabric


I can now see my endpoints in the AppFabric management console but I can’t see my service in the Service Bus registry because it’s not activated yet.


So I need to configure Auto-Start feature on this service which I can easily do using the AppFabric management console.


After configuring AutoStart I can straight a way see my service in the registry


When I browse to my service I see the standard help page which the metadata URL


Download: Web.config

Posted in Uncategorized | Leave a Comment »

2010 in review

Posted by zamd on January 3, 2011

The stats helper monkeys at WordPress.com mulled over how this blog did in 2010, and here’s a high level summary of its overall blog health:

Healthy blog!

The Blog-Health-o-Meter™ reads Wow.

Crunchy numbers

Featured image

About 3 million people visit the Taj Mahal every year. This blog was viewed about 27,000 times in 2010. If it were the Taj Mahal, it would take about 3 days for that many people to see it.

In 2010, there were 22 new posts, growing the total archive of this blog to 66 posts. There were 108 pictures uploaded, taking up a total of 7mb. That’s about 2 pictures per week.

The busiest day of the year was July 7th with 287 views. The most popular post that day was Using WIF with Workflow Services.

Where did they come from?

The top referring sites in 2010 were stackoverflow.com, social.msdn.microsoft.com, blogs.msdn.com, davidezordan.net, and forums.silverlight.net.

Some visitors came searching, mostly for datacontract isreference, this element is not currently associated with any context, id3082: the request scope is not valid or is unsupported., wif rest, and zamd.

Attractions in 2010

These are the posts and pages that got the most views in 2010.


Using WIF with Workflow Services July 2010


DataContract Serializer and IsReference property May 2008


Adding Dynamic methods to a WCF Service February 2010
1 comment


Integrating WIF, WF 4.0 & AppFabric: Claims-Based-Delegation June 2010


Error handling with WebHttpBinding for Ajax/JSON July 2008
1 comment

Posted in Uncategorized | Leave a Comment »

WF Security Pack is live now

Posted by zamd on July 1, 2010

  Wow, CTP1 of WF Security Pack is gone live now. Go get it from:


Check out following post for an introduction. 


My blog also has a slightly old intro post.


Over the next few days, we will cover all the interesting scenarios enabled by WF Security Pack. Stay tuned…  Please let us know what do you think about this pack. This would help us bring this functionality in next version of .Net Framework.

Posted in Uncategorized | Leave a Comment »