Translate

Wednesday 18 December 2013

The change

Not long ago, maybe less than a decade or so ago, when a mere description of Waqar Younis' "toe crushers", "vicious, in-swinging yorkers", was heard or read in newspapers, was sufficient to conjure up a wholesome visual experience that presented visuals of wide eyed batsmen hobbling away and a tear away fast bowler celebrating with joy - as if having been there!

Those kinds of eloquent writers are probably now waxing eloquence, meaninglessly, to live visuals on television for viewers who, as most probably, listen to music with the box on mute !

But did you realize the impact that such a huge change could have in inter-personal communication, bi-lateral relationships in and between people and countries, emergence of literature vis-à-vis the new 'types' of readers, the 'new' emotional, human and artistic values that get into the cultural system of a country, the sense of importance of imagination, its need 'and' the proportion of it

in the way planning of policies (that depend a lot on predictable human behavior) and other sustenance means of the human life cycle value-chain will be affected by all the above?

It is not a question that has an answer - it is a new type of human existence that provides a different vision of the future just like the new kind of life that must have presented itself to the generations that must have looked at the change that the computer and mobile, smart phone brought on them !

The only difference why it is not the same is that those changes were in material and visible terms.

Friday 29 November 2013

Personal preferences % (modulus of - as in software logic) Others' = Public Opinion

Public opinion, rumor and gossip are similar in one respect - they are like the modulus operator ('%'),

if the other side is 'even', the result is zero; if the other side is 'odd', the remainder gets calculated ! :)

Table value parameters - SQL Server

Table value parameters are the best way to pass a list or dictionary or key-value to a SQL Server stored procedure, a feature available from SQL Server 2008 onwards.

It is sometimes funny, this trend of many useful software and language features going unnoticed, when their applicability and usefulness is quite high. It is also likely that the usage or non-usage, of many such features may have influenced some programming trends or caused many simpler techniques to disappear.

One such feature is the usage of custom types, in SQL Server through the Table Valued Parameter (TvP), that makes a programmer's life simple.

A TvP is a custom type that can be defined for any database with the syntax,

Create type [dbo].[typeName] as table(
fieldName (type)(size)
)

Since arrays are not built-in to SQL Server, the customer type TvP helps in passing values to stored procedures as parameters of a SQL query with a SQLCommand or a SQLDataAdapter object.

There are many ways o passing values to a TvP type but the simplest is a DataTable object. Build the custom columns (DataColumn collection) corresponding to your TvP fields and add the values  as DataRows to the DataTable object.

So, the TvP is actually a type of table - a UserDefined TableType and hence, its name ! And so, due to less resources for some reason on the web, regarding its usage, this extremely useful data type or rather, table type is rarely used with its predecessor, the XML type more preferred.

The single most important thing when using a TvP is to remember that it is a table type and therefore, when using it in stored procs or functions, it is recommended for use with an alias failing which weird error messages may crop up totally unrelated to the type's structure or usage!

Many going the bookish way do not have much use for the TvP because it can be used only with "Insert" - this is what is the definition for usage but the context is not mentioned with the restriction leading many to believe that it must be a strange type !

It can be used within the SQL Server context with "Insert" because being a table type, you need to insert values into it first and only then you can use it! But from a program context, you can use it for any purpose - "update", "delete" or whatever.

The example below shows how to create a TvP, declare it in a stored procedure and iterate through it with the help of a cursor.

Example:

For a TvP, named 'myList'

// TvP declaration in SQL Server

use myDb;
create type myList as table(
myListValue nvarchar(max) 
)

// Stored Procedure

create procedure myProc

@myListVar myList READONLY       -- ReadOnly is a required attribute for a TvP

as
declare @listName nvarchar(max)

begin
declare @getListValues cursor
set @getListValues=cursor for

-- below, you are consuming the field defined in the TvP and getting the list value.
select c.myListValue from @myList c

open @getListValues

fetch next from @myListValue into @listName

WHILE@@fetch_status=0

-- update statement

fetch next from @myListValue into @listName
END
close @getListValues
deallocate @getListValues
end

Program code:

using System.Data;
using System.Data.SqlClient;

... more statements - class etc

DataTable dataTableObject=new DataTable("typeName");
dataTableObject.Columns.Add("fieldName");
dataTableObject.Rows.Add("SomeArrayValue");
....

The name of the DataTable, supplied as a parameter to its constructor, is the custom type defined in the database. The column collection corresponds to as many fields as is defined in the type.

SQLCommand/SQLDataAdapter cmd=new SQLCommand/SQLDataAdapter("StoredProcName",sqlConnectionObject);

cmd.CommandType=CommandType.StoredProcedure;

cmd.Parameters.Add("storedProcParameterName",SQLDbType.Structured);

cmd.Parameters["storedProcParameterName"].Value=dataTableObject;

cmd.ExecuteNonQuery(); // being an update query in the stored procedure.

Tuesday 26 November 2013

NVarchar (in SQL Server) - the mysterious 'N'

Sometimes the most preferred data type can cause problems due to the stereotyped acceptance that if it is the most adopted and works, it must be the best.

NVarchar is one such type.

Although this SQL type is quite likely the 'good' one and the 'chosen' one for all text type data requirements, it is not for at least two common requirements related to data-warehousing and transport.

1. Not to be used if the requirement is to have a columnar storage index.
2. Not to be used if the requirement is to export data in a flat file. I made this as a note for some future reference for myself but upon re-read it falls 'flat' !

The 'N' of course is extremely useful as a type prefix if you wish to avoid collating an entire database because just changing the data type of the table column to 'N' type will enable non-English text to be inserted into the column due to the unicode compatibility of the 'N' type.

Thursday 21 November 2013

Game 9 - If it were a child's play

The board position after Black queens with a check and white can play Nf1, Rf1 or Bf1 to save the check.



Anand played Nf1.

The evaluation line was expecting Bf1 and below are some possibilities with a few lines leading to a checkmate in favor of Anand.

If White had played, Bf1


 and black responds with Qxf6 because the impending R - > h4 threatens mate on h7 and black has to rescue its king from it



and if intead of Qxf6, if black plays Nxf6  White's gxf6, Qg7# wins for White.



















But then if it were only a child's play! :)

Monday 18 November 2013

Change and 'generation gap'

Because 'Change', of a social or mass kind. happens over a period of time or say, generations, to understand how effecting 'change' effectively happens, it is important to first dispel stereotyped understanding of words like 'generation gaps'.

As it is understood and propagated, a generation gap is related to lack or lesser numbers of effective communication channels between different generations. Understand it, instead, as "reduce the gap between generations by introducing generations to current age demand and technologies and past shortcomings" and change, instead of happening over decades, will begin to happen in years and even months. 

Friday 15 November 2013

Game 5 - huh?

Protocols are good to enforce and profess but only when a correct disposition towards convention and accepted compliance to what is correct in the given context  is also considered as a given.

The FIDE website on the FWCM 2013 has the link to the Game 5 Replay still pointing to game 4 !!

http://chennai2013.fide.com/results-and-info-page/

If a website is about a World Championship event, it is normal convention to be reflecting up-to-date information to reflect commitment to quality and maintain integrity.


Wednesday 13 November 2013

And Carlsen misses a decisive counter-trap - game 4 !!

Game 4 - Carlsen takes the Berlin route and trades for safety in move 35.

Vishy plays 35 Ne4 nviting Carlsen to gobble up the pawn on g4 and Carlsen obliged...the experts exclaimed as to why the need for speed.


because after 35...Rxg4+ 36. Kf2, everybody wanted black to play Ne5 or Rd8 to counter 37. Nd6+

The idea of 36...Ne5 is to support the rook on g4 and 36...Rd8 is to keep White from playing Nd6+


Here is the position following 36...Rd8.

37. Nc5+ bxc5 38. Rxg4 Ne5 and black threatens to take the rook back with Nxg4+






if 39. Rg3? Bxb5 (takes the piece back and the exchange fork remains!)

                                                       

but Carlsen obliged Anand's favor in game 3 and let go with a simple Rf4+ and rook back to Rf8 !!


Of course, it might be argued that Anand may not have played Nd6+ or Nc5+ but a World Champion does not sacrifice a pawn just like that and go two pawns down and a World no. 1 is clearly not in his elements if he cannot follow a simple unwritten practice in Chess - capture an open rank with rook and the more important, activate a passive piece and bring it in into play!

So that the above is not seen as a criticism of two greats of the game, I must note here that it is an observation of how two Grandmasters approach a likely-long championship, with both seizing on the first opportunity to shun complex, potentially explosive combinations to positional play.

Incidentally, this means that both are relying on positional play, which is human and cannot be analysed as well with the help of computer software...got it? :)

Tuesday 12 November 2013

Vishy misses a clear advantage ? - Game 3 World Chess Championship 2013

It is very rare that a position of this nature comes forth in a World Championship game, especially when both the players are known to be sharp.

The position is after the 29th move of Game 3 of the ongoing World Chess Championships being played in Chennai between Vishwanathan Anand, the reigning world champion and Magnus Carlsen, the World no.1 and the challenger to the crown.

1. Nf3 d5 2. g3 g6 3. c4 dxc4 4. Qa4+ Nc6 5. Bg2 Bg7 6. Nc3 e5 7. Qxc4 Nge7 8. O-O O-O 9. d3 h6 10. Bd2 Nd4 11. Nxd4 exd4 12. Ne4 c6 13. Bb4 Be6 14. Qc1 Bd5 15. a4 b6 16. Bxe7 Qxe7 17. a5 Rab8 18. Re1 Rfc8 19. axb6 axb6 20. Qf4 Rd8 21. h4 Kh7 22. Nd2 Be5 23. Qg4 h5 24. Qh3 Be6 25. Qh1 c5 26. Ne4 Kg7 27. Ng5 b5 28. e3  (the adjacent image has analysis by Fritz, barring the first line, which is quite a bizarre suggestion all the other lines of variations shows ...dxe3 29. Rxe3 Bxb2) 

but Anand played 29...Bd4 !?

So, I thought of analyzing the ...Bxb2 line and the results were + all the way for Black even though a draw, forced by White through a Bishop sacrifice (resulting from a sharp-ish Ra6 line for White, annotated below), does look the most likely result, the way to the draw shows a lot of interesting plus-es for Black that might have led to a pressure situation for White! Maybe what Carlsen meant by "survived a scare"!


Here is the 29....Bxb2 line




At the press conference, Anand mentioned "Re1 and White had enough compensation" but not really as the below position shows after 30. Nxe6+ fxe6 31. Re1

31...e5 32. Rb1 Bd4 33. Re2 Qf7 34. Bc6 b4 35. Qe4  Rd6 36. Qf3 b3   -+


Below is a sharp-ish variation that Carlsen may have played with the above assumption that Carlsen would be only too eager to release his Queen from the 'h' square quickly and bring it into play.

30. Nxe6 fxe6 31. Ra6 e5 32. Be4 Rd6 33. Bc6! (allowing for Qe4 to come into play, freeing the Queen, and at the same time threatening the b5 pawn. 

Wednesday 16 October 2013

The 'Good' Manager

Human Behavior

Alfred Hitchcock is probably the finest example of a highly tuned person, with a quirky sense of humor to deliver his perception, to human behavior. 

The expression of 'good' and 'bad' is an overwhelming unit of measure used in a human's routine life. Every artifact in the strata of modern life, financial, business, political, social, professional or personal, is designed to reflect this common understanding.

'Behavior' is also probably the most misconstrued perception that defies gravity and takes off as suits the direction in which social  winds blow. Personal inclinations, prejudice, comfort and safety will always define how standards or rules evolve to define acceptable human behavior in the future due to the intricate network of commitments at the various levels of life. So, it is safe to surmise that no drastic change from the past understanding of 'good' or 'bad' is likely except probably in the way compromises or levels of it, will shape up due to  implementations of policies. What this translates to, in simple words, is the perspective or context in which attitude, actions may get interpreted as behavior.

Because of the paradigm of understanding 'behavior' in the context of 'good' or 'bad', vilification of the 'manager class', as happens in say, an Agile community, or the glorification, as happens among the uneducated or the lesser educated class, will define how management schools may 'create' the 'employee' class and the 'manager' class of the future.

In one of my visits to a well-endowed and established private universities, in India, it was appalling to see a toilet in a dilapidated and ill-maintained state that one would not even see at the infamous Government institutions. The mind invariably makes a judgement at the kind of administration and management existing in that university or (in a logical perspective) a 'unique' and unknown technique of giving out 'wrong' impressions to satisfy 'jealousy' or 'extortionist' elements of the society that come to inspect or to check.

So, 'judgement' is a defining factor in understanding how 'organized' work, thought process or output will evolve in an 'organization'.

Judgement

This post was inspired by the following points that I came across on an online tutorial post that gave me a nourishing subject to test my experience, maturity and knowledge!

o  Explain how a manager’s behavior can affect the productivity of his or her workers.
o   Describe the types of management action that align with employment laws and those that do not.
o   Describe best practices for working within a diverse work environment.

To be continued...

Saturday 13 July 2013

DBFit + Slim + LocalDB

Cool!

Only word to  describe the way you can work with databases nowadays.

As I tried to figure out a way to work with a complex set of data using stored procedures (add to to this a SQL Server error that disallowed attaching a database file to the server), I realized the incredible number of options available to work with the database file - 1. Azure storage  2. Visual Studio  Data Connection  3. LocalDB  4. Read data in XML and import from XML file into DB and the list could go on, if one applies one's mind to it! Although I have not tried this but it may even be possible to use Excel to work with the DB (with the DataConnection or is it UDL or F?)...

So, first I tried to connect with VS to the LocalDB and succeeded in attaching the .mdf file.

Next, I wanted to test the stored procedures in the DB and since writing code to execute the procs looked tedious, decided to use the Management Studio 2012 to connect to the LocalDB and succeeded without any error!

So, executing the stored procedures is a simple step but I was not satisfied and so decided to use DBFit and since I wanted to write some functional acceptance tests, my first thought went to Slim!

A fantastic tool, Slim, just got better with support (this word 'support' is contentious as the DBFit team (or was it the Slim team)?) :D insists that there is no Slim support for DBFit) for  DBFit!

All you need to do is download DBFit and extract it into the Fitnesse folder and run the StartFitnesse.bat file (in Windows).

One of the more likely problem areas will be the connection string to the database from DBFit. If  you are a VS user for long, you will manage but if  you are not here is one connection string that you would like to use

Below is the LocalDB connection string, for integrated security, that you may not find anywhere else -

!|connect|Data Source=(LocalDB)\v11.0;AttachDbFilename='path to database file';Integrated Security=True;Connect Timeout=30|

The simpler one is

!|Connect|JV-PC|YourUserName|YourPassword|YourDatabaseName|

You can use almost any command you may otherwise use in the database environment and so the script to test 'Transaction' is

!|DatabaseEnvironment|
|commit|

!|DatabaseEnvironment|
|rollback|

Use the Rollback script in the TearDown fixture as is so that it could use the default, or the current connection/transaction.

Super cool!

Connect to http://localhost:8085/ after starting the Fit server with StartFitnesse.bat

Create a page by typing it in the address bar and type or copy/paste the below code, Save, Change the
properties of the page to Test, save the properties and theTest menu item will appear.

A simple query syntax to start with DBFit and Slim

!define COMMAND_PATTERN {%m -r fitnesse.fitserver.FitServer,"FitSharp\fit.dll" %p}
!define TEST_RUNNER {FitSharp\Runner.exe}
!define PATH_SEPARATOR {;}
!path FitSharp\dbfit.sqlserver.dll

!|dbfit.SqlServerTest|

|Query|SELECT n FROM ( SELECT 1 as n union all select 2 union all select 1 ) x |
|n|
|2|
|1|
|3|

|Ordered Query|SELECT n FROM ( SELECT 1 as n union select 2 union select 3 ) x|
|n|
|1|
|2|
|3|


You can also execute stored procedures, functions and any query that you may otherwise be executing with SSMS.


Friday 21 June 2013

A strange requirement...to 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 StackOverflow.com. 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

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);
try{
conn.Open();
}
catch (SQLConnection sqlc){

}
finally{
conn.Close();
}

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){
stringMessage=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)
        {
            txtErrorLog.Text=ev.errorMessage;
        }
        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
        {
            get
            {
                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)
            {
                sqlConnection.Close();
                throw new NoOrdersException("No order exists!");
            }
            else
            {
                dView = orderDetailsView;
            }
        }
        private class NoOrdersException : Exception
        {
            private string msg;

            public override string Message
            {
           get 
           { 
            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))
            {
                try
                {
                    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);
                try
                {                  
                    mq = new MessageQueue(qPath);
                    if (mq.CanWrite)
                    {
                       // mtx.Begin();
                        try
                        {
                            mq.Send(mesg, MessageQueueTransactionType.None);
                         //   mtx.Commit();
                            b = true;
                        }
                        catch (Exception ec)
                        {
                            //mtx.Abort();
                        }
                    }
                }
                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

Explanation
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"!

|Scenario||myScenario|

|myScenario|

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!











Thursday 25 April 2013

My Personal Ledger - Work on the move

Work on the move, upload to cloud, sync up with your workstation or client. Sounds good?


Wednesday 24 April 2013

GREYcells Ludo

Upcoming app - Ludo for Android

Monday 15 April 2013

Tuesday 9 April 2013

EasySudoku

Look for it on Google Store in a week's time!
 


Monday 25 March 2013

Easy Sudoku - Alpha version 1

Easy Sudoku - Alpha Version 1
 
 
(Representation image).
Currently testing that all numbers can be moved around...
 

Thursday 21 March 2013

Know your India - Android app


The graphics (the rice bags and the table on the right) need to be polished for production. :)

Tuesday 26 February 2013

"The Train" design pattern

If design patterns have emerged or are supposed to emerge from pattern-mining, many of the design patterns, if not all, are like over-worked donkeys and consuming resources like an Elephant in a middle-class family.

Design patterns, in the current, technologically well-established and stable world, needs to be able to enhance its own effectiveness by regrouping itself to make use of available resources.

Design patterns have been regarded as solutions to similar problems with a total disregard to how platform changes, resource managemrnt improvements, hardware improvements, hardware-software collaboration may affect the outcome of a designed solution.

The modern, post-web 2 world of design patterns has to be inherently dynamic enough to accomodate even language enhancements to utilize, optimally, hardware advancements like parallel processing or greater memory addressing powers.

"The Train" pattern that I am talking about here will not only be the basis for all modern artifacts like a computer game, it may also serve as the right solution to serve dynamically changing artifacts in processes.

The model of this pattern is already posted on this blog as a procces model.

I will post this pattern in an Android app, first, and later as the controller of a game.

Monday 18 February 2013

Working software

If a software works and gives the desired result, that is the first successful step in software development.

Refactoring, UI design, 'code smell', object/class design, whether to use a lst or a collection or a dictionary of objects and all the other fancy stuff that are dished out, by the dozen, in training and coaching sessions, do not matter if the software is not working.

Neither does 'working software' or 'software', in this context, means the complete software with all the features. It just means that you have created the 'sufficient' code that is 'stable' and provides a solid base to achieve the requirements set.