Feed your aggregator (RSS 2.0)   Send mail to the author(s)

Recent Entries
<2017 February>


The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

Copyright 2017 Manish Kumar Singh
 Monday, 11 August 2014
Scrum – Do you have YAY Team?

Scrum is an easy process to understand but not as easy to do well. It has many facets which if overlooked, results in failure of scrum team and erosion of the agile process. Scrum, done correctly, leads to creating a “YaY” team that is small and focused to velocity and an environment that is cooperative with the fire and willingness to succeed. But it requires a good understanding of how those facets affect the scrum team and sprint. Rather than discussing the scrum process, I would like to focus on the parameters that makes a YAY Scrum team.

The Team Dynamics

Team is formed of various shapes and size. Skills, work style and experiences varies extensively combined with behavioral variations as well. Some developers like collaborating while some like to work alone. Some like to dive in and some like to investigate and prepare before diving in.
As simple as it sounds, it is still a complex variable of sprint and iterations. The first and foremost important step towards a successful scrum team is to understand the team mix itself. The team size, expertise, specialization and ownership is very important before planning any sprint.

What really matters …. Is how the team is organized around the feature or product? Do they have everything in place to be able to deliver a working tested increment of the software? Do they fully understand the user stories? Can they understand the business value of it? Can they estimate it? Do they fully understand the backlog? Do they have necessary resources to commit?

The team is basically an accountability structure from top to bottom. If the structure does not have everything required, then they cannot be held accountable. When a team doesn’t have everything necessary to be successful, it erodes the sense of urgency around getting things done. Velocity destabilizes and no one cares. No one is accountable for making progress on the product and the team becomes a victim.

The bottom line is that if you cannot create the right mix of scrum team, you are en route to dead-end filled with some nasty surprises. Better find out some other innovative way of developing software than following agile and scrum. It’s that important.

The Project Increment

Like the team, the project also comes in various shapes and sizes. It sounds simple, but when observed carefully and in-depth, a project requires many things to be done before it is demoed to the end user. Planning, Research, Designing, Coding, Reviewing, Testing, Staging, Deploying, Documenting and many other stuffs. All parts of the deliverables should be broken down in ready stories.

The team decides what increment they can produce in the sprint and final deliverables of a sprint should not have any technical debt, pending feedback, pending testing, pending UAT or pending documentation. Anything deferred adds indeterminate amount of work at the backside of the project. What matters at the end is that the team have a measurable chunk of the sprint that can be neatly measured as ratios and timelines.


The essence of successful sprint and deliverables starts from backlog. A poorly formed backlog is almost every time the root cause of almost every problem in a failing sprints. A poorly articulated backlog is an outcome of poor sprint planning meetings. If the backlog isn’t clear, the team comes to sprint planning meeting and spends all the time on “what” needs to be done and not enough time on “how” it can be done. It is visible when the team is trying poker, planning and prioritizing on “what” rather than “how”.
Having backlog, that is well captured, well defined, broken into small chunks of tasks and easy for a team to understand and estimate, increases the success chance of the sprint by many folds. The team feels greater control over the tasks. It also help the product owners to determine what value addition can be committed for the next sprint release.


Because the team and the project both varies a lot in shape and size, a concept of ownership of user stories plays a very innovative and critical role. The owners are the subject matter experts and seniors who bring in more experience and quality break down of the story to backlogs. The owners of user stories bring in more holistic view, accuracy, competency and urgency to the sprint. The estimations are also radical and knowledge based. Asking a database administrator to own a QA user story or test plan and try breaking it into tasks is like bringing in grandmother to estimate a rocket engine.
Besides, the owners also brings in a sense of commitment and achievement that is greatly infused with a sense of ownership. The smaller the team wearing many hats, the better the ownership works. However, the owners should be capable and expert of those fields.

User Stories

User stories are the crux of backlog and increments in a sprint. These are the building blocks of the successful sprint. Something, I came across is very interesting concept: “Bill Wake’s INVEST criteria”, which relates user stories to independent investment decisions. Where each letter in the word INVEST is defined as:

I – Independent – The user stories must be independent of each other and self-contained.
N – Negotiable – User stories, up until they are part of an iteration, can always be changed and rewritten.
V – Valuable – A user story must deliver some value to end user.
E – Estimate-able – One must be able to estimate the size of user story
S – Small – A big user story is simply impossible to plan or visualize.
T – Testable – A good user story must have a clear test plan with simple use cases.

A typical format of a user story is “As a (role) I want (do something) so that (business value)”

As simple as it looks it can still be invaluable, excessive or odyssey, when misunderstood and misinterpreted. This always leads the team to sidetrack and get nothing accomplished. Here are some examples of user stories.

Good: As an admin I want to deactivate another user’s account, so that they can no longer log in.

This user story clearly describes role, what needs to be done and business value. It is self-contained, easy to understand, estimate and test. In short it follows all the INVEST aspects.

Invaluable: Send notifications when a contact is created.

The drawback is that it does not state who or what is sending notification. It does not state in what form the notification is sent e.g. email, twitter, SMS or something else. The description does not include any business value information. It is hard to estimate and a tester in the team won’t be able to describe what needs to be tested here. Asking the team to play Poker on it and estimate is like asking a five years old to describe the molecular structure of a rocket fuel.

Excessive: As a salesman, I want to save my customers list, so that I can create a copy, email and print later on.

The drawback here is that the user story is not clear whether saving the list is what’s required or print, copy and email features is what’s needed. There is excessive information in this user story and that leads to misunderstanding and sidetracking. This requires rework in breaking it down or reframing to a more well-defined user stories.

Odyssey: As John the customer, I want to register for an event, so that I can secure my place.

There is nothing wrong in having an epic or odyssey user stories as long as one understands that it must be broken down to ready stories that are self-contained and based on INVEST criteria.

Each user stories in the backlog and sprint increment must meet this INVEST criteria for the team to be able to commit to the working tested increment of the software. The success of a sprint depends on how well these user stories meet the INVEST criteria. Poker, Burndown charts, Retrospection, Sprint planning and all other exercises around sprint is futile otherwise.

Process Overlaps

Many companies who call themselves Agile are not really agile. They still haven’t come off the waterfall model, which ensures more control and tight iterations over sprints. There is a big difference between Agile and Waterfall. Mixing waterfall and agile is too confusing and too uncomfortable. Trying to control over Cooperation becomes a major challenge. Architecture and Design documents getting ready before a single task happens to build the product is simply not agile. It makes the process too complicated and rigid. This doesn't work on scrum. If you are using scrum, your project needs to adhere to the agile mindset. Ownership, communication, co-operation, repeated discussions and elaboration is the key to success. This helps in creating the “YAY” team effect.

Some even try to introduce Kanban outside the scrum process. This creates a distraction and cuts off the modules and member from the rest of the team. A bad practice that develops a feeling of job and duty than achievement and urgencies.

Culture & Shared Understanding

Just following scrum and its top 10 tips does not mean that the scrum will succeed. There has to be a shared understanding. It has to be organization wide. The sprint commitment and risks factors should be well understood by all team members. The culture of the company also plays an important role in how team works. In many cases it’s mostly the culture of control and fear that leads to a non YAY team effect. A non YAY team is like a pieces of robots taking orders.

There is a big gap in knowing scrum and practicing it correct. Without a correct agile mindset it always meets a tussle between waterfall and agile ways. Many keep struggling and sometimes give up scrum process or land up into mix of processes which is too uncomfortable, and leads to no difference than the same old traditional ways. It’s an old saying that people do smart things when they genuinely “want” to do it. A good culture is to fill that gap and inspire people to do things without being gripped by any fear.

Sprint Planning Dynamics

Another effect that works against a good scrum team is influencing planning phase to squeeze time and pressurizing the members to commit to the time squeeze. It should be owner of the user story (not to confuse with product owner) and team to estimate, work and retrospect to improve on next sprint. It must be the part of retrospection on how much each member deviated and how can it be improved. Burn down charts and estimation should be a continuous process. It must be done by the team for the team within the sprint iteration.

Influencing the team during iteration, changing priorities in any way is like taking the commitment part away from team to one’s own shoulder. The basic principle of the Agile and Scrum is to let team plan, commit, deliver and retrospect. Any kind of influence that lets team change the commitments at the beginning or in the middle of the iteration, would result in team always looking for directions and never valuing those commitments.


Even in real life one needs to get a feeling of value addition made to the task or team he or she has contributed to. If not so, one quickly gets bored and tries to escape from it as much possible. It is important for the leads and product owner to feed on the motivation and removing any fear or shy factor from the team member. It is very essential for a team to succeed collectively on what they committed to or commit and see it to completion. By seeing it to completion means, a reward or appreciation of job well done puts the team into high motivation zone.

You need to have a “YAY team” effect before you can see the velocity being met or even better, team beating old records and showing the signs of urgencies. Small wins and achievements works towards strengthening the shared understanding bonds and an environment that resembles a truly successful scrum team gaining on velocity, loosing on debts and beating their own past records.

As always seen, the only way to get something awesome done by a team is when there is a genuine willingness to do something. Thus having a motivated and inspired team is very essential for a successful scrum team – YAY Team!

Signs of failing Scrum Team

  • In sprint planning, team discussing “what” and not “how” they would complete the sprint.
  • User stories does not follow Bill Wakes INVEST criteria.
  • Poker and complexity numbers are arbitrary.
  • You’re having hard time having full attendance on stand-ups or it is forced.
  • Adding additional processes in trying to make the sprint successful.
  • Team being victimized as incapable or dumb.
  • Software failing after being Tested.


Every aspect described here are interrelated. They all must be explored and worked on to create a YAY team effect. If you have most of these right, you are struggling but en route. If not most likely you are trying to control the sprints with multiple processes and still have no clue why it’s failing. You are slipping into waterfall model whereby you are calling it agile. Your team is simply being victimized and coined as incapable to deliver.
Monday, 11 August 2014 05:42:17 (GMT Standard Time, UTC+00:00)  #  Comments [34] Trackback
 Friday, 10 February 2012
Kickstart jQuery Widget using Widget Factory

I was looking for a simple yet complete example of a working widget with widget factory from a scratch. Having trouble finding one, I came up with this blog post. Here I would explain how to create a custom widget from scratch. Widgets or Plugins are simple generic control or a unit of process that can be attached to any DOM element to give it a specialized behavior with methods and properties. The jQuery UI Widget Factory is the base class which is extended by all widgets.


To build a simple jQuery widget you need jQuery core library and jQuery UI library. JQuery UI is what contains the definition and base classes for widget factory. You may customize it to download the bare minimum to make your widget work. These can be downloaded from jQuery website or referenced as a link to CDN (Content Delivery Network).
JQuery core library can be downloaded from here
JQuery UI can be downloaded from here
Microsoft Ajax CDN contains the links for most jQuery core and jQuery UI that can be referenced. Visit for more details.

Project Structure

As a good practice for JavaScript coding, there are few things you should follow:
  • Keep jQuery core library files and your custom code files in separate folders
  • Use small case or camel case naming rules
  • Use uncompressed for development/debugging and compressed for production
  • Use namespace that uniquely separates your widget from other jQuery UI widgets
Here is a picture for project structure, I have created:

Widget Code Structure

There are plenty of materials out on the web explaining how to write a widget using widget factory. To kick start here are few good ones: You might come across multiple ways of doing same thing. This is because JavaScript itself is quite versatile and does not impose restrictions like most compiled languages do. However, as we move forward, I will explain the important methods that would get you going and start writing some interesting widgets. Following image explains the structure of a simple widget that uses widget factory.

Note the followings:
  • (function ($) { ... }(jQuery)); - This implies anonymous function to which jQuery is passed as an argument.
  • $.widget - This is where it calls and extends the base class of jQuery UI widget factory.
  • my.roundButton - This is the fully qualified namespace and class name of my widget.
  • Method prefixed with underscore are meant to be private. This is just a convention, since, there is no scope identifier in JavaScript.
  • options: This defines all the widget properties with default values.
  • _create: This is like a constructor. Fired only once by the widget factory during initialization.
  • _init (not in my code): This is also like a constructor. Fired every time by the widget factory each time widget is called without arguments. Mainly, used for default functionality implementation.
  • _setOption: Called to change a single property value of the widget defined in options. Example - $('#elem').roundButton('option', 'size', 100)
  • _setOptions: Called to change a multiple property value of the widget defined in options.
  • _destroy: This is like a Destructor. Cleanup code goes here.


Let us look at the html page that uses this widget. Things to note here is what scripts are referenced and how a widget is initialized with multiple arguments.

Note how multiple properties are set during the instantiation of the widget. Also note how a widget method is called with parameters. We will discuss about the function attached to "OnPressed" property in the next section.

Custom Events

If you have authored any control in any language, you must have come across the need of raising or chaining events to allow user implement custom code during state changes of the control. For example a user wants to execute some custom action when the widget is clicked. It might be a timeout, ajax call or an alert. You, as an author need to raise an event when the widget is clicked and let the user handle the custom action.

This can be done using the "_trigger" function of jQuery core. Signature of this function is : _trigger("callbackFunction", [eventObject], [arguments]). One must also check if the user has provided custom action code. In other words if the callbackFunction is not null then call it using "_trigger" function. For this, we will create a property in options section called "onPressed". During the click event if the "onPressed" is not null, the widget will call the "_trigger" function.

if (this.options.onPressed != null)
    this._trigger("onPressed", this.control);

Complete Code of "roundButton" Widget

            (function ($) {
                $.widget("my.roundButton", {
                    //control properties
                    options: {
                        radius: '5px',
                        text: "Click Me!",
                        backColor: "#bbbbbb",
                        onPressed: null
                    //ctor (called only once)
                    _create: function () {
                        //remove and redraw the control
                        //save the reference in this.control
                        this.control = $("
") .html(this.options.text) .css("border", "2px solid #a1a1a1") .css("padding", "10px 40px;") .css("background", this.options.backColor) .css("width", "300px;") .css("border-radius", this.options.radius) .appendTo(this.element); //create element this._refresh(); //bind events this._bindEvents(); }, _refresh: function () { this.control .css("background", this.options.backColor) .html(this.options.text); }, //single property setter _setOption: function (key, value) { //update widget factory this._super(key, value); }, //multiple property setter _setOptions: function (options) { //update widget factory this._super(options); this._refresh(); }, //bind internal click event that triggers onPressed event _bindEvents: function () { //remove event binding //Notice the use of this.control this._off(this.control, "click"); //rebind this._on(this.control, { "click": function () { //change property this.options.backColor = "#e7e7e7"; this.options.text = "Clicked"; //refresh this._refresh(); //We will learn how to trigger a custom event in jQuery Widget // Signature of _trigger //this._trigger("callbackFunction", [eventObject], [arguments]) if (this.options.onPressed != null) this._trigger("onPressed", this.control); //change property this.options.backColor = "#bbbbbb"; this.options.text = "Click Me!"; //refresh this._refresh(); } }); }, //public method changeText: function(txt){ this.options.text = txt; //refresh this._refresh(); }, //cleanup _destroy: function () { this.element.empty(); } }); }(jQuery));

Hope it helped ... Enjoy !!

Friday, 10 February 2012 14:02:29 (GMT Standard Time, UTC+00:00)  #  Comments [24] Trackback
 Sunday, 07 June 2009
Fun with SQL Query

Find Nth Max or Min Record

This query gets the Nth highest salary from the emp table. You can replace the Max function with Min to obtain Nth lowest salary.

SELECT Eno, Ename, Desig, Sal, Mgr, DNO
FROM dbo.Emp AS
WHERE (N - 1 =
            FROM dbo.Emp AS E2 WHERE (Sal > E1.Sal)))

Row Number

This query generates the row number for the records fetched.

               FROM dbo.Emp AS
               WHERE (e2.Eno <= e.Eno)) AS RowNumber,
Ename, Desig,
            FROM dbo.Emp AS


Running Total

This query computes the running total on salary for the records in Emp table.

SELECT a.Ename, SUM(b.Sal) AS RunningTotal
FROM dbo.Emp AS
INNER JOIN dbo.Emp AS b ON a.Ename >= b.
GROUP BY a.Ename

Find Duplicates

This query finds the duplicate records in Emp table.

SELECT Ename, Desig, Sal, COUNT(*) AS Duplicate
FROM dbo.
GROUP BY Ename, Desig,
ORDER BY Duplicate DESC, Ename

Let SQL Generate SQL

This query emits SQL queries as records fetched.

Select 'Select DName from Dept where Dno=' + CAST(DNO as varchar) from Emp

Sunday, 07 June 2009 06:07:50 (GMT Standard Time, UTC+00:00)  #  Comments [56] Trackback
 Sunday, 17 May 2009
Getting Started with WCF

WCF Kick Start

In this article I would be describing the simplest form of WCF (Windows Communication Foundation) project which would get you started with the WCF concepts and best practices. The purpose is to minimise the confusion from code and configuration and explain the idea along with the best practice. I would also provide description and links to help you move to a more advanced WCF topics as and when required.

For the sake of kick start I would be using basicHttpBinding for the service and consumer, which does not require any kind of authentication when accessing the service. It is kind of open to all.

Below is an overall image of the solution, projects and project files that I have used to demonstrate the simplest form of WCF implementation.


The solution contains a project WcfServiceOne which defines types for contracts exposed by the service. The person class is the data contract, MyService is the service and IMyService is an interface acting as a service contract. This project acts as an API for the services.

The ServiceOneHost is the service exposed to the client. It references the project WcfServiceOne which the actual implementation of the Service as an API. Though, I could have had the service implementation written in the same project, I preferred following the best practices, by implementing the Service and Service API (contracts and its implementation) in a separate project. One advantage of doing this is that, you have decoupled service and Service API, which simplifies using the API in a non-WCF environment by directly referencing it. The web.config file in this project contains the binding information for the service which I will be explaining later in this article.

The ServiceOneConsumer is a simple ASP.Net web application consuming the service exposed by ServiceOneHost. The web.config in this web application contains the binding information defined by the host.


WcfServiceOne project contains:

  • Data Contract - Person.cs
  • Service Contract - IMyService.cs
  • Service Implementation - IMyService.cs
Also notice that the project references System.ServiceModel and System.Runtime.Serialization which are required to assign attributes like ServiceContract, OperationContract, DataContract and DataMember.


using System.Runtime.Serialization;


namespace WcfServiceOne






        publicstring FullName { get; set; }



        publicstring Gender { get; set; }




using System.ServiceModel;


namespace WcfServiceOne






        string Callme(Person p);




namespace WcfServiceOne


    publicclassMyService : IMyService


        publicstring Callme(Person p)


            return"Hello " + p.FullName + "  " + " you are a " + p.Gender;





Add a reference to WcfServiceOne and then right click on the project. Select "Add New Item" from the context menu and select "WCF Service" templates. Name the new file ServiceOneHost.svc. The template would also create the code files for you in the App_Code folder. You can delete it, the code file is not required. Open the ServiceOneHost.svc and change the line to:

<% @ ServiceHost Language ="C#" Debug ="true" Service ="WcfServiceOne.MyService" %>


Now open the web.config file in this project and add the following block at the last within the closing of configuration tag.

  < system.serviceModel >

    < behaviors >

      < serviceBehaviors >

        < behavior name ="ServiceOneHostBehavior">

          < serviceMetadata httpGetEnabled ="true"/>

          < serviceDebug includeExceptionDetailInFaults ="false"/>

        </ behavior >

      </ serviceBehaviors >

    </ behaviors >

    < services >

      < service behaviorConfiguration ="ServiceOneHostBehavior"name="WcfServiceOne.MyService">

        < endpoint address =""binding="basicHttpBinding"contract="WcfServiceOne.IMyService">

          < identity >

            < dns value ="localhost"/>

          </ identity >

        </ endpoint >

        < endpoint address ="mex"binding="mexHttpBinding"contract="IMetadataExchange"/>

      </ service >

    </ services >

  </ system.serviceModel >

system.servicemodeltag defines how the consumer is going to connect to the service exposed here. When you add a "WCF service" to the project using template, it responds with adding the above system.servicemodel in the web.config, except the following two lines.

      < service behaviorConfiguration ="ServiceOneHostBehavior"name="WcfServiceOne.MyService">

        < endpoint address =""binding="basicHttpBinding"contract="WcfServiceOne.IMyService">

Change the name, contract and binding information as shown above. The wsHttpBinding is used to provide more secured communication using certificate. Visit The pattern and practices for WCF security at Codeplex for further guidance on how to implement wsHttpBinding using certificates.


Before you proceed with consumer, you need to generate a proxy for the service and define how it connects, in the web.config file. To generate the proxy and the configuration block we would use svcutil. Open the Visual studio command prompt from Visual Studio Tools and use the following command to generate the proxy and configuration.

svcutil http://localhost/ServiceOneHost/ServiceOneHost.svc /Language:C# /out:ServiceHostProxy.cs /config:ServiceHost.config

This will create a ServiceHostProxy.cs and ServiceHost.config. Open the ServiceHost.config and copy the block. Now open the web.config file and paste the block at the end before the closing tag of configuration. The endpoint address might differ depending your host and consumer address URL.

    < system.serviceModel >

        < bindings >

            < basicHttpBinding >

                < binding name ="BasicHttpBinding_IMyService"closeTimeout="00:01:00"

                         openTimeout ="00:01:00"receiveTimeout="00:10:00"

                         sendTimeout ="00:01:00"allowCookies="false"

                         bypassProxyOnLocal ="false"

                         hostNameComparisonMode ="StrongWildcard"

                         maxBufferSize ="65536"maxBufferPoolSize="524288"

                         maxReceivedMessageSize ="65536"

                         messageEncoding ="Text"textEncoding="utf-8"

                         transferMode ="Buffered"

                         useDefaultWebProxy ="true">

                    < readerQuotas maxDepth ="32"maxStringContentLength="8192"

                                  maxArrayLength ="16384"

                                  maxBytesPerRead ="4096"

                                  maxNameTableCharCount ="16384" />

                    < security mode ="None">

                        < transport clientCredentialType ="None"proxyCredentialType="None"

                            realm ="" />

                        < message clientCredentialType ="UserName"algorithmSuite="Default" />

                    </ security >

                </ binding >

            </ basicHttpBinding >

        </ bindings >

        < client >

            < endpoint address ="http://localhost/ServiceOneHost/ServiceOneHost.svc"

                binding ="basicHttpBinding"bindingConfiguration="BasicHttpBinding_IMyService"

                contract ="IMyService"name="BasicHttpBinding_IMyService" />

        </ client >

    </ system.serviceModel >


Now add the following UI in the home page of your consumer site. In this case it is Default.aspx.

< table style =" width: 400px;"cellspacing="0"cellpadding="0">


        <tdstyle="width:100px; vertical-align:top; text-align:left;">

            Your Name


        <tdstyle="width:10px; vertical-align:top; text-align:left;">



        <tdstyle="width:290px; vertical-align:top; text-align:left;">





        <tdstyle="vertical-align:top; text-align:left;">



        <tdstyle="vertical-align:top; text-align:left;">



        <tdstyle="vertical-align:top; text-align:left;">















</ table >

Default.aspx.cs - Code Behind

using System;

using WcfServiceOne;


public partial class _Default : System.Web.UI.Page


    protectedvoid Page_Load(object sender, EventArgs e)


        txtName.Text = "Manish Kumar Singh";


    protectedvoid btnSubmit_Click(object sender, EventArgs e)


        var p = newPerson {FullName = txtName.Text, Gender = ddlGender.SelectedValue};


        var proxy = newMyServiceClient();

        lblResult.Text = proxy.Callme(p);



That's it. Now run the consumer site and give it a try.


Sunday, 17 May 2009 17:42:17 (GMT Standard Time, UTC+00:00)  #  Comments [142] Trackback
 Saturday, 09 May 2009
Compile .NET code on the fly

In this section I would like to demonstrate how to compile a .NET code on the fly. The code has been written in C#. It contains a class "InlineParser" which does the main job. It mainly, defines the class, does in-memory compilation and exposes a method for the execution of an inner method defined in the class. It also supports a choice of language whether C# or VB.NET for compilation.

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Linq;

    4 using System.Text;

    5 using Microsoft.CSharp;

    6 using Microsoft.VisualBasic;

    7 using System.CodeDom.Compiler;

    8 using System.Reflection;

    9 using System.Xml.Linq;


   11 namespace com.eforceglobal.crux.bre

   12 {

   13     internalclassInlineParser

   14     {

   15         string expression = string.Empty;

   16         string functionArguments = string.Empty;

   17         string language = "CSharp";

   18         XDocument paramList = null;

   19         object objBase = null;


   21         public InlineParser(string expr, string functionArgs, XDocument parameters, string lang)

   22         {

   23             expression = expr;

   24             functionArguments = functionArgs;

   25             paramList = parameters;

   26             language = lang;

   27         }


   29         publicbool init()

   30         {

   31             if(language.ToLower().Equals("csharp"))

   32                 return InitCSharp();

   33             else

   34                 return InitVB();

   35         }


   37         internalbool InitCSharp()

   38         {

   39             // Compile the expression in a class on the fly

   40             CSharpCodeProvider cp = newCSharpCodeProvider(

   41                 newDictionary<string, string>() { { "CompilerVersion", "v3.5" } } );


   43             //ICodeCompiler ic = cp.CreateCompiler();

   44             CompilerParameters cparam = newCompilerParameters();

   45             cparam.GenerateInMemory = true;

   46             cparam.GenerateExecutable = false;



   49             // Reference Assembly

   50             cparam.ReferencedAssemblies.Add( "system.dll" );

   51             cparam.ReferencedAssemblies.Add( "mscorlib.dll" );

   52             cparam.ReferencedAssemblies.Add( "System.Core.dll" );

   53             cparam.ReferencedAssemblies.Add( "System.Xml.dll" );

   54             cparam.ReferencedAssemblies.Add( "System.Xml.Linq.dll" );



   57             // Write your code

   58             StringBuilder sb = newStringBuilder();

   59             sb.Append( "using System;\n" );

   60             sb.Append( "using System.Collections;\n" );

   61             sb.Append( "using System.Collections.Generic;\n" );

   62             sb.Append( "using System.Text;\n" );

   63             sb.Append( "using System.Text.RegularExpressions;\n" );

   64             sb.Append( "using System.Reflection;\n" );

   65             sb.Append( "using System.Linq;\n" );

   66             sb.Append( "using System.Xml.Linq;\n" );


   68             sb.Append( "namespace com.eforceglobal.crux.bre {\n" );

   69             sb.Append( "public class EvalClass {\n" );

   70             sb.Append( "public EvalClass(){}\n" );

   71             sb.Append( "public object Evaluate(\n" );

   72             sb.Append( functionArguments ).Append( " ) {\n" );

   73             sb.Append( expression ).Append("\n");

   74             sb.Append( "}\n}\n}" );


   76             //Console.WriteLine( sb.ToString() );


   78             string code = sb.ToString();

   79             CompilerResults cres = cp.CompileAssemblyFromSource( cparam, code );


   81             // Compilation Unsuccessfull

   82             StringBuilder errors = newStringBuilder();

   83             foreach ( CompilerError cerr in cres.Errors )

   84                 errors.Append( cerr.ErrorText );


   86             if ( cres.Errors.Count > 0 )

   87                 thrownewException( errors.ToString() );


   89             // Compilation Successfull

   90             if ( cres.Errors.Count == 0 && cres.CompiledAssembly != null )

   91             {

   92                 Type ClsObj = cres.CompiledAssembly.GetType( "com.eforceglobal.crux.bre.EvalClass" );

   93                 try

   94                 {

   95                     if ( ClsObj != null )

   96                     {

   97                         objBase = Activator.CreateInstance( ClsObj );

   98                     }

   99                 }

  100                 catch ( Exception ex )

  101                 {

  102                     throw;

  103                 }

  104                 returntrue;

  105             }

  106             else

  107                 returnfalse;

  108         }


  110         internalbool InitVB()

  111         {

  112             // Compile the expression in a class on the fly

  113             VBCodeProvider vb = newVBCodeProvider(

  114                 newDictionary<string, string>() { { "CompilerVersion", "v3.5" } } );


  116             //ICodeCompiler ic = cp.CreateCompiler();

  117             CompilerParameters cparam = newCompilerParameters();

  118             cparam.GenerateInMemory = true;

  119             cparam.GenerateExecutable = false;



  122             // Reference Assembly

  123             cparam.ReferencedAssemblies.Add( "system.dll" );

  124             cparam.ReferencedAssemblies.Add( "mscorlib.dll" );

  125             cparam.ReferencedAssemblies.Add( "System.Core.dll" );

  126             cparam.ReferencedAssemblies.Add( "System.Xml.dll" );

  127             cparam.ReferencedAssemblies.Add( "System.Xml.Linq.dll" );



  130             // Write your code

  131             StringBuilder sb = newStringBuilder();

  132             sb.Append( "Imports System\n" );

  133             sb.Append( "Imports System.Collections\n" );

  134             sb.Append( "Imports System.Collections.Generic\n" );

  135             sb.Append( "Imports System.Text\n" );

  136             sb.Append( "Imports System.Text.RegularExpressions\n" );

  137             sb.Append( "Imports System.Reflection\n" );

  138             sb.Append( "Imports System.Linq\n" );

  139             sb.Append( "Imports System.Xml.Linq\n" );


  141             sb.Append( "Namespace com.eforceglobal.crux.bre \n" );

  142             sb.Append( "Public Class EvalClass \n" );

  143             sb.Append( "Public Function Evaluate ( " );

  144             sb.Append( functionArguments ).Append(" ) As Object\n");

  145             sb.Append( expression ).Append( "\n" );

  146             sb.Append( "End Function\n" );

  147             sb.Append( "End Class\n" );

  148             sb.Append( "End Namespace" );


  150             //Console.WriteLine( sb.ToString() );


  152             string code = sb.ToString();

  153             CompilerResults cres = vb.CompileAssemblyFromSource( cparam, code );


  155             // Compilation Unsuccessfull

  156             StringBuilder errors = newStringBuilder();

  157             foreach ( CompilerError cerr in cres.Errors )

  158                 errors.Append( cerr.ErrorText );


  160             if ( cres.Errors.Count > 0 )

  161                 thrownewException( errors.ToString() );


  163             // Compilation Successfull

  164             if ( cres.Errors.Count == 0 && cres.CompiledAssembly != null )

  165             {

  166                 Type ClsObj = cres.CompiledAssembly.GetType( "com.eforceglobal.crux.bre.EvalClass" );

  167                 try

  168                 {

  169                     if ( ClsObj != null )

  170                     {

  171                         objBase = Activator.CreateInstance( ClsObj );

  172                     }

  173                 }

  174                 catch ( Exception ex )

  175                 {

  176                     throw;

  177                 }

  178                 returntrue;

  179             }

  180             else

  181                 returnfalse;

  182         }


  184         publicstring Evaluate()

  185         {

  186             string result = string.Empty;

  187             Type type = objBase.GetType();

  188             MethodInfo mInfo = type.GetMethod( "Evaluate" );


  190             if ( mInfo != null )

  191             {

  192                 ParameterInfo[] pInfo = mInfo.GetParameters();

  193                 object[] arguments = null;

  194                 if(pInfo!=null) arguments = newobject[pInfo.Length];

  195                 if ( pInfo != null )

  196                 {

  197                     foreach(ParameterInfo p in pInfo )

  198                         if ( paramList.Element( "arguments" ).Elements( p.Name ) != null )

  199                         {

  200                             arguments[p.Position] = (paramList.Element( "arguments" )

  201                                 .Elements( p.Name ).Single().Value);

  202                         }

  203                     if ( pInfo.Length != arguments.Length )

  204                         thrownewArgumentException( "Insufficient parameters." );

  205                 }


  207                 result = mInfo.Invoke( objBase, arguments ).ToString();

  208             }


  210             return result;

  211         }

  212     }

  213 }

Notice that the class name of the class to be compiled is "EvalClass" and the inner method of the class is "Evaluate". Calling the "Evaluate()" method requires you to execute the following lines of code.

  1 var parser = newInlineParser(subExpression, funcArgs, Arguments.Document, lang);

  2 parser.init();

  3 retString = parser.Evaluate();


Saturday, 09 May 2009 06:21:03 (GMT Standard Time, UTC+00:00)  #  Comments [179] Trackback
 Sunday, 29 March 2009
Microsoft Surface ... CLI to GUI and Now NUI (Natural User Interface)


Microsoft Surface Touch TableI was hearing about Microsoft Surface far last few months, but did not get much information. Recently, I saw a post "PDC 2008" by Robert Levy and Brad Carpenter having a video session demonstrating the capabilities of Microsoft Session. The demonstrate the unique attributes of Microsoft Surface computing, with a dive into vision-based object recognition and core controls like ScatterView, and how the Surface SDK aligns with the multi-touch developer roadmap for Windows 7 and WPF. The software giant has built a new touch screen computer — a coffee table that will change the world. Forget the keyboard and mouse, the next generation of computer interfaces will be NUI (Natural User Interface) which uses natural motions, hand gesture and real world physical objects. The surface is capable of object recognition, object/finger orientation recognition and tracking, and is multi-touch and is multi-user. Users can interact with the machine by touching or dragging their fingertips and objects such as paintbrushes across the screen, or by placing and moving placed objects. This paradigm of interaction with computers is known as a natural user interface (NUI). Surface has been optimized to respond to 52 touches at a time.

Microsoft Surface applications can be written in Windows Presentation Foundation (WPF) and .Net language like C# or VB.Net. It is nicely integrated with Visual Studio 2008 following the same pattern of programming paradigms the .Net developers are used to. However it has custom WPF controls to allow programming for the unique interface of Surface. Developers already proficient in WPF can utilize the SDK to write Surface apps.

Object Recognition Multi User Application

Microsoft Surface SDK 1.0

Right now, Microsoft Surface SDK is not available for public. It has been distributed only to some of the Microsoft partners. I am eagerly waiting to get my hands on the SDK once it is launched. Since, I have already worked with SilverLight and WPF, I think, it would be quite easy to pick Microsoft Surface. This is true for every developer worked on WPF and used XAML. However, there is a small catch ... Working for surface would require more creativity and unlearning the GUI which we are used to. The new interface requires us to think about the UI from entirely a new perspective ... a 360 degree multi-touch perspective.

I am sure the developers deep in love with .NET programming and having high respect for Microsoft Technologies, would be very excited after seeing the video session of PDC 2008. The features demonstrated, and the ease of programming together with seamless process of learning would make you sit up staright on your seat, open Google to find out whether you can get hold of Microsoft Surface SDK. Hmm! As you might be thinking after watching the video, whether you need the touch screen device which costs $10K-15K, to practice Microsoft Surface? The answer is No! Microsoft has a simulator for Surface which would allow you to deploy and play around with your surface code. Unfortunately, that too is not available to public right now. So you might have to wait a little more, until of course you are working for the company included in the Microsoft's Partner list, currently allowed to download and use Microsoft Surface SDK and Simulator.

It Is Not Just Another Glorified And Hyped Touch Screen Computer

Many had a wrong impression about Microsoft Surface thinking it to be another glorified and hyped touch screen computer. The touch screen computers enable users to do away with keyboard and mouse. They can navigate the menu by touching various options to reach a logical end of viewing data or printing. And there ends the comparison. Microsoft Surface device also known as Microsoft Tabletop can do many more things, which you might think are not possible!

The three main components that differentiates it from a regular Touch-Screen device, Direct interaction, Multi-Touch Contact and Object Recognition.

  Object Recognition
  • Multi-touch contact: User need not use only one finger to manage digital data. If user dips five fingers in five different colors in the on screen paint palette and draws five lines with five fingers, you get five lines with five colors . . .
  • Direct interaction: Facility to manage digital information with hand gestures and touch instead on mouse and keyboard.
  • Object Recognition: This technology allows non-digital objects to be used as input devices. This means that the input source does not necessarily have to be digital in form.

This Is The Future

Companies are putting in millions of dollar in research for NUI. There is a nice video "TED: Sixth Sense" from Pattie Maes' lab at MIT, spearheaded by Pranav Mistry. It's a wearable device with a projector that paves the way for profound interaction with our environment. It demonstrates a device which responds to natural gestures of hand which is read by a camera. The UI is developed and projected using a small projector fitted in the same device. If you guys have seen movies like "Minority Report", see these technologies nearing to the imaginations.

The NUI immensely increases interaction with digital contents in a more simplified manner. One does not need to practice with mouse. It won't be a single user interface anymore. Two users can open two different menus at the same time .... (Right now your application would open one menu at a time). A 360 degree interaction, with each person using the same application independently. Surely, we need to think and see the UI very differently now and you are bound only by your imaginations.

So friend's start unlearning the GUI you are accustomed to, and buckle your seat belts for the next gen -- NUI.


.Net | Thoughts
Sunday, 29 March 2009 09:26:22 (GMT Standard Time, UTC+00:00)  #  Comments [189] Trackback
 Monday, 23 February 2009
Interactive Video Advertising With Silverlight 2


Rich media advertisement is a buzz word today. Organizations are spending a huge amount to move out from a traditional banner advertisement approach, booklets and television to a more effective tactics where they can reach out to a wider mass through internet. Rich media advertisement forms a basis of wider coverage at less cost together with a wonderful user experience.

Macromedia Flash, already provides a state-of-art solution for it. However, it is mostly tied to its proprietary engine for shock wave and interaction. Flash are further, required to be embedded as a compiled unit. Besides all, it requires you to learn Flash an extra skill.

Something I like about silverlight is that it supports XAML based platform with language support for programming. EXtensible Application Markup Language (XAML) which is pronounced as Zamel, is used to define your canvas and storyboard, which are easy to manipulate at runtime using languages like C# or VB.Net. These are further deployed as a compressed unit rather than a compiled unit. This is no doubt a step further than what Flash has achieved. One drawback, however, is, adoption among wide number of serious users. I don't see it as a big drawback as long as Microsoft is serious about this product.

Silverlight Kickstart

My silverlight development environment includes VS2008 with SP1, Framework 3.5, Silverlight SDK and Microsoft Expression Encoder. I would not get into these details for the scope of this article. You may refer to Getting Started article for Silverlight, to setup your development environment. Further, if you donot want to get into the intrecacies of XAML, then you might also require Microsoft Expression Blend.

WMV for streaming Video with Silverlight

Silverlight supports WMV format for videos. Using Microsoft Expression Encoder these WMV files can be encoded to have markers on their timelines. These markers can be used by siliverlight for interaction. The markers are simply names given to a time in the video's timeline. Silverlight raises MarkerReached event (if registered) when a marker is reached while playing the video. This forms the basis of interaction between silverlight and streaming videos. There is a nice video tutorial explaining, how to add a marker using Microsoft Expression Encoder.

Silverlight UI

XAML in Silverlight allows you to do a lot of stuffs with the UI using its declarative tags. Few, real interesting things you can do, without any extra skill required, includes, drawing a curve, masking, controlling opacity, define animation ... all through XML like declarative tags ... Wow!. In this tutorial, I will be showing you how to create an interactive overlay on a running video. For this, I have a video with three markers defined on it (using Encoder). Now let us first examine the UI.

The UI

Few things, I would like to explain here, before we proceed to next step, since they have been referred ahead. Take a sneak into the code for things, I have marked in bold. Notice that:

  • Movie name is "MainMovieStream" defined as an attribute "x:Name".
  • The "MarkerReached" event is registered for the movie as "MainMovieStream_MarkerReached".
  • Canvas with a name "TopOverlay" which is placed -325 pixels on the left.
  • "TopOverlay" canvas has an inner element "TopText" with an event "MouseLeftButtonDown" handled by "TopText_MouseLeftButtonDown" function
  • A Canvas "BottomOverlay" is defined in a similar faishon except its top is "131".
Silverlight Story Board

Take a sneak into the code for things, I have marked in bold. Notice that:

  • Storyboard "TopOverlayIn" targets the canvas "TopOverlay".
  • The "Storyboard.TargetProperty" tells us that the "Left" property has to be changed.
  • The "SplineDoubleKeyFrame" defines, that after every 1 sec the target property moves near to the "Value=0". Hence, the Canvas.Left moves from -325 to 0
  • The Storyboard "TopOverlayOut" does exactly the opposite of "TopOverlayIn".


The Storyboards are treated as Canvas resource which would be used when required. Let us see the complete XAML for our tutorial.

C# Code

When you add a XAML file into your solution, visual studio responds with adding an associated code behind file for the XAML. Besides, you would also find a App.xaml and its code behind file with same name. While doing any development on Silverlight, most of the time you would ask "How can I pass values to Silverlight application at runtime" or in another way "How can I make it as a component to be used in other projects?". This is done through parameter passing at the time of initialization.


Let us sneak into App.xaml.cs file where the necessary changes has been made for the same. The only changes required in the App.xaml.cs file are:

  • Declare an "IDictionary" object for paramters as a class variable

    public partial class App : Application {

        private IDictionary<string, string> initParams;


  • Initialize it in the "Application_Startup"

    private void Application_Startup(object sender, StartupEventArgs e)


        this.RootVisual = new MediaControl();

        InitParams = e.InitParams;



Now let us sneak into the MediaControl.xaml.cs file to see how we collect the parameters and how we handle the animation and events.

In the code above we get the reference of the Silverlight application using "Application.Current as App" (marked in bold) in the "Page_Loaded" event. Once we have got the handle of the application we can access its public properties. In this case the parameters. As you can see, I am iterating through each parameters and storing the values into my local variables. The marker parameters here contains the storyboard names that we would see in the next section. Also notice, how I am handling the "MarkerReached" event and the "MouseLeftButtonDown" events. The actions are self explanatory here.

Embedding Silverlight RichMediaAd Control

Once you have done with this code, your control is ready to be used. When you compile a Silverlight application, you would notice that it generates a RichMediaAd.xap file under ClientBin folder of your web application which references the Silverlight application. This .xap file is nothing but a compressed file containing your application manifest and the DLL. You can use a simple un-zip command to view the files inside. In the page

Now let us see the code where we embed this Silverlight control we made.

Once you have embedded the XAP file. It is ready to run. Notice, that I am sending all necessary parameters at runtime, including the media I want to use.

Happy Silverlight Programming !!

Monday, 23 February 2009 14:14:53 (GMT Standard Time, UTC+00:00)  #  Comments [35] Trackback