Home > 2014

2014

Reactive Extensions: Observing an Event

Thursday, November 13, 2014 Category : , , 0

In the last post, NEsper (.NET library on Esper for Java) complex event processing was discussed. This post discusses the basics of observing a simple .NET event using .NET Reactive Extensions.

.NET Reactive Extensions build on IObservable and make event based programming simpler. One advantage I came across of using RX over NEsper is that it is easier to write unit tests. NEsper hides a lot of its functionality in internal libraries for which writing unit test cases tightly integrates with the NEsper queries and it may not be possible to cover everything. In the same breath, it also comes to mind that performance-wise NEsper may perform better since it is Java based. Performance comparison of NEsper and RX to be done in one of the subsequent posts.

For now, this post focuses on writing a very simple example of how to observe another class' events. Let us assume we have a data generator class:
 internal class SomeDataGenerator
    {
        public event EventHandler ev;
        Timer tim;
        public SomeDataGenerator()
        {
            tim = new Timer();
            tim.Interval = 1000;
            tim.Elapsed += tim_Elapsed;
            tim.Start();
        }

        void tim_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (ev != null)
                ev(this, null);
        }
    }
For observing such an event that conforms to the standard .NET event pattern (having two parameters - sender and eventargs), we can use the Observable.FromEventPattern method from the System.Reactive.Linq library:
public static event EventHandler SimpleEvent;
        static void Main(string[] args)
        {
            SomeDataGenerator dg = new SomeDataGenerator();
            IObservable<EventPattern<object>> eventAsObservable = Observable.FromEventPattern(
               ev => dg.ev += ev,
               ev => dg.ev -= ev); 
            

            Console.WriteLine("Subscribe");
            var subs = eventAsObservable.Subscribe(ar => Console.WriteLine("Received event..."));
           

            Console.Read();
        }


The above code creates an instance of the data generator class (SomeDataGenerator). The FromEventPattern method allows attaching and detatching to the event we want to observe, which is dg.ev. Once we start observing the event, we can subscribe to the event firing by calling Subscribe on the observable.

So whats the big deal? We can do that by attaching events anyway in .NET without RX. The difference is apparant when we try to do something more complex like filtering data out of an incoming stream of data| or grouping it | or performing aggregations on windows like moving average. This code subscribes to each firing of the event. So the code given to Subscribe is called everytime the event is raised. This behaviour can be changed for grouping/aggregating/complex-merging the continuous stream of data thrown by SomeDataGenerator. Detailed sample to be discussed in next post on that.

NEsper Complex Event Processing: Pattern Matching

Saturday, October 11, 2014 Category : , 0

This article discusses the basics of complex event processing and pattern matching in streaming data using NEsper (.NET).

What is Complex Event Processing (CEP)

 

Before discussing the details of how NEsper can be used for matching patterns in streaming data, first some information on what complex event processing is. In most of the applications created these days, the data is first stored (in a relational or non-relational database/datastore) and then queried later to get results. These results obtained from pre-stored data are a sort of snapshot for the instant at which the results are fetched. If the same query is run 10 seconds later, we may get different results since the underlying data may have changed by then.

Complex event processing turns that model around and says that instead of storing the data, store the queries. Data can then be made to pass through these queries (or rules) as and when it arrives and can be pushed in the processed form to all the interested parties (including a persistence engine).

CEP Uses

The processing of streaming data can be useful in many scenarios. For example, in stock market trading, we may have market data of a given ticker arriving at intermittent intervals. The price of a given ticker does not change every second but it may change any second. These changes can arrive as a stream and can then be used for calculating moving averages and other calculations can be performed on them to predict whether the ticker is on an upward trend or downward trend.
Another possible scenario can extend the previous scenario by joining the market data stream with the actual trading data (buy/sell) stream of a given user in a day to predict whether the total profit of the user is in an upward trend or a downward trend.

CEP Advantages

The first advantage of CEP is performance. Since the data is analyzed and processed as and when it arrives, operations are performed on small bits of data instead of on the entire data at once. Thus, the cost of performing operations is small.

The second advantage of CEP is real-time analysis. Since updates are pushed immediately to concerned parties and results updated, data is always fresh. Re-querying data is not required.

NEsper CEP

NEsper is the CLR based component for Esper for Java and provides stream processing capabilities for an event driven system. More information on ESper is available at:
http://esper.codehaus.org/about/esper/esper.html

NEsper Pattern Matching

The source code for this discussion is available at:

This code sample contains a very basic UI:


The following entries are available in the drop-down, which represent the actions that a programmer-next-door performs every single day:



Based on the sequence in which the items on this list are selected, the prediction changes.  For example, try selecting Scroll:



The text at the bottom changes to “programmer On a quest”.

Similarly, for a more complex sequence of events, if Minimize is selected, followed by Maximize, followed by Scroll, the prediction is that the programmer is bored:



If this is followed by Lock:


You get the idea.

While all this is going on, NEsper is remembering the previous data that came and adding on the new data to it to try and make sense of the rules given to it.

At the code level, it is pretty basic. For simplicity’s sake, all code has been kept in one file: Form1.cs. The form itself performs 3 important functions when the constructor fires:



The first function “InitializeEPLStatements” is the core here. It defines all the queries that we are storing in NEsper. These are the queries that run each time new data arrives. Let’s take a look at one of these:

 
"SELECT \"recharging\" FROM pattern [every a=Payload(PayloadText=\"Minimize\") -> every b=Payload(PayloadText=\"Maximize\") -> every c=Payload(PayloadText=\"Scroll\") -> every d=Payload(PayloadText=\"Coffee\")]"

The arrow symbol in the above query (->) indicates “followed by”. So, represented simply, this query is of the following format:

Event “a” (followed by) Event “b” (followed by) Event “c” (followed by) Event “d”
So if events occur in the order a->b->c->d, fire this query and select “recharging”. Event “a” itself means that object of type Payload arrives, and this object has property PayloadText set as “Minimize”. So, event “a” will not occur when Payload object arrives with any other PayloadText value.

In summary, the above query translates to:

Select “recharging”
When (first payload arrives with PayloadText=”Minimize”
Followed by payload arrives with PayloadText=”Maximize”
Followed by payload arrives with PayloadText=”Scroll”
Followed by payload arrives with PayloadText=”Coffee”)

Once these queries are initialized, the NEsper initialization code is fired, which is:



This code creates the NEsper default config, followed by adding an event type where the type of data expected in the event is of type Payload. Payload is a simple class containing only one string property. This code then creates a runtime for NEsper and creates a message handler class which should expose one Update method. If the Update method is removed from the definition of MessageHandler, the following error occurs:



So the Update method should be provided by whichever class is being passed in as a statement subscriber to NEsper.

Once the NEsper initialization is complete, the WireEPLStatements method wires the queries created earlier with the message handler created just now:



That’s it! More to be covered in upcoming posts.




Dependency Properties - II Contd.(Memory Footprint)

Tuesday, June 10, 2014 Category : , , 0

To demonstrate the memory footprint of dependency properties vs CLR properties, as described in my last post, I profiled the sample application's memory usage in the following 4 cases:

  1. Dependency property with values overridden a lot
  2. Dependency property left with default value most of the time
  3. CLR property with values overridden a lot
  4. CLR property left with default value most of the time

 Dependency property with values overridden a lot

For this case, I created a dependency property for Quantity in last post's user control. I then used this control inside the datagrid on the main page as a column, so this control repeats for as many items I have in the grid. Next, I bound the Quantity field in XAML of the main page to a value different from the default value. Then, I profiled the application and got the following:


CLR property with values overridden a lot

Next, I converted the dependency property in the last step to a CLR property and profiled again:


If you compare the above figures, you see the following:


All instances and allocations (live instances) All instances and allocations (live bytes - total)
Dependency Property 118,493 6,989,272
CLR Property 118,492 6,981,018

Conclusion: Over-riding Defaults with Dependency Properties

There are some other figures that can be compared as well but from the above, it is obvious that:
Dependency properties perform worse than CLR properties in terms of memory when most of the times, the value of the property will be over-ridden from the default value. Obviously, you would still have to use dependency properties in case you want your value to be dynamic-bound in the XAML of the calling page, since CLR properties do not support that at all. More information on dynamic binding and dependency properties can be found here.

Dependency property left with default value most of the time

Again, in the base sample, I used dependency property for Quantity but this time, I did not change the value of this property in the calling page, but left it at default. I profiled the application and this time, I got the following results:


 CLR property left with default value most of the time


Next, I changed the dependency property to a CLR property, still leaving it at default value in the calling page:



If you compare the figures this time, you see the following:



All instances and allocations (live instances) All instances and allocations (live bytes - total)
Dependency Property 118,325 6,970,616
CLR Property 118,330 6,980,248

 Other figures also seem to be lower for dependency property as compared to CLR property.

Conclusion: Over-riding Defaults with Dependency Properties

Dependency properties reduce the memory footprint of the application but only if the usage of this dependency property is such that each usage does not specify a different value. 

If most of the controls on the page use the default value of the dependency property, the memory usage will be lower than CLR property. However, if most of the controls on the page explicitly set a different value of the dependency property, the memory usage will be higher than CLR property

Powered by Blogger.