Friday, 21 June 2013

A strange say the least ! :D

Got reminded of Sherlock Holmes and Professor Moriarty when I read a requirement from a business website that had an exact, same text with bulleted numbers in The requirement had simply copy/pasted a question's answer and formed a requirement of it. Why did it remind me of ...? Because the respondents to the requirement had an interesting, religious symbolism! :D

A UI notification technique - Exceptions or an event or as both (C#)

Just knowing MVC as defined in the books and arguing over it does not make any sense, does it?

It is when you know how to put the pattern to practise that will satisfy you that you know MVC or any design pattern/architecture and this is where most of the patterns example fail to do (believe me, most of the examples that abound 'are meant' to make sense to only similar, like-minded people (not necessarily to mean technically oriented)...;P here is a simple step-by-step example on how to simplify your UI notifications (not necessarily the heavyweight, 'technical' way).

Simply put, a front-end (since this is in C# - a Windows Form), a business layer (BusinessClass.cs) and a database class. (DataClass.cs)

Let us call it as an Orders utility with one of the specs, "Log as error and display on the user's error log so that the user can copy/paste it to a text editor, if no order is present in the results returned from the database query.

Now, let us implement this spec.

What are the mechanisms that you have? An exception? But this is no exception, in the true sense of the word. So? Return a resultset that if contains no rows satisfies our need.

Before we go further, let me tell you that you should have - knowledge of creating custom exceptions, how to use/create custom event handlers, the 3.5 way. To continue...


Exceptions, in programming, are any deviations, during the normal execution of a program, that need to be either taken care of or  dealt with in some way to enable graceful execution  of the software program.

An exception, in C#, is implemented as a base class called System.Exception and when it occurs is handled by the CLR (Common Language Runtime). This means that any object, let us  say the BusinessClass or DataClass, in our  example scenario, if does not handle the exception through the "try...catch..finally" mechanism, will throw the exception all the way up the  stack. So, if the DataClass was to throw an exception, it will be handled by the  preceding class and since the preceding objects cannot handle exceptions of other objects can only handle it through the base Exception class or not at all, in which case the program will terminate with a runtime exception!

But, if handled as a base System.Exception, our requirement of having to inform the user as to what kind of an exception it is cannot be satisfied because, as mentioned in the previous paragraph above, other objects cannot handle other objects exception. In simple terms, this means if "Object A" throws a "SQLConnection error", Object B can handle it as

SqlConnection conn=new SQLConnection(connectionString);
catch (SQLConnection sqlc){


only if SQLConnection is a type of an Exception or, in programming terms, derives from System.Exception as shown below,

public class SQLConnection : Exception{
public SQLConnection(string exceptionMessage):base(exceptionMessage){

Hark back to the beginning of this post. Is "Log as error and display on the user's error log so ..." an exception ? No. It is a custom exception. So, we handle it by defining a custom exception class called "NoOrdersException" as below.

using System;
// The class
public class NoOrdersException: Exception{
// the data that he exception will return as a string
private string stringMessage="Default message";
// the constructor of the exception class that will pas the message to the base exception class
// and initialize this class' message
public NoOrdersException(string exceptionMessage):base(exceptionMessage){
// the property of the class that will return this exception message that will override the base Message
//  property
public override readonly string Message{ get{return stringMessage;}}

Does this solve our requirement completely? No. because the program still has to notify the user. This can be done only through the UI (the Window on which the user awaits the result).

But, the front-end, the user input screen has nothing to do with the database class that interacts with the database. All it needs to know is how to pass the input from the user and receive the result.

Another problem that you will tackle is to understand what this custom exception is meant for; as you know, exceptions can be thrown and there is an inbuilt mechanism to handle exceptions but "NoOrders" is not really an exception in the execution process of the application rather, it is an exception in the data flow. You can understand it as, when you dip your hand inside a Popcorn bag but find the bag is empty or "NoPopcorns".

As of now, the above translates into a design like

with the BusinessObject class not doing anything. Do we really need the class in the design?

Yes, because if we define business rules in either the view or the data object, it is a deviation of OO principles - a View's purpose is just to enable correct user interaction and the data class to enable data related transactions or actions. Another reason why a separate Business Object class makes sense is because business rules may change as per market or client or customer or other needs and keeping it as separate logical unit makes sense.

All this is common knowledge so what does MVC or this post aim to provide as a value add-on?

As per the previous analysis on why we need the BusinessObject, let us modify the code to use this class to to establish the business rules with the design representing the code as below.

This design represents our requirement to notify the UI in the event of "NoOrders" correctly but is not a correct representation of the code.

It ia contrived because as per programmatic rules, a return value of a called method can only be returned to the calling object so the design representing the code should actually look like below, which it does.

This design represents the code (DataClass and the FormClass) correctly but is there a way to verify that  it is correct and not contrived? Yes, by verifying it through tests, requirements and performance but right now, let us re-look at the problem - throwing a custom exception that is not an exception. Why do we need to do it? Because it is the simplest mechanism to notify the UI from an object that is not known to it, as shown above. And to accomplish this in the OO way, we will use an event.

Event and Event Handlers

        private void OnNoOrdersErrorEvent(object sender,ErrorEvent ev)
        public event myEventHandler<ErrorEvent> ErrorLogEvent;
        delegate void myEventHandler<T>(object sender, ErrorEvent ev);

with the ErrorEvent defined as below:

 public class ErrorEvent : EventArgs
        string eventMessage;
        public ErrorEvent(string evMsg)
            eventMessage = evMsg;
        public string errorMessage
                return eventMessage;

The parameter is the 3.5 version that is simpler than the previous way of handling events though you still need to wire up the event with the event handler as earlier:

        private void Form1_Load(object sender, EventArgs e)
            ErrorLogEvent += new myEventHandler(OnNoOrdersErrorEvent);

Now, let us look at how the data class notifies the "NoOrdersException."

    public class DatabaseActions
        private static SqlConnection sqlConnection;
        private static SqlCommand sqlCommand;
        private static SqlTransaction sqlTransaction;
        private static DataSet dSet;
        private static int businessRule;
        private static DataView dView;
        public static void FetchOrderTransaction(string sqlQuery)
            dSet = new DataSet();
            SqlDataAdapter da = new SqlDataAdapter(sqlQuery, sqlConnection);
            da.SelectCommand.Transaction = sqlTransaction;
            da.Fill(dSet, "OrderDetails");
            EnumerableRowCollection<DataRow> ordersQuery = from row in dSet.Tables["OrderDetails"].AsEnumerable()
                                                            orderby row.Field("OrderNumber")
                                                            select row;
            DataView orderDetailsView = ordersQuery.AsDataView();
            if (orderDetailsView.Count <= 0)
                throw new NoOrdersException("No order exists!");
                dView = orderDetailsView;
        private class NoOrdersException : Exception
            private string msg;

            public override string Message
            return msg;
            internal NoOrdersException(string msgException)
                : base(msgException)
                msg = msgException;



Much of the code above is meant for the example purpose and can be used with your own database as is

The question now is, why can we not raise the noOrdersEvent directly from here? 

The reason is - design. 

The exception or the event of no orders occurs in the data class and the result is subscribed by the UI class. If we raise the event from the data class, the design will look like

Not very elegant because there is another flow for the orders present, which will mean that the data class becomes attached to two objects. What is wrong in doing so? It will mean that testing the data class will be difficult.

So, either we declare the event in the UI class and raise the event from the data class but for which we need a handle to the UI in the data class (totally unnecessary) or just throw the exception from the data class, not handle it anywhere till it reaches up the stack to the UI class and then raise the event!

But why raise an event, when we already have the "catch..." mechanism? Because there could be another data flow exception, "MissingOrders" and because, the exception caught in the UI class will be of the base Exception type, the UI class will have no way of knowing which kind of exception occurred, plus because 
neither being exceptions may need to be handled in their own way.

But more importantly, other factors like thread safety, testability and simplicity in design are the real reasons!

An artist's impression of how it looks from the outside - only representative. :D

More to follow...and Webbased MVC and the challenges that MVC solves

Thursday, 20 June 2013

Microsoft Asp.Net MVC 4, SignalR, the Cloud and Google

As if Shakespeare's sonnets were not mind boggling, the awesome guys n gals of Microsoft, Apple and Google have added dimensions to how you exercise your mind, to keep it decision savvy. It is, quite possibly, equal only to how I used to feel when up against William Shakespeare's sonnets in my second year of graduation. (Even today, I can guarantee that not one of those sonnets have enhanced or improved my outlook towards life (then why did they make me go through all that?)).

Imagine a toad (or is a frog more suited? Either way, feel free as both leap and hop quite willingly.) as it leaps from one grass cover into another lest it croaked, literally speaking!

This is how 'you' feel (and if 'you' do not, let me know and I will change the 'you' to 'I' but, of course, it is in a manner of rhetoric that I say so, so please do not take it too seriously)  as you go through the new technology initiatives from Microsoft and Google (being partners in technologies that make platform compatibility to nearly 70%) and Apple, to some extent (that is, when I try to get even more awed by technology than necessary and venture into OS X and iOS).

I had followed Asp.Net till about 2.0 or maybe, till the MVC days and since I knew about MV, courtesy, XCode/IB, I was satisfied that I was well-equipped; but not even the sonnets gave me the kind of jolt that words like Grease, Breeze, Ember, SignalR (I used to live near Signals Enclave as a child so I embraced this word (due to its familiar sound) as a South Indian, on a trip to North India, does, when meeting another native from his home town.) did and the other words are as monstrous as Cucumber, Jasmine and the rest (Okay, so you thought REST was it, did you? YOU SUCKER. There is LESS now!) sound to newcomers to the Open Source world of Agile software development.

Installing SignalR, an open source, browser implementation to enable client-server synchronization through asynchronization (tell me when it gets too simple) in Asp.Net web applications is not such a cake walk.

Because. while trying to figure out (by searching forums) the various parameters related to an installation, you will come across a post that will cause you to wish for a "rollback" mechanism in your installation (Did I hear the "adhiga prasingee" (a Tamil word. I am so liberated thanks to words like Katanga and OWin that I am convinced that people can figure out what you want to say, no matter if it is Japanese or Tamil!) say, "Oh, didm't you know? Such a mechanism exists?"?) - the post says, "you 'may not' cancel an install of the Asp.Net web tools 2012.2 nor install the Asp.Net updates while Visual studio is open as it "will" (not may) cause Visual Studio to misbehave!".

I will continue with a "Safe and sane install step-by-step" of SignalR in the next post, as in this one I seem to have drifted a little but totally justified (you ill know it when you install and use it) but I do have a thought here (not claiming any self-bragging rights) - I developed a code editor (jvWriter) way back in the 90s (code coloring, intellisense and the stuff) that I used to think was at par with VS, then, but what they have introduced with Web Extensions (see?

You were sitting back, relaxed, that there was nothing else!)

for Javascript and CSS is only an over-hyped term for a plug-in.

Why I mention this is that  you should be careful before going overboard about any new technology announcement - they may just be a glossed up word for something simpler that used to exist but because of the new demands of the Cloud, network security protocols, data management hardware, and Google APIs the econo-market needs may be the real cause for the new technological terms and not, really, - technical needs!

Ps.: If you had to frequently roll back your reading mechanism back and forth over a sentence (to stay with me in those long, complex sentences with all the brackets and sub-sentences), that is how reading the Sonnets used to make me feel!

But so that you get something from this post, here are just two images to get you started with SignalR (if you have downloaded ASP.Net web tools 2012.2 but are unable to see a SignalR template - one thing that may help you faster is that it is an Item Template and.not a VS project template.)

Start the "Package Manager Console" from the Tools- menu (VS Express 2012 for web) as below.

This will open the console as below. Type the highlighted text and the necessary references, .js files will be added to your Solution/Project. 

That is right. You can add the SignalR package only after you have created a project, an empty web app should do.

Tuesday, 18 June 2013

Best way to consume a public web service

is to either call the web method using the query string, save the XML result as file and then use the XML File or, by creating a local reference.

It is best this way to avoid your app from crashing in case the web service provider withdraws/closes its service.

A simple MSMQ example

You can consume this class from a main method or for a unit test.

using System;
using System.Messaging;

   public class QClass
        private string qPath;
        MessageQueue mq;
        public QClass(string queue_Path)
              qPath = queue_Path;
        MessageQueue queue = null;
        private bool LoadQueue()
            bool b=false;
            if (!MessageQueue.Exists(qPath))
                    mq = MessageQueue.Create(qPath, true);
                    b = true;
                catch (Exception ex)
                    b = true;

            return b;
        public bool SendMessageToQueue(string msg)
            int msgCount = 0;
            MessageQueueTransaction mtx = new MessageQueueTransaction(); // Use for transactional q's
            string labelMessage = "Queue Loaded ";
            Message mesg = new Message();
            mesg.Body = "Hello world";
            mesg.Label = "Label 1";

            bool b = false;
            b = LoadQueue();
            if (b == false)
                mq = new MessageQueue(qPath);
                    mq = new MessageQueue(qPath);
                    if (mq.CanWrite)
                       // mtx.Begin();
                            mq.Send(mesg, MessageQueueTransactionType.None);
                         //   mtx.Commit();
                            b = true;
                        catch (Exception ec)
                catch (Exception ex)
                    b = false;
                return b;
        public Message readReceive()
            Message m1=mq.Receive();
            return m1;

Thursday, 13 June 2013

It is not the work of a hacker

Two identical query to Google API returning two results.Maybe 'they' were trying to predict my next search :S :D or maybe, 'they' were trying to get too ambitious and used a static response stream! 

Tuesday, 11 June 2013

Slim help (no pun intended!) !

Before I begin this post, let me say this -

Do not forget to leave a "Thank you" comment if this helped you in using Slim. I know the worth of this post as there is hardly any online help (simple ones that is) on Slim!

Even though I started using Slim 3-4 years back, I still find it can behave unpredictably, unlike other tools so I am posting some tips here. :P

Tip #1 - Use the Format button on the Wiki but wait! It may format your wiki code but it is not a magic wand and you must use it as an informed user. For instance, if you write a wiki line of code like "'{some line here |' the "{" will not be declared as an error!! So, the Format button only helps experienced Slim/FitNesse coders.

Tip #2 - There is no logic to this tool. It is as open for "trial and error" as you could imagine, so go ahead and try all the syntax that you know!

Well, okay, jokes apart, here is the real one!

To start using Slim, you will need the Fitnesse.jar file and Slim Download Fitnesse and Slim. Extract it after downloading and navigate to your Fitnesse folder (through command prompt) and type
"java - jar fitnesse.jar " (or the name of the .jar file as may be). This will launch your fit server on port "80". If  the port is not available, type "java -jar fitnesse.jar -p 9888 (or any other number)".

In your favorite browser, type localhost (this example is based on Windows 7 Home Basic (no IIS default)): and you will be at home with Fitnesse ! :)

Create a new page "HelloWorld" by typing it in the address bar of the browser and an editable text box will open.

Delete the !contents line. In the empty text box, enter the following lines -

!define TEST_SYSTEM {slim}
!define TEST_RUNNER {e:\fitSharp\Runner.exe}

!define COMMAND_PATTERN {%m -r fitSharp.Slim.Service.Runner,e:\fitSharp\fitSharp.dll %p}

!path DllDrive:\yourDLLpath\YourDllLibrary.dll

The first line indicates that you want to use Slim - default is "fit". The second line says use Slim Runner to execute the tests in your page. The third line is the service that is to be used by Slim and the location of the Slim library. The 4th line is the path where your C# domain library resides! That is it! 

The "!" mark is used wherever you want to let Fitnesse know that the following lines should not be used as a wiki code and formatted!

There are various techniques for writing Acceptance tests and it is beyond the scope of this post so I will introduce the tools used in Slim - tables.

There are Decision, Scenario, Table, Script, query, import....tables. Each has its own applicability and to learn about them you can take a look here.

Scenario table

Scenario tables are my favorite in Slim because of my inclination towards BDD (Behavior Driven Development). 

A scenario table, as the name indicates, describes scenarios (use cases/user stories) and by itself does not do anything so if you wish to impress somebody in your team/management, you can simply declare a scenario like this and it will show "Green"!



Below is an example screen(s) of a scenario table with the Slim script following it and the C# code after it.

The script of the last scenario in the script has not been included and you can use that as an exercise !

Similarly, the class name and the namespace names have been left out in the C# screenshot that you can use as an exercise!