Introduction to Reactive Extensions

Recently I got an opportunity to work on a FX  trading (client facing) application. I specifically mention client facing because in this money world trading application has to be very responsive and fast. When I started working on this application, along with the other challenges the major one was to learn and understand the Reactive extensions (Rx). Fx trading application is a Reactive application and it has to be looking at its business domain and the software solution it provides.

But what do you mean by Reactive Application?
If we try to briefly understand the Reactive Applications, they are

  • Event driven – React to events
  • Scalable – React to loads
  • Resilient – React to failure
  • Responsive – React to users

All the above features imply how the application and environment works together. The reactive application passively waits for the environment to send the data and then reacts to it. This behavior can be achieved by Microsoft reactive extensions.

This article is intended to give an Introduction to Reactive Extensions(Rx).
To study the Rx to its depth you can find good material at below links

Definition

The Reactive Extensions (Rx) is a library for composing asynchronous and event-based programs using observable sequence and LINQ-style query operators.

Essentially Rx is built upon the foundations of the Observer pattern and the interfaces IObserver<T> and IObservable<T> forms the fundamental building blocks for it.

IObservable<T>

//Defines a provider for push-based notification.
public interface IObservable<out T>
{
//Notifies the provider the that an observer is to receive notifications.
IDisposable Subscribe(IObservable<T> observer);
}

It is a simple interface with just a Subscribe method. We can think anything that implements IObservable<T> as a streaming sequence of T objects (sequence of data in motion). Example IObservable<Price> refers srteam of Prices.

IObserver<T>

//Provides a mechanism for receiving push-based notifications.
public interface IObserver<in T>
{
//Provides the observer with new data.
void OnNext(T value);

//Notifies the observer that provider has experienced an error condition.
void OnError(Exception error);

//Notifies the observer that provider has finished sending push-based notification.
void OnCompleted();
}

An implementation of the IObserver<T> may have zero or more calls to OnNext(T) followed optionally by a call to either OnError (Exception) or OnCompleted(). This protocol ensures that if a sequence terminates, it is always terminated by OnError(Exception) or by OnCompleted(). However this protocol does not demand that OnNext(T), OnError(Exception) or OnCompleted() ever be called.This enables to concept of empty and infinite sequences.

ISubject<T>

If we create our own implementation of IObservable<T> we may find that while we want to publicly expose the IObervable characteristics we still need to be able to publish items to the subscribers, throw errors and notify when the sequence is complete. That sounds more like the methods in IObserver<T>. So ISubject<TSource, TResult> implements both the IObservable<T> and IObserver<T> interfaces. The implementation of ISubject<T> reduces the learning curve for the developers new to Rx.


//Represents an object that is both an obsrevable sequence as well as an observer
public interface ISubject<in TSource, out TResult> : IOBserver<TSource>, IObservable<TResult>
{

}

Subscribing

The Subscribe extension method of observable allows us to

  1. Pass an action to be performed when OnNext is invoked for each incoming data.
  2. Throws an Exception in case of OnError notification.
  3. Pass an action OnCompeted when the source completes

There are different overloads of the Subscribe extension method but below is for the complete implementation.

IDisposable Subscribe<TSource>(this IObservable<TSource> source,
Action<TSource> onNext,
Action<Exception> onError,
Action onCompleted);

Unsubscribing

The return type of subscription is of type IDisposable. This disposable can be consider as the subscription itself, or perhaps a token representing the subscription. Disposing it will dispose the subscription and effectively unsubscribe.

The instance of IDisposable that is returned from subscription does not have a finalizer and will not be disposed when it goes out of scope. If you call a Subscribe method and ignore the return value you will lose your only handle to unsubscribe. The subscription will still exist and you will lose the access to this resource which could result in leaking memory  and running unwanted processes.

Rx Example

var tickingTimespan = TimeSpan.FromSeconds(5);

//source is the observable stream which gets the price for every 5 secs.
IObserverable<Price> source = Observable.Interval().Select(_=> GetPrice());

//Observable sourceis subscribed to react to incoming price.
//For every new price DisplayPrice method is called.
//On error if any can be handled with action 'ActionOnError'.
//On completion of the source stream ActionOnCompleted will be called.
IDisposable priceSubscription = source.Subscribe(DisplayPrice() ,ActionOnError(), ActionOnCompleted());

//Dispose is used to unsubscribe the priceSubscription.
priceSubscription.Dispose();

Flavors of Reactive Extensions

We also have Rx in different languages as below

  • Rx.NET: The Reactive Extensions (Rx) is a library for composing asynchronous and event-based programs using observable sequences and LINQ-style query operators.
  • RxJS: The Reactive Extensions for JavaScript (RxJS) is a library for composing asynchronous and event-based programs using observable sequences and LINQ-style query operators in JavaScript which can target both the browser and Node.js.
  • Rx++: The Reactive Extensions for Native (RxC) is a library for composing asynchronous and event-based programs using observable sequences and LINQ-style query operators in both C and C++.
  • RxJava: A library for composing asynchronous and event-based programs using observable sequences for the Java VM.

The Garbage Truck

How often do you let other people’s nonsense change your mood?
Do you let a bad driver, rude waiter, curt boss, or an insensitive employee ruin your day? However,
The mark of a successful person is how quickly one can get back their focus on what’s important.

David J. Pollay explains his story in this way….

Sixteen years ago I learned this lesson. I learned it in the back of a New York City taxi cab. Here’s what happened.

I hopped in a taxi, and we took off for Grand Central Station. We were driving in the right lane when, all of a sudden, a black car jumped out of a parking space right in front of us. My taxi driver slammed on his breaks, skidded, and missed the other car’s back end by just inches!
The driver of the other car, the guy who almost caused a big accident, whipped his head around and he started yelling bad words at us. My taxi driver just smiled and waved at the guy. And I mean… he was friendly. So, I said, “Why did you just do that? This guy almost ruined your car and sent us to the hospital!”
And this is when my taxi driver told me what I now call, “The Law of the Garbage Truck.”
“Many people are like garbage trucks. They run around full of garbage, full of frustration, full of anger, and full of disappointment. As their garbage piles up, they need a place to dump it. And if you let them, they’ll dump it on you. When someone wants to dump on you, don’t take it personally. You just smile, wave, wish them well, and move on. You’ll be happy you did.”
I started thinking, how often do I let Garbage Trucks run right over me? And how often do I take their garbage and spread it to other people: at work, at home, on the streets? That is when I said to myself, “I’m not going to do it anymore.”

Life’s too short to wake up in the morning with regrets. Love the people who treat you right. Forget about the ones who don’t. Believe that everything happens for a reason.

Never let the garbage truck runs over you….

Get File CheckSum

The following C# code returns the checksum of the file given the path in strFilePath string.

using System.Security.Cryptography;
public string GetCheckSum(string strFilePath)
{
byte[] checksum = new byte[2000];
MD5 oMD5 = MD5.Create();
string strchecksum = “”;

try
{
using (FileStream stream = File.OpenRead(strFilePath))
{
checksum = oMD5.ComputeHash(stream);
}
strchecksum = BitConverter.ToString(checksum).Replace(“-“, String.Empty);
}
catch (Exception ex)
{
//Handle Exception
}

return strchecksum;
}

Get Rid of Your Limits: Achieve Your Goals

Have you heard about the frog that was born at the bottom of a well? He thought life couldn’t get any better till one day he looked up and saw daylight. Climbing up to investigate he was amazed to find a much larger pond than the one he lived in. And going further afield he discovered a lake that was bigger again. When eventually he came to the ocean and all he could see was water, it dawned on him just how limited his thinking had been. He thought everything he needed was down in the well, but that was a drop in the bucket compared to the things that were out there for him to enjoy.

Maybe you’re living today in your own little “well,” reluctant to leave your comfort zone, settling for a limited and safe existence while God has rivers “deep enough to swim in.” Wouldn’t you like to step out in faith, experience new depths in Him and go where you’ve never been before? Remember, the enemy will do everything he can to keep you focused on your background, your lack of formal education, your appearance and your limited resources. But Bruce Wilkinson says, “It doesn’t matter whether you’re short of money, people, energy, or time. What God invites you to do will always be greater than the resources you start with?” You don’t have to let fear limit your vision when God is your source, because His supply is unlimited! One idea from Him, just one, can change your life and the lives of others. He’s got great things in store for you today.


“The only limits you have are the limits that you believe.”
So Wider your wings get rid of your boundaries and limitation and get ready to jump with your full strength to explore yourself.

Harsha Bhogle’s speech on excellence

Recently I came across a video of harsha bhogle’s speech, delivered in IIM-A, on excellence. It was the most wonderful speech I have ever heard. It was very motivating and inspiring.
It is really difficult for me to stop myself sharing his wonderful thoughts.
Harsha Bhogle is a man with multiple personalities. When he is not with Cricket big shots in the commentary box, he contributes as columnist to multiple news papers.

Harsha started with talked about some points on the institute (IIMA), how was his life in the institute when he was a student of the institute. In his speech he always kept on referring to his father (how he was petrified of him), his son (how his is not petrified of him), his wife, his lost hair and age (it was just like a warm up to make the atmosphere lighter).

Then he started to speak on Excellence. He used many real time experience to supports he’s point (mainly related to cricket).

Harsha says

– Excellence is not a skill; it’s an attitude, desire, passion.
– Excellence is about chasing the professional performance goal and letting the results take care of themselves. (Karmanye Vadhikaraste Ma Phaleshu Kadachana)
– Excellence never seeks excuses.
– Excellence is the series of 100%
– In life if you seek excellence, always seek people, who are better than you, Always surround yourself with people who are better than you.
– Excellence is not about talent alone. In fact major part of excellence has nothing to do with talent. It is what you do with the talent matters.
– Excellence is also about learning from mistakes. Mistakes are your best friends. Making mistakes is not a sin. Repeating same mistake is a big sin.
– Excellence is as much as knowing what not to do as much as knowing what to do.
– Excellence is all about having the confidence to share knowledge
– Excellence is all about accepting criticism.

His views on “The End”

The end is crucial. Because end is always the driver of the ambition. We usually set ourselves the end or the result goals. The End gives us the vision. “The End” at all cost attitude that pervades is the source for all anxiety. It also creates the temptation to do whatever it takes to win.

His views on “The Path”

Excellence is about chasing the professional performance goal and letting the results / end take care of themselves. Make the process of achievement supreme and make the result irrelevant. Make perfect the process of performance and don’t allow the pressure of the results to choke your performance. And that is the wonderful journey path to excellence.

“Excellence is a series of 100%”

If you give every moment 100% and then wait for the next moment and say “You know what! This is the moment I wanted to give 100% too” and then the next moment turns up and then you say ” Actually this was the moment I really wanted to give my 100% best” . And then you will find the little things in life that makes the difference between the good and great just happen.
You don’t know who is watching you, where which opportunity is coming along. So always give your 100% best effort.

Can you fill 2 liters in a 1 liter Pepsi bottle?
So you can never give anything more than 100%.
But you can give 100% for every moment

There is no shame in saying “Well done … you are better than me” When you know that you have given your 100% effort ethically.

“Excellence never seeks excuses”

The moment someone says “I would have been good But”.. This means you are not great already! it means you are trying to assign the blame of your poor performance on someone else.
The Aussies will never say that we have lost. They’ll just say that we’ll come back and do better next time.
The moment you allow yourself to go wrong, you fall into a possibility map, then you DO go wrong!

“Stop hating Criticism”

Don’t live in the rarified bubble without taking criticism.

“Arrogance”

Arrogance is the biggest stumbling block to success.
In the path of excellence, if you have ego and anger on your side, you don’t need an opponent. You have done 90% of the job of ruining yourself.

“Talent and Attitude”

Excellence is not about talent alone. In fact major part of excellence has nothing to do with talent. It is what you do with the talent matters. Talent needs to be justified by actions.
Attitude and Passion count far more than talent. Ability talent opens the first door but it is not going to open the last door for you.
Always live in present. Live by actions and not words.

“Luck”
Luck is all about recognizing the opportunity before it comes.
Luck is the fantastic fusion of talent and an opportunity spotted.

At the end this man tossed with a great saying, which realy boosts my confidence and motivated me like anything.
“khud ko kar buland etna ka har takdeer khuda bande se puche bol bande teri raza kya hai”.

Well these were some of his thoughts which I was able to summarize.

You can find Harsha Bhogle’s speech on excellence here

Comparing files using MD5

Following C# function takes the two files path as arguments and return true if these two file are
same or false in other case.

public bool CampareFiles(string strFilePath1, string strFilePath2)
{
bool bReturn = false;
System.Security.Cryptography.MD5 oMD5 = MD5.Create();
byte[] checksum = null;
string strchecksum1 = ” “;
string strchecksum2 = ” “;

try
{
//Getting Checksum for file 1 in string format
using (FileStream stream = File.OpenRead(strFilePath1))
{
checksum = oMD5.ComputeHash(stream);
//Converting in string format
strchecksum1 = BitConverter.ToString(checksum).Replace(“-“, String.Empty);
}

using (FileStream stream = File.OpenRead(strFilePath2))
{
checksum = oMD5.ComputeHash(stream);
strchecksum2 = BitConverter.ToString(checksum).Replace(“-“, String.Empty);
}

//Comparing Checksum
if (strchecksum1 == strchecksum2)
{
bReturn = false;
}
return bReturn;
}
catch (Exception ex)
{
//Catch Error here if any
}
return bReturn;
}

Using zlib.net

In one of our project,
we required to compress a file using zlib.net and store it in database in byte array format,
and on retrieving it, uncompressed byte array and create a file on disc.

Hope this post helps others …. !

download Zlib.net click here

Add reference of above dll.

using zlib;

public void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[2000];
int len;
while ((len = input.Read(buffer, 0, 2000)) &gt; 0)
{
output.Write(buffer, 0, len);
}
output.Flush();
}

//compress function gets the file path to be compresss and fills in byte array arrCompressed
public void compress( ref byte[] arrCompressed, string strFileSrcPath)
{
MemoryStream oOutStream = new MemoryStream();
ZOutputStream ostream = new ZOutputStream(oOutStream, zlib.zlibConst.Z_DEFAULT_COMPRESSION);
FileStream inStream = new FileStream(strFileSrcPath, FileMode.Open);
try
{
CopyStream(inStream, ostream);
ostream.finish();
arrCompressed = oOutStream.ToArray();
}
finally
{
ostream.Close();
oOutStream.Close();
inStream.Close();
}
}

//uncompress function gets back file from compressed btye Array
public void uncompress( byte[] arrCompressed, string strFileDesName)
{
MemoryStream oInStream = new MemoryStream(arrCompressed);
ZInputStream oZInstream = new ZInputStream(oInStream);
MemoryStream oOutStream = new MemoryStream();

byte[] buffer = new byte[2000];
int len;
while ((len = oZInstream.read(buffer, 0, 2000)) > 0)
{
oOutStream.Write(buffer, 0, len);
}
oOutStream.Flush();
byte[] arrUncompressed = oOutStream.ToArray();
oZInstream.Close();
oOutStream.Close();
writeByteArrayToFile(arrUncompressed, strFileDesName);
}

//Writes Byte Array to Disc
public void writeByteArrayToFile(byte[] buff, string fileName)
{
try
{
FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(buff);
bw.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}

Methods in Global.asax

Application & Session Events in the Global.asax File

Methods corresponding to events that fire on each request

Application_BeginRequest() – fired when a request for the web application comes in.

Application_AuthenticateRequest() –fired just before the user credentials are authenticated. You can specify your own authentication logic over here.

Application_AuthorizeRequest() – fired on successful authentication of user’s credentials. You can use this method to give authorization rights to user.

Application_ResolveRequestCache() – fired on successful completion of an authorization request.

Application_AcquireRequestState() – fired just before the session state is retrieved for the current request.

Application_PreRequestHandlerExecute() – fired before the page framework begins before executing an event handler to handle the request.

Application_PostRequestHandlerExecute() – fired after HTTP handler has executed the request.

Application_PreSendRequestHeaders()-fired just before ASP.Net sends HTTP Headers to the client. This can be useful if you want to modify a header.

Application_PreSendRequestContent() – just before ASP.Net sends content to the client.

Application_ReleaseRequestState() – fired before current state data kept in the session collection is serialized.

Application_UpdateRequestCache() – fired before information is added to output cache of the page.

Application_EndRequest() – fired at the end of each request

Methods corresponding to events that do not fire on each request

Application_Start() – fired when the first resource is requested from the web server and the web application starts.

Application_Init() – fired after_Start and is used for initializing code.

Session_Start() – fired when session starts on each new user requesting a page.

Application_Error() – fired when an error occurs.

Session_End() – fired when the session of a user ends.

Application_End() – fired when the web application ends.

Application_Disposed() – fired when the web application is destroyed.

Tables vs Divs

Hi All,

Over the last several years, developers have moved from table to div based website structures, WHY?

Well, I like to mention good / bad points of both table and div.

Starting with table

Table

For beginner tables are easy to learn and implement, we see tabular data every day, so the concept is well known.

The existence table attributes makes it easy to implement as developer doesn’t have to use a separate style sheet.

Tables don’t break when the content is too wide. Columns are not squeezed under other columns as they are in a div-based structure.

But at the same time, using tables increase in the number of line of code and nested tables add the complexity to it. The colspan and rowspan attributes make the code even more complex, and any developer maintaining the page in future has to go through alot of code to understand its structure.

More lines of code mean larger file sizes, which mean longer page loading time.

Table structure provides less flexibility in updating the existing code due to its rigid row-column structure.

Div

Div is not wrapped in a parent element the way td tags are in tables, so they do not have the limitation of it parent tag.

Using Div and CSS is immensely cleaner and more easily editable. All you need to do is make changes to your CSS code to change the all website pages across the board

Div–based website renders on your browser much faster as they are lighter in weight.

Div based website is completely flexible and it Increases accessibility and usability of a site. A good example this is site called Zen Garden – The beauty of CSS Design, all the templates are design without changing the HTML, simply by generating the CSS style sheet.

To develop div-based website developer is required to have good understanding of technology and experience writing CSS. it takes a more time to get the effect (compare to table-based website) and requires a lot of work, time and patience in order to make your website compatible with older browsers.

Considering all above point I have made my mind, that I’ll use table only for displaying tabular data and not structuring the website , for structuring I’ll go with div-based structure.

You make your own choice J

Regards,

Deepak waje