Sunday, January 18, 2015

Publisher/Subscriber pattern with Event/Delegate and EventAggregator

Shout it kick it on DotNetKicks.com

Publisher/Subscriber pattern

Publisher/Subscriber pattern is one of the variation of the Observer designer pattern introduced by GOF in software devlopment. In Publisher/Subscriber pattern publisher(entiry responsible for publishing message) publish message and there are one or more Subscriber(entity who subsribe(i.e. intested in message) to perticular message type)  who capture published message. Below image desribe the senario of publisher and subscriber pattern where Publisher publisher two type of message (MessageA and MessageB) and Subscribers of the message receive the message in which they subscribed (Subscriber1 capture MessageA and Subscriber2 & Subscriber3 capture MessageB).




To understand this consider Real life senario where Mobile operators sending message to their customers.



As in above image Mobile operator publisher(brodcast) message (Message of Cricket Score and Message of Laster News) and message capture by the customer cells who subscribed for the message(Customer1 & Customer2 capture cricket score message and Customer3 & Customer4 capture latest news message).

Implementation with Event

Oneway to achieve Publisher/Subscirber pattern in application is make use of Event/Delegate i.e. with the help of framework. Below is deatil description of publisher/subscriber implementation

Message - Below is class which represent message that is publish by Publisher and capture by interested Subscriber.

    public class MessageArgument<T> : EventArgs
    {
        public T Message { get;  set; }
        public MessageArgument(T message)
        {
            Message = message;
        }
    }
In technical term MessageArgument is generic class so instance of this class can be of any type which is represent by T template type.

Publisher  - as already descibed above in defination, Publisher is responsible for publish message of diffrent types.

    public interface IPublisher<T>
    {
        event EventHandler<MessageArgument<T>> DataPublisher;
        void OnDataPublisher(MessageArgument<T> args);
        void PublishData(T data);
    }

    public class Publisher<T> : IPublisher<T>
    {
        //Defined datapublisher event
        public event EventHandler<MessageArgument<T>> DataPublisher;

        public void OnDataPublisher(MessageArgument<T> args)
        {
            var handler = DataPublisher;
            if (handler != null)
                handler(this, args);
        }


        public void PublishData(T data)
        {
            MessageArgument<T> message = (MessageArgument<T>)Activator.CreateInstance(typeof(MessageArgument<T>), new object[] { data });
            OnDataPublisher(message);
        }
    }

Technically Publisher is generic class which inherit IPublisher interface, as Publisher is generic class instace of it can be of any type which is represented by T template type. Publisher Instance of created of selected given type publish on that type of message only. For publishing differnt type message it requires to create  different type of Publisher Instace. To understand better read below how to use publisher in client class code.

Publisher Class provide event DataPublisher , subscriber attach themself to this event to listen the message.
PublishDta is publisher class method that publish data to Subscribers.

Subsriber - Subscriber captures message of the type it intreseted in.

   public class Subscriber<T>
    {
        public IPublisher<T> Publisher { get; private set; }
        public Subscriber(IPublisher<T> publisher)
        {
            Publisher = publisher;
        }
    }
Technally Subscriber is genric class allows to create multiple instace of subsriber and each subsriber subsribe to message it intested it using publisher.

Subsriber pass instace of perticular type publisher to capture message publisher by that Publisher.

How it works

    public class Client
    {
        private readonly IPublisher<int> IntPublisher;
        private readonly Subscriber<int> IntSublisher1;
        private readonly Subscriber<int> IntSublisher2;

        public Client()
        {
            IntPublisher = new Publisher<int>();//create publisher of type integer

            IntSublisher1 = new Subscriber<int>(IntPublisher);//subscriber 1 subscribe to integer publisher
            IntSublisher1.Publisher.DataPublisher += publisher_DataPublisher1;//event method to listen publish data

            IntSublisher2 = new Subscriber<int>(IntPublisher);//subscriber 2 subscribe to interger publisher
            IntSublisher2.Publisher.DataPublisher += publisher_DataPublisher2;//event method to listen publish data

            IntPublisher.PublishData(10); // publisher publish message
        }

        void publisher_DataPublisher1(object sender, MessageArgument<int> e)
        {
            Console.WriteLine("Subscriber 1 : " + e.Message);
        }

        void publisher_DataPublisher2(object sender, MessageArgument<int> e)
        {
            Console.WriteLine("Subscriber 2 : " + e.Message);
        }
    }
As you can see in the above code Client is class which create publisher and subsriber. Client class creates Publisher of integer type (in practicle you can careate any time of publisher) and creates two Subsriber classes which subscribe to the publisher message by attaching DataPublisher event which is provide by Publisher class.

So when you care instace of Client class you will receive following output



So as per the ouput Publisher of integer type published message "10" and two Subsriber who subscribed to publisher capture and displays message to output.

In practicle senario i.e. in actual application, one need to create all publisher at application start point i.e. at entrypoint of app and pass instace of publisher when creating subscriber.

For Example in Windows application create publisher in Main() Method , in Web Application create publisher in Appication_Start method of Global.asax or make use of Dependacy Injection in which you register your publisher and use container to create when needed.
Once created you can pass the publisher in Subscriber as done in above client class code.

Implementation with EventAggregator

EventAggregator - by name one can easily say the it aggraegat events. In Publisher/Subscriber EventAggregator is woks as HUB whos task is to aggregate all publish message and send message to interested subscribers.



As you can see in above image EventAggregator comes as HUB between publisher and Subscriber , it works like this
  1. Publisher publish message
  2. EventAggregator Receives message send by publishers
  3. EventAggregator get list of all subscirber interesed message
  4. EventAgregator sends message to interested subscriber
EventAggregator Implementation

SubScription - It class which used to create subscription token. When Subsriber subscribe to intereset message type via EventAggregator return Subscription token which further used by Subscriber to keep track of its subscription.

    //Does used by EventAggregator to reserve subscription
    public class Subscription<Tmessage> : IDisposable
    {
        public Action<Tmessage> Action { get; private set; }
        private readonly EventAggregator EventAggregator;
        private bool isDisposed;
        public Subscription(Action<Tmessage> action, EventAggregator eventAggregator)
        {
            Action = action;
            EventAggregator = eventAggregator;
        }

        ~Subscription()
        {
            if (!isDisposed)
                Dispose();
        }

        public void Dispose()
        {
            EventAggregator.UnSbscribe(this);
            isDisposed = true;
        }
    }

EventAggregator -

    public class EventAggregator
    {
        private Dictionary<Type, IList> subscriber;

        public EventAggregator()
        {
            subscriber = new Dictionary<Type, IList>();
        }

        public void Publish<TMessageType>(TMessageType message)
        {
            Type t = typeof(TMessageType);
            IList actionlst;
            if (subscriber.ContainsKey(t))
            {
                actionlst = new List<Subscription<TMessageType>>(subscriber[t].Cast<Subscription<TMessageType>>());

                foreach (Subscription<TMessageType> a in actionlst)
                {
                    a.Action(message);
                }
            }
        }

        public Subscription<TMessageType> Subscribe<TMessageType>(Action<TMessageType> action)
        {
            Type t = typeof(TMessageType);
            IList actionlst;
            var actiondetail = new Subscription<TMessageType>(action,this);

            if (!subscriber.TryGetValue(t, out actionlst))
            {
                actionlst = new List<Subscription<TMessageType>>();
                actionlst.Add(actiondetail);
                subscriber.Add(t, actionlst);
            }
            else
            {
                actionlst.Add(actiondetail);
            }

            return actiondetail;
        }

        public void UnSbscribe<TMessageType>(Subscription<TMessageType> subscription)
        {
            Type t = typeof(TMessageType);
            if (subscriber.ContainsKey(t))
            {
                subscriber[t].Remove(subscription);
            }
        }

    }
In above code

Dictionary<Type, IList> subscriber - is dictionary in which Type is Type of message and IList is list of action. So it holds list of action mapped to perticular Mesagsse Type.

public void Publish<TMessageType>(TMessageType message) - is method used to publishing message. As in code this method does receives message as input than it filterout list of all subscriber by message type and publish message to Subscriber.

public Subscription<TMessageType> Subscribe<TMessageType>(Action<TMessageType> action) - is method used to subsribe interested message type. As in code this method recevies Action delegate as input. It maps Action to perticular MessageType, i.e. it create entry for message type if not present in dictionary and maps Subscription object  (which waps Action) to message entry.

public void UnSbscribe<TMessageType>(Subscription<TMessageType> subscription) - is method used to unsubscribe form perticular message type. It receives Subscription object as input and remove object from the dictionary.

How To Use

      static void Main(string[] args)
        {
            EventAggregator eve = new EventAggregator();
            Publisher pub = new Publisher(eve);
            Subscriber sub = new Subscriber(eve);

            pub.PublishMessage();

            Console.ReadLine();

        }
As in above code shows it first create instace of EventAggregator which pass as agrument to publisher and subscriber, than publisher publish message.

Publisher - Code of Publisher class , which shows how publisher publish message using EventAggregator

 public class Publisher
    {
        EventAggregator EventAggregator;
        public Publisher(EventAggregator eventAggregator)
        {
            EventAggregator = eventAggregator;
        }

        public void PublishMessage()
        {
            EventAggregator.Publish(new Mymessage());
            EventAggregator.Publish(10);
        }
    }

Subscriber - Code of Subscriber class, which shows subscriber subscribe to messages which it intersted in using EventAggregator.

    public class Subscriber
    {
        Subscription<Mymessage> myMessageToken;
        Subscription<int> intToken;
        EventAggregator eventAggregator;

        public Subscriber(EventAggregator eve)
        {
            eventAggregator = eve;
            eve.Subscribe<Mymessage>(this.Test);
            eve.Subscribe<int>(this.IntTest);
        }

        private void IntTest(int obj)
        {
            Console.WriteLine(obj);
            eventAggregator.UnSbscribe(intToken);
        }

        private void Test(Mymessage test)
        {
            Console.WriteLine(test.ToString());
            eventAggregator.UnSbscribe(myMessageToken);
        }
    }

Output



Note:
In practicle senario i.e. in actual application, one need to create EventAggregator at application start point i.e. at entrypoint of app and pass instace of publisher and subscriber.

For Example in Windows application create EventAggregator in Main() Method as in above example code, in Web Application create publisher in Appication_Start method of Global.asax or make use of Dependacy Injection in which you register your publisher and use container to create when needed.

Event/Delegate Vs. EventAggregator

Differnce between Event/Delegate and EventAggregator is
Event/Delegate EventAggregator
For publishing Diffrent type of message there is need of creating diffrent type of Publisher
For Example : Publisher - for integer type publisher Publisher - for string type publisher So the if class want to publish diffrent type of messages it require to consume or create differnt type of publisher.
To publish integer abd string type message publisher class will be Publisher(Publisher intPublisher, Publisher strPublisher).
As EventAggregator works as HUB there is no need create more than one instance of Eventaggregator and publisher just need to consume it. Example : Publisher(EventAggregator eventAggregator)
Tight Coupling bettwen Publisher and Subscriber. In this pattern Subscriber require to know publisher as they subscribe to event of publisher. Loose Coupling between Publisher and Subscriber. In this pattern as EventAggregator is midator Publisher and Subscriber dont know each other they just need to know EventAggregator.

Conclusion

It's my Point of view , Event/Delegate is easy to implement and good for the small project or in project where thre are less number of Publisher/Subscriber. EventAggregator is suitable for the large project or project which is having large number of Publisher/Subscirber.
But I think its always good to use EventAggregator because its offer loose copuling.

NOTE
It's my point of view please do comment on this and provide your feedback.

Wednesday, February 12, 2014

Help Yourself in Debugging (Part-3) StackTrace and Caller Information attribute

Shout it kick it on DotNetKicks.com
Read below post related to same topics
  1. Help yourself in Debugging by using Call Stack and Immediate Window  
  2. Help Yourself in Debugging (Part-2) using Breakpoint/Tracepoint
This post is about two feature in C# Caller Information Attribute and StackTrac class , which are helpful to get information at runtime from where the call came i.e. both provide information about caller. As purpose of both is same but there is significant difference between both of them. Information provided by both can be used by developer application to provide trace information.

Before start with StackTrace and Caller information following image shows structure of the code.



So the project is divided in three layer UI, Business and DataLayer.

Front Layer code 

class Program
    {
        //Program p = new Program();

        public int i = 10;
        public static void Main(string[] args)
        {
            try
            {
                var str = (new BusinessEmployee()).GetEmployeeList();
                Console.WriteLine(str);
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                global::System.Windows.Forms.MessageBox.Show(ex.Message);
            }

        }
    }
As you see in above code Font layer calling “GetEmployeeList” method to get list of all employee.

BusinessLayer code 
 
    public class BusinessEmployee
    {
        private readonly DataEmployee dataEmployee;

        public BusinessEmployee()
        {
            dataEmployee = new DataEmployee();
        }

        public  void GetEmployeeList()
        {
            dataEmployee.GetEmployeeList();
        }
    }
In this layer Business class calling DataLayer to get employee list from the database.

DataLayer code

    public class DataEmployee
    {
        //Data layer class for employee 
        public  void GetEmployeeList()
        {
            //code goes here for retiving from DATABASE
        }
    }
This layer return employee list, but for the example its returning exception.

 

StackTrace

Class in C# part of System.Diagnostics name space which provide information same as Call Stack window (Read more about Call stack window ) at runtime.

To understand it better way lets consider change in above code in DataLayer
        //Data layer class for employee 
        public string GetEmployeeList()
        {
            //// get call stack
            StackTrace stackTrace = new StackTrace(true);

            StringBuilder sb = new StringBuilder();

            foreach (StackFrame frame in stackTrace.GetFrames())
            {

                sb.AppendLine(" Method Name: " + frame.GetMethod().Name + " File Name:" + frame.GetMethod().Module.Name + " Line No: " +                   
                                   frame.GetFileLineNumber());
            }

            return sb.ToString();
        }

As you can see in code it create StackTrace class and when creating new object of class "true" is passed as argument to the constructor of StackTrace class for capturing the file name, line number, and column number.
After the object get created GetFrames method is usd to get information about each frame(each method call is represented by one frame) and finally each frame details is appeded using StringBuilder, then it displayed by front end.

Following is output get recieved once the code run


So output prints each call made from one layer to antoher if you see above code call is coming from the fron layer to database layer.

Advatage 
  • StackTrace provide detail informaiton about from where call came from the beggining till end. This is one resason devloper can use StackTrace when there is need to get i.e. trace details level information. 
  • Also StackTrace frame also provide control on the caller method, provide assebmbly from where call is coming. 
Disadvantage
  • Inline method  is not get listed when code compiled in Relase mode, which is get listed when code compiled in Debug mode.
         To understand it cosider below code changes in front layer code.



 Now if you compile code in Debug mode with below configuration
  

  
It will generate below output for you , where you can see four line i.e. on extra line of calling to method "GetEmployeeList1".



So debug list all method calls But Now if you compile code in Release mode with below configuration




It will generate below output for you , where you can see three line.  The line of calling method "GetEmployeeList1" is missing.


So StackTrace doesn't list out methods which is converted to inline method by compiler. if you want to list out you can mark method as [MethodImpl(MethodImplOptions.NoInlining)]



if devloper mark method as [MethodImpl(MethodImplOptions.AggressiveInlining)] than the method also no get list in debug
So StackTrace information can be spoof by making method inline.
  • As StackTrace provide every minute detail, StackTrace will show the full trace right into the core MS sourced assemblies, and will reveal details about what technologies you're using, and possible versions as well. This gives intruders valuable info on possible weaknesses that could be exploited. So always careful before displaying this information and put security on this.
Advantage over Caller Information attribute
  • It provides minute details which is not possible with Caller Inormation attribute.
  • Line number, Filename and Method Name information is given by StackFrame which cannot be changed by devloper But in case of Caller Information attribute devloper can spoof by passing wrong value in caller information parameter.

 

Caller Information attribute

This is new feature introduce in C# 5.0. and attributes are part of System.Runtime.CompilerServices namespace. These attributes required to be added as optional parameter in the method for which need to get caller information.
 Example
Accessiblity ReturnType MethodName (Type parameterName,....,         
                                    [CallerMemberName] string memberName = "",
                                    [CallerFilePath] string sourceFilePath = "",
                                    [CallerLineNumber] int sourceLineNumber = 0

Name Type Description
CallerMemberName string Provide caller method Name
CallerFilePath string Provide caller method File Name
CallerLineNumber int Provide caller Line number in File from where method get called


Note :
Caller of the method can aslo pass this value as this attribute added as parmeter to method.

Example when calling method which is decorated by caller information attribute


To understand this let do change in the DataLayer method like this
        
         //Data layer class for employee 
        public string GetEmployeeList([CallerMemberName] string memberName = "",
                                     [CallerFilePath] string fileName = "",
                                    [CallerLineNumber] int lineNumber = 0)
        {

            return " Method Name: " + memberName + " File Name:" + fileName + " Line No: " + lineNumber;
        }
 So running above code provide below output


Advantage
  • Information of caller attribute cannot be spoofed till devloper pass informaton in method parameter.
  • There is no rutime cost for this i.e. it doesnt affect performance of the code as attribute are compile time.
  • Very hepfull to find out when call is coming from some unknonw location like in case of "PropertyChange". 
Disadvatage
  • Information of caller can be spoofed by devloper if devloper pass wrong information in the parameter of the caller information.
  • There is only one StacFrame i.e. it will give information about who called method(immediate caller of method) but doesnt provide detail information like StackTrace. 
  • It's part of C# 5.0 so its not working with older version of framework. 
Advantage over StackTrace
  • As its complied time there is no rutime cost like StackTrace ( we need to create object of StackTrace runtime to get information).
  • Information provided by attribute cann not be Spoofed by method attributes.
Do Comment if the information is missing or wrong.

Referenced from 

Monday, January 27, 2014

Getting Exact Location of Exception in C# Code

Shout it kick it on DotNetKicks.com
Post is about locating exact location of the Exception in the code. There is always problem for the developer to locate exact location from where Exception raised, because of that it difficult for the developer what actually went wrong. Most of the time problem occurs when there is too many libraries referenced i.e. used in project.

To understand let’s consider below example:
In following example application is divided in three layers
  1. Font end - Layer though which user interact with application and Displays data to end user of application.
  2. Business -Layer which is having business logic, code to call datalayer and the info classes which transport between font and data layer.
  3. Data - Layer which interact with database and supply data to business layer.
Front Layer code 

class Program
    {
        //Program p = new Program();

        public int i = 10;
        public static void Main(string[] args)
        {
            try
            {
                (new BusinessEmployee()).GetEmployeeList();
            }
            catch (Exception ex)
            {
                global::System.Windows.Forms.MessageBox.Show(ex.Message);
            }

        }
    }
As you see in above code Font layer calling “GetEmployeeList” method to get list of all employee.

BusinessLayer code 
 
    public class BusinessEmployee
    {
        private readonly DataEmployee dataEmployee;

        public BusinessEmployee()
        {
            dataEmployee = new DataEmployee();
        }

        //Business layer class for employee 
        public  void GetEmployeeList()
        {
            dataEmployee.GetEmployeeList();
        }
    }
In this layer Business class calling DataLayer to get employee list from the database.

DataLayer code

    public class DataEmployee
    {
        //Data layer class for employee 
        public  void GetEmployeeList()
        {
            throw new Exception("Not able to fetch employee");
        }
    }
This layer return employee list, but for the example its returning exception.

Now if you run above code by putting it into respected layer, then when exception thrown by the actual code debugger break execution in the front layer code. Below image shows same thing.



So it becomes difficult for the developer what went wrong if there is actual complex code is there.

Solution
 In Visual studio there is option as given in below image that allows to break debugging at the point i.e. at the code from where exception is coming.



Once you clicked on menu option it will open up dialog box where you can mark tick on “Common Language Runtime Exception” as in below image and click ok.



Now if you run same code than debugger will stop at exact location from where exception is coming, you can also see below image.


So breaking at exact location from where error is coming you can find out which part is actually causing problem and help to resolve error easily.


Conclusion
Visual studio option to locate exception also very helpful when there is multiple threads doing operation and throws exception. Also locate exceptions dialog provide other option that is also help full when you are using JavaScript, com component etc. that you can try by yourself.