SOA Applications Archives - Anuj Varma, Hands-On Technology Architect, Clean Air Activist https://www.anujvarma.com/category/technology/service-oriented-architecture/ Production Grade Technical Solutions | Data Encryption and Public Cloud Expert Thu, 06 Jul 2017 03:05:05 +0000 en-US hourly 1 https://wordpress.org/?v=6.7.1 https://www.anujvarma.com/wp-content/uploads/anujtech.png SOA Applications Archives - Anuj Varma, Hands-On Technology Architect, Clean Air Activist https://www.anujvarma.com/category/technology/service-oriented-architecture/ 32 32 web services security https://www.anujvarma.com/web-services-security/ https://www.anujvarma.com/web-services-security/#respond Tue, 14 Feb 2017 14:33:36 +0000 http://www.anujvarma.com/?p=4503 How you secure web services depends on whether they are intranet or internet facing. Internet Facing Services For an internet facing web service, you need message level encryption. The encryption […]

The post web services security appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
How you secure web services depends on whether they are intranet or internet facing.

Internet Facing Services

For an internet facing web service, you need message level encryption. The encryption key can be a simple username – however, as a best practice it is better to use certificate based public keys. The public key can be requested by anyone directly from the host – once available, all messages are encrypted using this public key. The public key can only encrypt- not decrypt any messages. The private key is only available to the host – so the host is able to decrypt the message successfully. Once decrypted, the host scans the message for the username, which it then uses to authenticate the service.

INTRANET Facing Services

These do not need message level encryption. Simply using windows identify (windows auth) should successfully allow the client credentials to be authenticated. One can use Windows-based security for transfer security, authentication,and authorization. The client process (which uses a service proxy to call the service) automatically knows it has to send its windows credentials to the service (the service configures this in the endpoint configuration).

Authenticate end users – Two-Way Certificates

One way to ensure that your end client is truly your end client is to distribute a certificate that you create and maintain – purely for end user authentication purposes. This is different from the server certificate – which identifies, not the end user, but the actual website that is hosting the web service.  This requires the host (server) to maintain a list of issued certificates (a local Certificate Authority in a sense).  This can quickly become unmanageable as the number of end users grows. However, it is a super-secure model – as it is impossible for either the clients or the server to bypass trust.

Glossary

: Web Services can be secured using a combination of the following:

  1. Transport Layer Security—SSL.
  2. XML Encryption (Confidentiality)
  3. XML Signature (Integrity, Authenticity)
  4. WS-Security.
  5. WS-Security Tokens. Username. X.509 Certificate. Kerberos Token. SAML Token.
  6. WS-Policy.
  7. WS-SecurityPolicy.

The post web services security appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/web-services-security/feed/ 0
Restful versus SOAP–Is SOAP Obsolete? https://www.anujvarma.com/restful-versus-soap-is-soap-obsolete/ https://www.anujvarma.com/restful-versus-soap-is-soap-obsolete/#respond Thu, 19 Jan 2017 03:18:25 +0000 http://www.anujvarma.com/?p=4468 REST is obviously taking over the world of web services. However, there are several vendors still pushing out SOAP compliant APIs and providing services that are SOAP based. The reason […]

The post Restful versus SOAP–Is SOAP Obsolete? appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
REST is obviously taking over the world of web services. However, there are several vendors still pushing out SOAP compliant APIs and providing services that are SOAP based. The reason for this is many-fold.

Atomicity and Transactions

Only SOAP, through WS-AtomicTransaction provides complete ACID in the web service world.

Security

In addition to standard SSL  support, SOAP provides WS-SEcurity options. These can be thought of as message level security (encrypting parts of the soap message), as opposed to transport level security (which SSL provides).

One might ask, why do we need message level encryption when the entire transit is encrypted at the network level?  That’s just the point – SSL takes care of in-transit encryption – but the actual soap message is unencrypted. If, for instance, your web traffic is routed through a proxy server, the SOAP message is decrypted at the proxy – which means it passes into your network in plain text.

Advantages of REST

In a nutshell, simplicity is the biggest advantage of REST. REST doesn’t require a complex interface description language (SOAP requires WSDL). REST works with just XML or JSON (JavaScript Object Notation) and several other media types.

REST is also better performing (reads can be cached, for example) and scales easily. Amazon (and eBay) are primarily REST based.

Downsides of SOAP

Interoperability (aka Interop) has been a challenge with SOAP. Since SOAP is strongly typed, it expects servers (web servers) to understand what a client (browser or web client) means when it says  ‘I am passing an integer’ or ‘Here is an array’.  If you are trying to pass parameters from a .NET Client to an Apache SOAP service, you may encounter interop issues.  Whereas .NET SOAP (and WCF) supports multi-dimensional arrays as parameters, apache soap does not.  SOAP is very ‘breakable’ – changes in parameter types – even simple changes of the type that changes 16 bit int to a 32 bit int – can break all clients (consumers). Brittle is probably a better word to describe SOAP interoperability. Which is all the more ironic – since SOAP was designed to solve platform-to-platform interoperability issues. In all fairness, SOAP did a decent job for the most part – and worked fairly well – except when it didn’t. And the fixes usually were not life changing events – it was fairly easy to change from an ArrayList (in .NET) to an Array before passing it to a J2EE server.

Summary

For an enterprise grade SOA that requires both Transactionality (between successive message calls) and Security (message level security), SOAP is still more powerful  than REST. If these advanced security and transactionality features are ‘optional’, you may be better off with RESTFul services.

The post Restful versus SOAP–Is SOAP Obsolete? appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/restful-versus-soap-is-soap-obsolete/feed/ 0
Exposing SOAP Header info to Client through the WSDL https://www.anujvarma.com/exposing-soap-header-info-to-client-through-the-wsdl/ https://www.anujvarma.com/exposing-soap-header-info-to-client-through-the-wsdl/#respond Thu, 14 May 2015 18:33:08 +0000 http://www.anujvarma.com/?p=3116 The WSDL specification provides you with two different ways of specifying the use of SOAP header fields. In explicit headers, you add all of the header information to the portType […]

The post Exposing SOAP Header info to Client through the WSDL appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
The WSDL specification provides you with two different ways of specifying the use of SOAP header fields.

In explicit headers, you add all of the header information to the portType of the service. It becomes exposed to the client as additional parameters. The advantage of this style is that the client can pass all of the information directly to the service.

The post Exposing SOAP Header info to Client through the WSDL appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/exposing-soap-header-info-to-client-through-the-wsdl/feed/ 0
Google Chrome’s Wizdler Extension https://www.anujvarma.com/google-chromes-wizdler-extension/ https://www.anujvarma.com/google-chromes-wizdler-extension/#respond Tue, 28 Apr 2015 18:31:34 +0000 http://www.anujvarma.com/?p=3035 SoapUI used to be a quick way to parse WSDLs and test out the exposed services listed in that WSDL. It required a 100MB download -and an underlying java runtime […]

The post Google Chrome’s Wizdler Extension appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
SoapUI used to be a quick way to parse WSDLs and test out the exposed services listed in that WSDL. It required a 100MB download -and an underlying java runtime to run.

A simple plugin from Google Chrome (an extension on Chrome) accomplishes the same task. The extension is called Wizdler – it is under 1MB – and is automatically launched whenever you BROWSE to a WSDL (Chrome figures this out for you).

The post Google Chrome’s Wizdler Extension appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/google-chromes-wizdler-extension/feed/ 0
SOA Challenges–State Maintenance, Security https://www.anujvarma.com/soa-challenges-state-maintenance-security/ https://www.anujvarma.com/soa-challenges-state-maintenance-security/#respond Mon, 02 Mar 2015 03:04:00 +0000 http://www.anujvarma.com/?p=4840 APIs Computer to computer interactions (see 2-way certificates for Web Service Security). APIs are tightly integrated into client code – Web Services work through a proxy – nothing from the […]

The post SOA Challenges–State Maintenance, Security appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
APIs

Computer to computer interactions (see 2-way certificates for Web Service Security). APIs are tightly integrated into client code – Web Services work through a proxy – nothing from the actual server (except a proxy representation of the service) is needed.  In RESTFul APIs, even the proxy is not really needed  – it is direct HTTP call

State in SOA

– Per Call (new object instantiated for each call) and Per Session (object stays alive for entire session of calls) services.

Operations – 1 way versus Request-Response versus Callbacks  

1-way calls – Fire and Forget

Request Response – Most common pattern

Callbacks 

The client becomes the server – so the client needs to host an HTTP CAllback Object

HTTP cannot be used for callbacks – so WSHTTP and BasicHTTP bindings are both useless (only NetTCP and NamedPipes support Duplex mode)

The post SOA Challenges–State Maintenance, Security appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/soa-challenges-state-maintenance-security/feed/ 0
Always build a services tier (layer) even if you don’t think you may need it https://www.anujvarma.com/always-build-a-services-tier-layer-even-if-you-dont-think-you-may-need-it/ https://www.anujvarma.com/always-build-a-services-tier-layer-even-if-you-dont-think-you-may-need-it/#respond Fri, 30 May 2014 00:03:22 +0000 http://www.anujvarma.com/?p=2556 There is a lot of debate on the prevalence of the service layer (web services tier) – in almost every app (web or non web) built today. Martin Fowler also […]

The post Always build a services tier (layer) even if you don’t think you may need it appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
There is a lot of debate on the prevalence of the service layer (web services tier) – in almost every app (web or non web) built today. Martin Fowler also promotes such an approach.

In my experience, not only is it a good practice, it is a MUST DO practice for the following reasons

Multiple Clients – The top reason cited by most advocates is simply that you cannot be guaranteed that you will have a single client type (say a desktop browser). You may end up with a mobile app client, another web service client or a multitude of other clients. The services layer serves as the entry point for all these clients – and in a lot of cases, handling your new client is as simple as providing another binding – a simple CONFIGURATION change. It is hard to beat that for the effort required to handle new clients.

While handling multiple types of clients is an important motivation for building a services layer, I find another compelling reason. When I start approaching any new application, the business operations seem to map naturally to service operations. If I think in terms of CreatingNewAccounts or UpdatingCustomerInfo– those seem to be ideally mapped to an AccountService and a CustomerService respectively.  Even as the business operations span across a single transaction (for e.g. AddItemToShoppingCart and CheckOut), it is easier to map these through attributes in the Services Operation.

The first starting point is always the service interface (a list of all the operations that the service will support). To me, any n-Tier app – needs to start with the Services tier –and then be concerned about the data access or the data tier or the web tier.

 

When might it be overkill?

If you see no other potential client except for the simple web client that you are building – if you see no future mobile clients or other services calling this functionality, the services layer may not be necessary. A simple MVC app – with your controller actions mapped to user operations would be sufficient.

The post Always build a services tier (layer) even if you don’t think you may need it appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/always-build-a-services-tier-layer-even-if-you-dont-think-you-may-need-it/feed/ 0
Agatha–Getting Started–First Application https://www.anujvarma.com/agathagetting-startedfirst-application/ https://www.anujvarma.com/agathagetting-startedfirst-application/#comments Thu, 12 Dec 2013 23:51:00 +0000 http://www.anujvarma.com/?p=1691 Introduction The advent of WCF has made life simpler for web service developers . Passing complex types, quick serialization,  write once run with multiple bindings (and hence multiple consumers) etc. […]

The post Agatha–Getting Started–First Application appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
Introduction

The advent of WCF has made life simpler for web service developers . Passing complex types, quick serialization,  write once run with multiple bindings (and hence multiple consumers) etc. – have contributed to its popularity. However, larger WCF projects start suffering from the following symptoms:

The Proxy Dependence

Each time a parameter is modified (on a service request), the service definition needs to change. This requires an update of the proxy on each client consuming the service.

Agatha’s Solution  – Standardize the request and response – so there is no change in the single contract that all services expose. This single contract looks like :

public abstract Response Handle(TRequest request);

Services and Operations Bloat

Large number of Services, each with multiple Operation Contracts.

Services start overflowing into other services – and lack boundaries.  Each service starts to have too many operations. When adding a new operation, one would be faced with a decision : whether to add it to an existing service or to create a brand new service.

Agatha’s solution – Define custom request types for each operation (e.g. if your operation is to GetEmployeeDetails, you would have a request called GetEmployeeDetailsRequest – and a response GetEmployeeDetailsResponse). Each operation then is simply a Handler for these custom request types. So – GetEmployeeDetailsHandler – would have a single Handle() method to contain your business logic.

This enforces granularity on your service operations – and makes them easier to maintain. You will never have to worry about WHERE to place a new operation. It just gets its own handler, its own request and response types.

No More Initialization, No More XML

A WCF client would need to initialize an instance of each proxy – and then invoke the operations on it. In addition, it would need to ensure that the proxy was up to date (by updating its service reference).

Agatha’s solution – Use an IoC container to discover and initialize all your services (i.e. just a single service the WcfRequestProcessor service).

private static void InitializeAgatha()

      {

          new ClientConfiguration(typeof(AgathaGettingStartedRequest).Assembly, typeof(Agatha.Castle.Container)).Initialize();

      }

Single service, Single endpoint, Common contract

Since all the requests and responses derive from a common agatha Request and Response typesT, all services exchange the same types. Their contract is the same. Only a single endpoint is needed – regardless of how many requests and responses (operations) you may have in your project.

<services>

      <service behaviorConfiguration="RequestProcessorBehavior" name="Agatha.ServiceLayer.WCF.WcfRequestProcessor">

        <endpoint address="" binding="customBinding" bindingConfiguration="binaryXmlOverHttp" contract="Agatha.Common.WCF.IWcfRequestProcessor" />

      </service>

    </services>

 

Getting Started

Having discussed the need for something like Agatha, here is a sample project that shows how to use it (source code  towards the bottom).

Step 1 , Getting Started – Defining Request Types and Response Types

A base Request type is provided by Agatha – to which you can add your request fields. For example, suppose your service operation is one that Creates a new Account. You would define a new Request Type called CreateAccountRequest which would be of (a base) type Request (agatha’s base request type).

public class CreateAccountRequest : Request

  {

      public AccountDTO accountDTO{ get; set; }

  }

namespace Agatha.Common

{

    public abstract class Request

    {

        protected Request();

    }

}

 

Step 2, Getting Started – Adding Service Operations

agatha_solution

 

Step 3a – Registering Agatha Services , Client

Normally, in your WCF client, you would ‘Add a Service Reference’ from within your client project to access a known WCF service. If your client is using Agatha, you can use an IoC container to ‘discover’ the services for you – so you never have to ‘Add a Service Reference’. All you need in your client code is:

private static void InitializeAgatha()

        {

            new ClientConfiguration(typeof(AgathaGettingStartedRequest).Assembly, typeof(Agatha.Castle.Container)).Initialize();

        }

Step 3b – Registering Agatha Services , Server (service)

An IoC container can be used to register and initialize the service within the WCF runtime. Notice that you do not have to worry about any XML configuration (contract name, bindings etc.). All you need is to use the provided ServiceLayerConfiguration class – and initialize it when the web app initializes (Global.asax, application_start).

void Application_Start(object sender, EventArgs e) 

    {

        //  Agatha initialization can happen here

        Bootstrapper.RegisterAgatha();

    }

public static void RegisterAgatha()

      {

          new ServiceLayerConfiguration(Assembly.GetExecutingAssembly(), typeof(AgathaGettingStartedRequest).Assembly, typeof(Agatha.Castle.Container)).Initialize();

      }

What are some other things Agatha can do?

 

Call your services asynchronously

Just as in WCF (or any other async pattern), the actual service itself does not need to be asynchronous. Only the client needs to invoke the service asynchronously from its side. This is accomplished in regular web services using  the BeginInvoke and EndInvoke (or BeginServiceOperation and EndServiceOperation).

  In Agatha, similar constructs exist to enable calling the same service asynchronously from a client. An AsyncRequestDispatcher implementation contains a ProcessRequest method to help with async client requests.

/// <summary>

       /// ProcessRequests is the Asynchronous version of requestDispatcher.Get

       /// </summary>

       private static void CallTheServiceAsynchronously()

       {

           var requestDispatcher = IoC.Container.Resolve<IAsyncRequestDispatcher>();

           requestDispatcher.Add(new AgathaGettingStartedRequest());

          

           // ProcessRequests is the Asynchronous version of requestDispatcher.Get

           requestDispatcher.ProcessRequests(ResponsesReceived, e => Console.WriteLine(e.ToString()));

       }

 

       private static void ResponsesReceived(ReceivedResponses receivedResponses)

       {

           Console.WriteLine(receivedResponses.Get<AgathaGettingStartedResponse>().Message);

       }

       private static void InitializeAgatha()

       {

           new ClientConfiguration(typeof(AgathaGettingStartedRequest).Assembly, typeof(Agatha.Castle.Container)).Initialize();

       }

 

Customize your Request object (e.g. Custom Authentication)

What if you wanted only specific users to access certain services? You would need to pass in a userId with each request. This is easily accomplished by defining a custom base request class – that can be used as the parent for all subsequent requests.

/// <summary>

    ///  A single, centralized request allows passing custom Authentication parameters - e.g. userId.

    /// </summary>

    class CustomizedAuthRequest : Request

    {

        public long userId { get; set; }

    }

OverRide beforeHandle and AfterHandle for custom processing

Agatha provides a base RequestHandler class ( RequestHandler<TRequest, TResponse>) – with several useful template methods. These include Handle, BeforeHandle and AfterHandle methods to provide custom processing. If you wanted all your requests (containing a userId) to be authenticated (against sql server or ldap etc.), you would just need to do it in the BeforeHandle method. The template pattern used in Agatha, is a life-saver here as well, as in other OO codebases.

public override void BeforeHandle(TRequest request)

{

        // e.g. - do custom authentication (LDAP, ActiveDirectory etc.)

    base.BeforeHandle(request);

}

 

public override void AfterHandle(TRequest request)

{

        // e.g. - do custom logging etc.

    base.AfterHandle(request);

}

Single WCF Performance Counter

Remember that Agatha is a generic request response processing layer – and does not need WCF. However, a WCF processor is provided with Agatha – since it is commonly used with WCF. If you look in your performance counters, under ServiceModelService 4.0.0.0 , you should see the WcfRequestProcessor counter that Agatha registers on your local PC. This can be monitored during your testing effort.

WcfRequestProcessor_thumb2

 

What do I need on the client? Agatha Client Side Requirements

Agatha relies on your defining custom request and response classes for each of your operations. The client needs to know what these types are. You DO need to share the assembly containing the common types between the server and the client. And you DO need common Agatha libraries – in particular Agatha.common and Agatha.castle (for Castle Windsor IoC).

However, note that agatha services CAN consumed by non-Agatha aware clients.  It is possible to consume an Agatha service just like any WCF service, as described here.

What about NServiceBus (or service buses in general)?

A service bus does not (typically) do ‘request-response’ well. It relies on a message publishing (and subscribing) – which is not (necessarily) instantaneous and not (necessarily) synchronous. It is, however, fault tolerant (ensuring that messages DO get delivered) – and highly scalable (since instantaneous responses are not mandatory).

For a typical web user, a request-response pattern is more important than a message publishing pattern.

Having said all that, NServiceBus supposedly supports a request-response pattern – in addition to its core message publish subscribe pattern

The sample Hello World project

Project 1 –SharedCommonTypes

The types that are common between the client and the Service Layer

Project 2 – ServiceLayer

The Service Layer itself. This inherits from Agatha’s base RequestHandler class. It overrides the Handle method in the base class. This is all that is REQUIRED in the services layer. Notice that the Service Layer knows nothing of WCF or any other web service technology. All it is – is a pure request – response handling layer.

A static class that provides an initialization method is a good idea – it makes the code on the client much easier.

Project 3 – Agatha Host Site

The blank WCF service that acts as a container. This will allow us to host it within IIS. There is no logic, no operations etc. within this WCF service. It is just a blank service. All service operations are moved to the ServiceLayer – which has a custom Handle method for each operation.

Project 4 – Console App (Client)

Contains the only default config needed to call Agatha services – and methods to call the service synchronously as well as asynchronously.

Running the sample

Just open it up in two different instances of VS – one for running your service layer – and the other for the client.

VS Instance 1 – In the first one, set the WCF service (AgathaHostSite) as the startup project. It should start up on a localhost – browse to localhost: port/Service.svc – and you should see a WcfRequestProcessor Service page (WcfRequestProcessor is the processor inside Agatha for handling WCF requests).

VS Instance 2 – Set the Console App (client) as the startup project. Start it to see your client – and initialize and invoke the service.

VS Instance 1 VS Instance 2 Started up WebService
agathaHostSiteStartup consoleappstartup agatha_service_page

 

Summary

For larger WCF projects, a layer such as Agatha becomes more than a convenience. Apart from saving tons of maintenance, it provides cleaner, fine grained operations.  These operations utilize a base RequestHandler class that contains a Handle operation. This operation is all you need to override for each of your custom service operations.

With IoC support, you no longer have to worry about initializing services (on the service layer or the client). With a single endpoint, you no longer have to worry about large XML web.configs. 

Source Code Download

The post Agatha–Getting Started–First Application appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]> https://www.anujvarma.com/agathagetting-startedfirst-application/feed/ 1 The Publish Subscribe Pattern in C# and some gotchas https://www.anujvarma.com/the-publish-subscribe-pattern-in-c-and-some-gotchas/ https://www.anujvarma.com/the-publish-subscribe-pattern-in-c-and-some-gotchas/#comments Wed, 17 Apr 2013 19:48:50 +0000 http://www.anujvarma.com/?p=1440 This post does three things: Provides a complete implementation of the publish subscribe pattern in C#. Highlights 4 potential issues that are inherent to ANY publish subscribe implementation – including […]

The post The Publish Subscribe Pattern in C# and some gotchas appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
v\:* {behavior:url(#default#VML);} o\:* {behavior:url(#default#VML);} w\:* {behavior:url(#default#VML);} .shape {behavior:url(#default#VML);}

This post does three things:

  1. Provides a complete implementation of the publish subscribe pattern in C#.
  2. Highlights 4 potential issues that are inherent to ANY publish subscribe implementation – including the one provided here.
  3. Provides original, tested workarounds for each of the 4 issues (source code included).

As far as the author is aware, this is the only publish subscribe implementation that provides these workarounds – making it immune from the common issues of badly behaved subscribers, race conditions and subscribers that fail to unsubscribe. 

UPDATE: With the introduction of two new interfaces (IObserver and IObservable) in .NET 4.0, there is a cleaner way to implement the Publish Subscribe pattern in C# .NET. However, the ‘gotchas’ listed here still apply. Even with the new interfaces, one still needs to worry about things such as ‘unsubscribing from the publisher’, ‘badly behaved subscribers’ and ‘new subscribers added while publishing is in progress’.

DELEGATES and EVENTS way OF IMPLEMENTING PUBLISH SUBSCRIBE in C#

 

Introduction : Events , combined with delegates in C#  make it possible to implement a simple publisher – subscriber pattern. If you are unfamiliar with delegates, read this post first.

There are three main players in any Publish Subscribe pattern implementation:

  1. The Event : The example below revolves around the ‘payday’ event – which is called PayrollArrived.
  2. The Publisher : The event is published by the Employer class (the Employer announces the payday when it arrives).
  3. The Subscriber : Each Employee (i.e. each instance of the Employee class) listens for the event – and is hence a subscriber to the PayrollArrived event.

 

The Event

Events provide a way to signal a change of state to whoever is ‘subscribed’ to that event. The arrival of the first of every month may be the event for publishing a new issue of a magazine. The subscribers would be everyone who has a paid subscription to the magazine – and the publisher would be the magazine publisher.

The arrival of the 15th of every month may be a payroll event for a company. The subscribers would be all employees who get paid on the payroll date.  The publisher would be the company itself that pays the employees on payroll day. The example code in this post deals with the latter event – a payroll event with an Employer (Publisher) and multiple Employees(Subscribers). 

// For events to be treated as 'fields', they need to be of type 'delegate'.

// First, define the delegate type for the event 

   public delegate void PayrollArrivedHandler(object sender, PublisherEventArgs e);

 

// public event declaration, a 'delegate' type for the event must be declared first

   public event PayrollArrivedHandler PayrollArrived;

The Publisher (Employer)

public class EmployerPublisher 

{

    LinkedList<Employee> _listSubscribers = new LinkedList<Employee>();

    public LinkedList<Employee> ListSubscribers

    {

        get { return _listSubscribers; }

        set { _listSubscribers = value; }

    }

 

    // For events to be treated as 'fields', they need to be of type 'delegate'.

    // First, define the delegate type for the event 

    public delegate void PayrollArrivedHandler(object sender, PublisherEventArgs e);

 

    // public event declaration, a 'delegate' type for the event must be declared first

    public event PayrollArrivedHandler PayrollArrived;

  

    // add new subscriber

    public void AddSubscriber(Employee em)

    {

        // Add new subscriber to the TOP of the linked list - this way it will not interfere with the notification in progress

        this.ListSubscribers.AddFirst(em);

 

        // Subscribe the new subscriber to the event.

        // The coupling between the publisher publishing and the subscriber subscribing is via the common delegate

        this.PayrollArrived += em.OnPayrollArrival;

    }

 

    // This event firing is synchronous - i.e. the publisher instance is tied down until the subscriber finishes processing OnPayrollArrival

    public void FireEvent(DateTime dayToFireEvent)

    {

        PublisherEventArgs args = new PublisherEventArgs();

        args.DateToFireEvent = dayToFireEvent;

 

        if (PayrollArrived != null)

            PayrollArrived(this, args);

    }

 

    // This is an asynchronous version of the same event-firing - just fire it - 

    // and do not CARE about how long the subscriber takes - since subscriber processing is on a different thread.

    // This works around the 'Badly behaved subscriber - Gotcha 1'.

    public void FireEventAsynchronous(DateTime dayToFireEvent)

    {

        if (PayrollArrived != null)

        {

            PublisherEventArgs args = new PublisherEventArgs();

            // We have more than one subscriber - employee 1 and empoyee 2. Each one subscribes via its own delegate. 

            // so - we need to loop over all the delegates

 

            Delegate[] delegates = PayrollArrived.GetInvocationList();

            foreach (Delegate del in delegates)

            {

                PayrollArrivedHandler handler = (PayrollArrivedHandler) del;

                handler.BeginInvoke(this, args, null, null);

            }

        }

    }

 

    public void RemoveSubscriber(Employee em)

    {

        this.PayrollArrived -= em.OnPayrollArrival;

    }

}

The Subscriber (Employee)

// Subscriber class – Employee – interested in knowing when the PayrollArrived event occurs

public class Employee 

{

   private string _name;

 

   public string Name

   {

       get { return _name; }

       set { _name = value; }

   }

 

   public Employee(string name)

   {

       this.Name = name;

   }

 

   public void OnPayrollArrival(object sender, PublisherEventArgs args)

   {

       DateTime dateToday = args.DateToFireEvent.Date;

 

       // Round up some friends and go spend the money!

       Console.WriteLine(this.Name + " was notified. Today is payday - date :" + dateToday);

   }

}

Most implementations out there have just the code above. They do not account for various things that can go wrong with a simple publish subscribe implementation.

 

What can go wrong? (The 4 main potential issues with any publish-subscribe implementation)

 

Gotcha 1 – The badly behaved subscriber

One rotten apple – blocks the others. When multiple subscribers are present – what if one of the subscribers blocks the publisher so that it is effectively not available to other subscribers?  This can easily occur if any one of the subscribers decide to do something lengthy in its event handler. How do we prevent such an occurrence?

Gotcha 2 – New Subscriber while notification is in progress

What if a subscriber is added while notification is in progress? Supposing the list of subscribers is being notified – and a new subscriber happens to come along (this is not a rare event – especially if any one of the subscribers happens to contain time-consuming code as in Gotcha 1) . What happens to the new subscriber? Does it get dropped? Do we add it? If so – where and when do we add it?

Gotcha 3 – Subscribers that fail to unsubscribe

A  good practice in .NET eventing is to ensure that all subscribers eventually unsubscribe from their events – once they are done handling it. Failure to do so leads to potential memory leaks.  This is actually one of the more common sources of memory leaks in .NET applications.

Gotcha 4 – Race conditions in the .NET framework

Race conditions in the .NET eventing framework – leading to inconsistent handling of events.

Workarounds for each of the Gotchas

 

Gotcha 1 Workaround 

The badly-behaved subscriber problem is best solved by working under the assumption that all subscribers will be badly behaved. So what is a publisher to do? One solution is to launch each notification on a new thread – that way even if a subscriber is badly behaved – it does not tie down the notification of other subscribers. Since the CLR in .NET provides a ready-made thread-pool, this is a seemingly simple solution. All one needs to do is use the built in support for asynchronous delegates (the event defined in the publisher class is really just a delegate – see sample below).

// This is an asynchronous version of the same event-firing - just fire it - 

// and do not CARE about how long the subscriber takes - since subscriber processing is on a different thread.

// This works around the 'Badly behaved subscriber - Gotcha 1'.

public void FireEventAsynchronous(DateTime dayToFireEvent)

{

    if (PayrollArrived != null)

    {

        PublisherEventArgs args = new PublisherEventArgs();

        // We have more than one subscriber - employee 1 and empoyee 2. Each one subscribes via its own delegate. 

        // so - we need to loop over all the delegates

        Delegate[] delegates = PayrollArrived.GetInvocationList();

        foreach (Delegate del in delegates)

        {

            PayrollArrivedHandler handler = (PayrollArrivedHandler) del;

            handler.BeginInvoke(this, args, null, null);

        }

    }

}

We are almost there. The only problem with the above code is a C# restriction – if you want to call BeginInvoke, your delegate (our event) can only have one target. We already have two targets (employee1.OnPayrollArrival and employee2.OnPayrollArrival) – so what do we do? Just loop over all the targets of our delegate – and call BeginInvoke on them one at a time. That should work around the original problem.

Gotcha 1 (Badly behaved subscribers) Workaround Summary

The badly-behaved subscriber problem is essentially addressed by launching each subscriber on a separate thread (and letting the subscribers stay badly behaved). We just don’t care – we’ve still managed to notify all the subscribers successfully.

Gotcha 2 (A subscriber is added while notification is in progress) Workaround

This is a slightly trickier problem to solve. We still want to allow the new subscriber to add itself – but we do not want to interfere with the current notification process. This solution is borrowed from Holub on Patterns – and works well in our scenario as well. The basic idea is that instead of having just ANY collection of subscribers – use a linked list to store subscribers.

Notification of the list of subscribers boils down to traversing the linked lists one node at a time. Say you are on some intermediate node – and a new subscriber arrives. Simply add the new subscriber (as a node) to the head of the list!

This way – it doesn’t interfere with the existing notification process – and is successfully added to the list of subscribers whenever the next notification comes around.

 

LinkedList<Employee> _listSubscribers = new LinkedList<Employee>();

public LinkedList<Employee> ListSubscribers

{

    get { return _listSubscribers; }

    set { _listSubscribers = value; }

}

// add new subscriber

   public void AddSubscriber(Employee em)

   {

       // Add new subscriber to the TOP of the linked list - this way it will not interfere with the notification in progress

       this.ListSubscribers.AddFirst(em);

Gotcha 2  Workaround Summary

Adding new subscribers while notification is in progress – is solved by ensuring that any new subscribers are added to the head of a linked list (containing all the subscribers)

Gotcha 3: Subscribers that fail to unsubscribe

The publisher holds a reference to every subscriber that has subscribed to its events. 2 subscribers – 2 references – 100 subscribers – 100 references. Unless each and every individual subscriber specifically unsubscribes after handling the event, the publisher does not release the reference to that subscriber. This leads to objects hanging around on the managed heap for longer than they are needed.

To work around this, simply ensure that a RemoveSubscriber method is available that can be called ON each subscriber (by the publisher) when it is done with the subscriber.

public void RemoveSubscriber(Employee em)

{

     this.PayrollArrived -= em.OnPayrollArrival;

}

Gotcha 3 Workaround Summary

Ensure that subscribers always unsubscribe from subscribed events when they are done. A simple RemoveSubscriber method as shown above can help accomplish this.

Gotcha 4 : Race Condition in the .NET eventing framework

This is not a publish-subscribe problem – but more an ‘eventing’ problem in the .NET framework. This ends up being a publish-subscribe problem nevertheless.

// initialize to empty delegate to avoid Gotcha 4 - race condition      

 public event PayrollArrivedHandler PayrollArrived = delegate {} ;

Gotcha 4 Workaround Summary

A simple workaround is to ensure that the event is always initialized to an empty delegate – this way it will never be null.

public event PayrollArrivedHandler PayrollArrived = delegate {} ;

 

Summary

The publish subscribe pattern is one of the most ubiquitous patterns in use today. Events and delegates in c# make it relatively simple to implement the pattern with a few lines of code. However, this implementation is prone to performance issues and potential bugs – if certain conditions are not handled up front.

With the 4 workarounds described in this post, the publish subscribe implementation (in C#) is as close to unbreakable as possible. Subscribers can continue to be long running , poorly behaved. Race conditions can try and cause unanticipated interjections. The simple workarounds in the sample code will handle these conditions.

These problems are especially noticeable when your event has a LARGE number of subscribers.

Full Source Code

Download Full Solution with the workarounds 

References

The post The Publish Subscribe Pattern in C# and some gotchas appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/the-publish-subscribe-pattern-in-c-and-some-gotchas/feed/ 5
A flexible service oriented architecture that handles multiple platforms (multiple devices, multiple databases…) https://www.anujvarma.com/a-flexible-service-oriented-architecture-that-handles-multiple-platforms-multiple-devices-multiple-databases/ https://www.anujvarma.com/a-flexible-service-oriented-architecture-that-handles-multiple-platforms-multiple-devices-multiple-databases/#respond Tue, 24 Apr 2012 18:57:15 +0000 http://www.anujvarma.com/a-flexible-service-oriented-architecture-that-handles-multiple-platforms-multiple-devices-multiple-databases/ The Problem Statement Imagine that you have just built a sophisticated application to work against a SQL Server database. You followed a best-practices approach and separated out your presentation, business […]

The post A flexible service oriented architecture that handles multiple platforms (multiple devices, multiple databases…) appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
The Problem Statement

Imagine that you have just built a sophisticated application to work against a SQL Server database. You followed a best-practices approach and separated out your presentation, business logic and data access layer. Your application is service oriented – and exposes a set of services to the outside world. For e.g. – your application offers an Account Service and a Security Service for consumption by the outside world.

  1. Now – you are told that this application needs to work against not just SQL Server – but Oracle as well.
  2. However, the services (AccountService, SecurityService) – will be somewhat different for the Oracle version. 
  3. While the services may be different, a lot of the functionality between the platforms will be similar.
  4. In addition, your design must be flexible (extensible). If more database platforms were added down the road – or more services to go along with the AccountService and the SecurityServices, the design should accommodate these with minimal changes.

This can be summarized as supporting multiple services for multiple platforms (these platforms do not have to be multiple databases – can be multiple OSes, multiple device platforms –e.g. Mobile and Desktop).   One of the key issues that this design presents is that of code commonality –  and code differentiation. Some of the code for the multiple platforms may be common to both the platforms. Example – when the AccountService creates an Account, there may be exception handling code that is common to both Oracle and SqlServer. In addition – a good deal of code would be completely unique to each platform – so – a SQLServer account creation would use SQLServer authentication whereas an Oracle account creation would use Oracle specific authentication.

This article presents an architecture to solve both of the problems above (keeping common code as well as differentiation platform specific code) – and provides a full sample implementation. This implementation can be used for various problems that require accommodating multiple services and multiple platforms. The possibilities are limitless – and I have used this on at least 2 projects successfully.  It allows for extensibility by allowing more services to be added – as well as more platforms to be added down the road.

Starting Point – Make it simple for the client

What would a sample client need to do to invoke a sample platform-specific service ? Say – a client wanted to use the AccountService specific to SqlServer. The snippet below shows everything that a client should need to do – get a handle to the SqlServer factory. This factory is responsible for all SqlServer specific services – so getting an AccountService back from this factory should be as simple as a GetService call. The snippet below shows everything that a client should need to do.

Code Snippet
  1.  
  2. ServiceFactory.SqlServerServiceFactory sqlFactory = new ServiceFactory.SqlServerServiceFactory();
  3. IAccountService acctService = sqlFactory.GetService<IAccountService>();

An Introduction to the overall architecture

To model the various services (AccountService, SecurityService…), we notice firstly that these services are unrelated to each other. A prospective implementation could implement both the AccountService and the SecurityService.  This leads us to explore an interface based approach for the set of services.

Services by Feature (Account, Security) Architecture – An Interface Based Approach

Code Snippet
  1. interface IAccountService
  2.   {
  3.       void CreateAccount();
  4.   }

 

Code Snippet
  1. interface ISecurityService
  2.     {
  3.         void AuthenticateUser();
  4.     }

Services By Platform (SQLServer, Oracle…) Architecture – An Inheritance Based Approach

For the platform differentiation, we note that some of the code may be common to both platforms – for e.g. – error handling and exception logging from the AccountService would need to be identical for both Oracle and SqlServer. We use an inheritance based approach – which allows us to use a Template pattern. The template pattern would provide a template method – that consists of a) Common Code b) Platform Specific Code

Code Snippet
  1. public virtual void CreateAccount()
  2. {
  3.  
  4.     //  common code – example – Initialize
  5.     Console.WriteLine("Account Service: Common Initialization Code");
  6.  
  7.     // Platform specific code
  8.     SomePlatformSpecificOperation();
  9.  
  10.     // common code again – example – cleanup()…
  11.     Console.WriteLine("Account Service: Common Cleanup Code");
  12.  
  13. }
  14.  
  15. protected virtual void SomePlatformSpecificOperation()
  16. {
  17.     Console.WriteLine("Some BASE operation that is common to both ORACLE and SQLServer. This can be over-riddent in the child classes for PLATFORM speficic functionality");
  18. }

The Overall Architecture – using Inheritance for Platform Variation – and interfaces for services

services_architecture_object_model_thumb

 

The Service Factory

The only other component (apart from the interface based services and the inheritance based platforms) that we need is a service factory – one that will return the appropriate feature service (e.g. Account Service) – along with the appropriate platform (e.g. SqlServerAccountService).

Code Snippet
  1. interface IServiceFactory
  2.     {
  3.        T GetService<T>();
  4.     }

A simple dictionary is used to store the list of services (AccountService, SecurityService…) – and a lookup method is provided as shown below:

Code Snippet
  1. private IDictionary<string, object> allservices = new Dictionary<string, object>();
  2.  
  3. public T GetService<T>()
  4. {
  5.     object service = null;
  6.     T returnedService = (T)service;
  7.     string serviceName = typeof(T).FullName;
  8.     if (allservices.TryGetValue(serviceName, out service))
  9.     {
  10.         returnedService = (T)service;
  11.     }
  12.  
  13.     return returnedService;
  14.  
  15. }

Summary

Almost every app today follows a service oriented architecture which exposes multiple services. If our app was limited to just that, the above interface based approach coupled with our Service Factory (to return a specific service) would be all that is needed. However, today’s services are not just feature based – but also tend to support multiple platforms. These multiple platforms could be multiple databases (e.g. SQLServer and Oracle on the backend), multiple devices (e.g. Desktop and Mobile), multiple OSes etc.

This post provides a full object oriented implementation that supports multiple platforms along with multiple services (features). The multiple services were modeled using interfaces. Then, to account for the different platform implementations of each service, we defined an inheritance hierarchy – coupled with a template pattern to handle code commonality between the different platforms.

  This proves to be an elegant solution for a common, real-world problem in Object Oriented projects. There are a multitude of possible applications of the above architecture. 

Perhaps the greatest strength of the above architecture is the extensibility it provides. One can add new database platforms and new services down the road – with ease and minimal code changes.

NOTE: Ideally, you would want to design a Data Access Layer that was agnostic of the underlying database. This layer would generate all your SQL statements (CRUD) without caring about what the underlying database platform was. Such a database agnostic data access layer is described in an earlier post here.

Full Solution Download

Services_By_Platform_Architecture Download Solution

The post A flexible service oriented architecture that handles multiple platforms (multiple devices, multiple databases…) appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/a-flexible-service-oriented-architecture-that-handles-multiple-platforms-multiple-devices-multiple-databases/feed/ 0
Session Storage – App Fabric Cache https://www.anujvarma.com/session-storage-app-fabric-cache/ https://www.anujvarma.com/session-storage-app-fabric-cache/#comments Mon, 05 Mar 2012 06:51:52 +0000 http://www.anujvarma.com/session-storage-app-fabric-cache/ Introduction (From Microsoft’s Azure Documentation) –  Windows Server AppFabric is a set of integrated technologies that make it easier to build, scale and manage Web and composite applications that run […]

The post Session Storage – App Fabric Cache appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
Introduction

(From Microsoft’s Azure Documentation) –  Windows Server AppFabric is a set of integrated technologies that make it easier to build, scale and manage Web and composite applications that run on IIS.

Session Management

Prior to cloud computing, there were only 3 options to storing your session data. InProc (in the runtime process’ memory), Out-of-Proc (SqlServer or StateServer). The out of proc option was usually used for high volume websites to accommodate server farms (sessions that need to persist across servers – need to be stored in an external medium such as a database).

With the advent of cloud computing, a 4th option was made available for storing session data. The AppFabric Cache. The AppFabric utilizes a distributed caching architecture which makes it highly scalable – and a worthwhile option to try for storing session data. 

So – what could go wrong?

Well – one of the more frequent exceptions that our event log showed was:

ErrorCode<ERRCA0014>:Cache::PutAndUnlock: Object being referred to is not locked by any client.

 

What was going on? We kept seeing this error over and over again. Turns out, that the AppFabric Session State Provider uses a lock on the session data at the start of each request. It only releases the lock when the request is completed. If the request takes too long, it keeps the lock and never releases it. The request times out (based on your normal HttpRuntime setting) – causing the AppFabric to retry the request (and also throw an exception before retrying). So – essentially – a long running request manifests itself as an AppFabric cache exception. This, in itself, is not terrible.  Except that all the ‘retries’ eventually end up exhausting IIS – and bringing the website to a crawl. This is what we were experiencing.

All the ‘retries’ on the part of the AppFabric were bringing IIS to a crawl.

Here is Microsoft’s official documentation on this session locking mechanism:

A lock  is set on session-store data at the beginning of the request  in the call to the GetItemExclusive method. When the request completes, the lock is released during the call to the SetAndReleaseItemExclusive method.

Workarounds

Workaround 1: Increase the request execution timeout : Now that we had an idea of why our sessions weren’t scaling (and why we were seeing all the exceptions in our event log), we asked Microsoft for some workarounds. Their only somewhat helpful suggestion was to increase the default Http request timeout (from 120 seconds to 300 seconds). This, in our opinion, was only a partial fix. It would not eliminate the exceptions entirely.

Workaround 1: HttpRuntime – execution timeout increase

Code Snippet
  1. <system.web>
  2.     <httpRuntime executionTimeout = "300"/>
  3.   </system.web>

Workaround 2: Store the session in sqlserver. Since the root of the exceptions was the session locking mechanism of the AppFabric cache, we decided to try not using that at all. Instead of storing sessions in the AppFabric cache, let us revert to the old, tried and tested SqlServer session storage (we had previously scaled up to 3000 simultaneous user sessions). In addition, we would isolate ourselves from any network latency issues (SqlServer would reside inside the intranet).

The actual steps in making this happen are surprisingly straightforward.

Step 1 – Create the supporting tables (to store session data) inside SqlServer.

aspnet_regsql.exe -S SampleSqlServer -E -ssadd -sstype p 
Notes – The ‘-E’ lets you use integrated windows security (without it, you would need to specify a SQL Server username –U and password -P)

Step 2: Modify the web.config file to specify SqlServer session storage.

Code Snippet
  1. <sessionState mode="SQLServer" sqlConnectionString="data source=127.0.0.1;user id="myuserid;password=mypassword" cookieless="false" timeout="20"/>

Summary

Am happy to report that, while they are still running more load tests, the application seems to be holding up well under a 10,000 user load. This is a 5 fold increase from the original 2000 that was bringing the website to a crawl.

Summary – Azure’s Scalability and Performance

The Microsoft Cloud offering (aka Azure aka AppFabric) is  something to reckon with for 2 reasons:

a) Ease of configurability (I doubt if any cloud offering can make it any easier than tweaking app.config files)

b) Scalability and Performance – While there are a few things Microsoft needs to address (such as better handling of the AppFabric cache’s ‘session locking’), overall, if your application doesn’t have any slow, unresponsive pieces, then the AppFabric itself will enable you to scale in hitherto, impossible ways.

The post Session Storage – App Fabric Cache appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/session-storage-app-fabric-cache/feed/ 1