WCF Publish Subscribe - A Full Example in C#, Step by Step Archives - Anuj Varma, Hands-On Technology Architect, Clean Air Activist https://www.anujvarma.com/series/wcf-publish-subscribe-c/ Production Grade Technical Solutions | Data Encryption and Public Cloud Expert Thu, 05 Dec 2013 16:04:00 +0000 en-US hourly 1 https://wordpress.org/?v=7.0.2 https://www.anujvarma.com/wp-content/uploads/anujtech.png WCF Publish Subscribe - A Full Example in C#, Step by Step Archives - Anuj Varma, Hands-On Technology Architect, Clean Air Activist https://www.anujvarma.com/series/wcf-publish-subscribe-c/ 32 32 WCF and Publish Subscribe–A Full Example: Running the Client (Subscriber) https://www.anujvarma.com/wcf-and-publish-subscribea-full-example-running-the-client-subscriber/ https://www.anujvarma.com/wcf-and-publish-subscribea-full-example-running-the-client-subscriber/#comments Thu, 28 Jul 2011 19:58:47 +0000 http://www.anujvarma.com/wcf-and-publish-subscribea-full-example-running-the-client-subscriber/ Now that all the pieces are in place, we are ready to run our client program.  The first error I encountered was: AddressAccessDeniedException: HTTP could not register URL http://+:8080/ Step […]

The post WCF and Publish Subscribe–A Full Example: Running the Client (Subscriber) appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
Now that all the pieces are in place, we are ready to run our client program.  The first error I encountered was:

AddressAccessDeniedException: HTTP could not register URL http://+:8080/

Step 1 – On running the Subscriber project, you may get an AddressAccessDenied exception (especially if you are on Windows Vista). To work around this error, launch a command prompt as administrator (right click and Run As Admin). In the command prompt, type :

netsh http add urlacl url=http://+:26836/ user=DOMAIN\UserName (do you need to lookup your username or your domain name ?).

Step 2 – What I needed was to provide local access to the address on which the client was running (the callback address). A tool called HttpNamespaceManager allowed me to grant that access to the http address+port that I needed. (See http://blogs.msdn.com/b/paulwh/archive/2007/05/04/addressaccessdeniedexception-http-could-not-register-url-http-8080.aspx for details). A quick summary of how to work around this error is given below:

1. Copy the http namespace from your DOS prompt.

dos_copy_url

2. Launch HttpNamespaces exe – Click Add – Paste the copied URL into the URL textbox that appears.

add_http_namespace

3. Grant access to the following USER GROUPS – USERS and LOCAL SERVICE. Once you add these groups, select them and check the ‘GenericExecute’ box as shown below.

USERS_group   execute_perms_users_group

Summary

Once you get past the Unhandled Exception: System.ServiceModel.AddressAccessDeniedException (using the steps above), you should be able to run the Subscriber console app (make sure you run the service first by starting the MagazineService project as shown below. You CAN run both from the same Visual Studio Solution Explorer).

launch_service

 

download full source codeWCFPublishSubscribe.zip

The post WCF and Publish Subscribe–A Full Example: Running the Client (Subscriber) appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/wcf-and-publish-subscribea-full-example-running-the-client-subscriber/feed/ 11
WCF and Publish Subscribe–A Full Example: Client Code https://www.anujvarma.com/wcf-and-publish-subscribea-full-example-client-code/ https://www.anujvarma.com/wcf-and-publish-subscribea-full-example-client-code/#comments Thu, 28 Jul 2011 19:55:37 +0000 http://www.anujvarma.com/wcf-and-publish-subscribea-full-example-client-code/ The subscriber needs to know about the service. We will use svcutil.exe to generate the proxy class for the subscribers to use. Step 1 : Ensure Service Loads Ok Use […]

The post WCF and Publish Subscribe–A Full Example: Client Code appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
The subscriber needs to know about the service. We will use svcutil.exe to generate the proxy class for the subscribers to use.

Step 1 : Ensure Service Loads Ok

  1. Use CRL F5 to start the Magazine service  – it should start running on a local port such as http://localhost:26836/. Click on MagazineService.svc to ensure that it is setup right (you will encounter errors if something was incorrect). The first error I encountered was related to the http binding. The default http binding is ‘BasicHttpBinding’  – and BasicHttpBinding does not support sessions (need wsDualHttpBinding for that) service_error_1 
  2. Inserting the following inside the <system.serviceModel> element fixed the issue                           <protocolMapping> <add scheme=httpbinding=wsDualHttpBinding/> </protocolMapping>
  3. Once the service fires up without errors (e.g. http://localhost:26836/MagazineService.svc), we are ready to generate our proxy.

Step 2: Generate the proxy

  1. Add a reference to System.ServiceModel in your Subscriber (client) project.
  2. On the Start menu click All Programs, and then click Visual Studio 2010. Click Visual Studio Tools and then click Visual Studio 2010 Command Prompt (you would need to ‘Run As Administrator’ if you are not logged on as the administrator).
  3. c:\Program Files\Microsoft Visual Studio 10.0\VC>svcutil /language:cs /out:generatedProxy.cs /config:app.config http://localhost:26836/MagazineService.svc
  4. Copy over the two files (generatedProxy.cs and app.config) to the folder containing the client project (subscriber project) – and ‘Add Existing Items’ to the project. Your solution should look something like this at this point.                                                                                                                                                                                                                                                                                                                                                                                    solution_explorer

Step 3: Client (Subscriber) Code

Now that we are done with the plumbing, we are ready to code our client.  Our client is just a subscriber who wants to be notified (on its callback method) whenever a new issue is available.

  1. A client class : Note that we already have a client class provided by the proxy. This is called  MagazineServiceClient.
public partial class MagazineServiceClient

     2.   A callback interface: The interface IMagazineServiceCallback is also available to us through our generated proxy.

Our client is just a subscriber who wants to be notified (on its callback method) whenever a new issue is available.

Here is the complete client code:

//The service contract is defined in generatedClient.cs, generated from the service by the svcutil tool.

//Client implementation code.

 

class Subscriber : IMagazineServiceCallback

{

        static void Main(string[] args)

        {

            // always create an instance context to associate the service with            

            InstanceContext siteHostContext = new InstanceContext(null, new Subscriber());

 

            MagazineServiceClient myClient = new MagazineServiceClient(siteHostContext);

 

            // create a unique callback address (if you want multiple subscribers to run on the same machine)

            WSDualHttpBinding binding = (WSDualHttpBinding)myClient.Endpoint.Binding;

            string uniqueCallbackAddress = binding.ClientBaseAddress.AbsoluteUri;

 

            // make it unique - append a GUID

            uniqueCallbackAddress += Guid.NewGuid().ToString();

            //uniqueCallbackAddress += 9;

            binding.ClientBaseAddress = new Uri(uniqueCallbackAddress);

 

            // Subcribe

            Console.WriteLine("subscribing...");

            myClient.Subscribe();

 

            Console.WriteLine();

            Console.WriteLine("Press ENTER to unsubscribe");

            Console.ReadLine();

 

            Console.WriteLine("unsubscribing...");

            myClient.Unsubscribe();

 

            // Closes the underlying http connection

            myClient.Close();            

        }

 

        public void MessageReceived(string linkToNewIssue, string issueNumber, DateTime publishDate)

        {

            Console.WriteLine("MessageRecei(item{0}, item{1}, item{2}", linkToNewIssue, issueNumber, publishDate);

        }

}

At this point, your project is complete. You have a working Service and a working client. See the next post – Running your client (adding a new subscriber and getting notified of new published events).

The post WCF and Publish Subscribe–A Full Example: Client Code appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/wcf-and-publish-subscribea-full-example-client-code/feed/ 1
WCF and Publish Subscribe–A Full Example: The Event Generator https://www.anujvarma.com/wcf-and-publish-subscribea-full-example-the-event-generator/ https://www.anujvarma.com/wcf-and-publish-subscribea-full-example-the-event-generator/#comments Thu, 28 Jul 2011 16:09:16 +0000 http://www.anujvarma.com/wcf-and-publish-subscribea-full-example-the-event-generator/ The purpose of the Event Generator code is to publish events (New Magazine Issue Available)  that subscribers will get notified about. Add a new Console App (Add New Project) to […]

The post WCF and Publish Subscribe–A Full Example: The Event Generator appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
The purpose of the Event Generator code is to publish events (New Magazine Issue Available)  that subscribers will get notified about.

  1. Add a new Console App (Add New Project) to the WCFPublishSubscribe solutionCall it EventGenerator.
  2. Copy over the app.config and the generatedProxy.cs to this new project.
  3. Publishing an event is as simple as invoking the Publish method (PublishMagazine) on the client (proxy class)
myClient.PublishMagazine("http://www.anujvarma.com", "Vol1: Issue1", System.DateTime.Now);

class EventGenerator: IMagazineServiceCallback

    {

        static void Main(string[] args)

        {

            // always create an instance context to associate the service with            

            InstanceContext siteHostContext = new InstanceContext(null, new EventGenerator());

            MagazineServiceClient myClient = new MagazineServiceClient(siteHostContext);

 

            Console.WriteLine("Publishing New Issue(http://www.anujvarma.com, Vol1: Number1, )");

            myClient.PublishMagazine("http://www.anujvarma.com", "Vol1: Issue1", System.DateTime.Now);

 

            Console.WriteLine();

            Console.WriteLine("Press ENTER to stop publishing events");

            Console.ReadLine();

 

            //Closing the client gracefully closes the connection and cleans up resources

            myClient.Close();

        }

 

        public void MessageReceived(string linkToNewIssue, string issueNumber, DateTime publishDate)

        {

            Console.WriteLine("MessageReceived(item{0}, item{1}, item{2}", linkToNewIssue, issueNumber, publishDate);

        }

    }

The post WCF and Publish Subscribe–A Full Example: The Event Generator appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/wcf-and-publish-subscribea-full-example-the-event-generator/feed/ 1
WCF Publish Subscribe– A Full Example: The Service Side Part 2 (Implementation) https://www.anujvarma.com/wcf-publish-subscribe-a-full-example-the-service-side-part-2-implementation/ https://www.anujvarma.com/wcf-publish-subscribe-a-full-example-the-service-side-part-2-implementation/#comments Thu, 28 Jul 2011 16:02:11 +0000 http://www.anujvarma.com/wcf-publish-subscribe-a-full-example-the-service-side-part-2-implementation/ Our implementation is based on .NET events (for a non-events based implementation, check out the New IObserver IObservable interfaces in C# 4.0). The idea of publishing goes hand-in-hand with ‘raising […]

The post WCF Publish Subscribe– A Full Example: The Service Side Part 2 (Implementation) appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
Our implementation is based on .NET events (for a non-events based implementation, check out the New IObserver IObservable interfaces in C# 4.0). The idea of publishing goes hand-in-hand with ‘raising an event’  – and the idea of subscribers goes hand-in-hand with consuming an event.

Our event based implementation thus consists of:

  1. Defining an event
  2. Defining an  event handler (all the handler will do is notify the various subscribers)
  3. Implement the Subscribe method
  4. Implement the Unsubscribe method
  5. Implement the PublishMagazine method
public class NewIssueAvailableEventArgs : EventArgs

{

    public string hyperlinkURL;

    public string issueNumber;

    public DateTime datePublished;

}

 

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]

public class MagazineService : IMagazineService

{

    public static event NewIssueAvailableHandler NewIssueAvailableEvent;

    public delegate void NewIssueAvailableHandler(object sender, NewIssueAvailableEventArgs e);

 

    // instance of eventhandler

    NewIssueAvailableHandler newIssueHandler;

 

    // Callback to individual clients using the ClientContract

    IClientContract callback = null;

 

    public void PublishMagazine(string hyperLinkToIssue, string issueNumber, DateTime datePublished)

    {

        NewIssueAvailableEventArgs eargs = new NewIssueAvailableEventArgs();

        eargs.hyperlinkURL = hyperLinkToIssue;

        eargs.issueNumber = issueNumber;

        eargs.datePublished = datePublished;

 

        // fire the event

        NewIssueAvailableEvent(this, eargs);

    }

 

    public void Subscribe()

    {

        callback = OperationContext.Current.GetCallbackChannel<IClientContract>();

        // this is the handler that we will 'unsubscribe' from later

        newIssueHandler = new NewIssueAvailableHandler(MagazineService_NewIssueAvailableEvent);

        NewIssueAvailableEvent += newIssueHandler;

    }

 

    public void Unsubscribe()

    {

        NewIssueAvailableEvent -= newIssueHandler;

    }

 

    public void MagazineService_NewIssueAvailableEvent(object sender, NewIssueAvailableEventArgs e)

    {

        callback.MessageReceived(e.hyperlinkURL, e.issueNumber, e.datePublished);

    }

}

The post WCF Publish Subscribe– A Full Example: The Service Side Part 2 (Implementation) appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/wcf-publish-subscribe-a-full-example-the-service-side-part-2-implementation/feed/ 8
WCF Publish Subscribe–A Full Example – The Service Side Part 1 (Interface) https://www.anujvarma.com/wcf-publish-subscribea-full-example-the-service-side-part-1-interface/ https://www.anujvarma.com/wcf-publish-subscribea-full-example-the-service-side-part-1-interface/#comments Thu, 28 Jul 2011 15:59:14 +0000 http://www.anujvarma.com/wcf-publish-subscribea-full-example-the-service-side-part-1-interface/ The Service code consists of an Interface (IMagazineService) and its implementation (MagazineService). The Interface defines all the capabilities of the service. What do we really want from a Publisher service? […]

The post WCF Publish Subscribe–A Full Example – The Service Side Part 1 (Interface) appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
The Service code consists of an Interface (IMagazineService) and its implementation (MagazineService).

The Interface defines all the capabilities of the service. What do we really want from a Publisher service?

  1. A Publish method (called PublishMagazine)
  2. A Subscribe method (to allow clients to subscribe to the service)
  3. An Unsubscribe method (to allow clients to unsubscribe from the service)

Those are the three main things we need from our Publisher service. As long as all we need is the Publisher to get in touch with multiple subscribers, we are all set.

However, we also need a way to notify individual clients (subscribers) who have subscribed to our service. 

This can be handled via a Callback method (called MessageReceived in our example). The Callback method is best made available as part of a separate interface (known as IClientContract).

public interface IClientContract

{

    [OperationContract(IsOneWay = true)]

    void MessageReceived(string hyperlinkToNewIssue, string issueNumber, DateTime datePublished);

}

[ServiceContract(SessionMode = SessionMode.Required, CallbackContract = typeof(IClientContract))]

public interface IMagazineService

{

    [OperationContract(IsOneWay = false, IsInitiating = true)]

    void PublishMagazine(string hyperLinkToIssue, string issueNumber, DateTime datePublished);

    [OperationContract(IsOneWay = false, IsTerminating = true)]

    void Subscribe();

    [OperationContract(IsOneWay = false, IsTerminating = true)]

    void Unsubscribe();

 

}

 

public interface IClientContract

{

    [OperationContract(IsOneWay = true)]

    void MessageReceived(string hyperlinkToNewIssue, string issueNumber, DateTime datePublished);

}

The post WCF Publish Subscribe–A Full Example – The Service Side Part 1 (Interface) appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/wcf-publish-subscribea-full-example-the-service-side-part-1-interface/feed/ 2
WCF and Publish Subscribe– A Full Example: Introduction https://www.anujvarma.com/wcf-and-publish-subscribe-a-full-example-introduction/ https://www.anujvarma.com/wcf-and-publish-subscribe-a-full-example-introduction/#comments Thu, 28 Jul 2011 15:56:33 +0000 http://www.anujvarma.com/wcf-and-publish-subscribe-a-full-example-introduction/ Imagine that you are a magazine publishing company. Your revenue depends on subcribers – in particular, happy subscribers. To ensure that your subscribers stay happy, one of the foremost services […]

The post WCF and Publish Subscribe– A Full Example: Introduction appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
Imagine that you are a magazine publishing company. Your revenue depends on subcribers – in particular, happy subscribers. To ensure that your subscribers stay happy, one of the foremost services you need to provide is timely noticification whenever a new issue is out.

What do you (the magazine publisher) need to do?

You need to implement the publisher side of the publish-subscribe pattern.

What do your customers (subscribers) need to do?

Each customer needs to implement the subscriber part of the publish-subscribe pattern.

The post WCF and Publish Subscribe– A Full Example: Introduction appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/wcf-and-publish-subscribe-a-full-example-introduction/feed/ 1