Saturday, August 27, 2011

Is ballot process immutable?

Those who agitate against a misconducting priest are not against GOD. Indian constitution is devine, no one is objecting it's greatness. But what to do when priest is misconducting? Unfortunately constitution with its divinity and parliament as sacred legislative house cannot themselves offer governance to any society. There got be a functional government made up of competent people, capable of being representative as well as authoritative to uphold traditions of a particular parliamentary system. 

And the process of selecting such competent people is crucial to make this system work for any society. Such process can't be mere a competency assessment test or proportional representation. First of all this got to be peaceful and then workable, innovative and above of all mutable. Democracy suggests majority vote as one of the mechanisms through which this process can be exercised peacefully. Founding fathers of our nation suggested a workable solution in the form of a ballot which in fact was a popular form of practice prevailed at that time. And in last 60+ years the only improvement we could do is to convert a paper ballet to an electronic one. But we somehow caught in an impression that this process is immutable. Voting system can't be the only possible solution for this process.

Current day advances in network technology can offer more practical solutions for this problem. And the scope of the solution need not limit to electing but could also include selecting the candidates for election. And how can we make selection of a candidate a continuous process and election a periodic process say once in every 5 years?

Wednesday, August 24, 2011

Where were these maestros?

Now a days I am getting to know about so many people who are suggesting far superior methods than what Anna is following to fight against corruption in this country.

I don't know that there are so many knowledgeable people in this country who can suggest about intelligent ways to fight against corruption.

But it is quite unfortunate that I could hear and rather know about them only when a 70+ year old man makes a so called dangerous move.

Yesterday, few fellow country men, under the influence of alcohol, came to Ramlila ground and tried to create ruckus. Police came and took them away. I have high respect for them because they had to consume alcohol to behave abnormally. As influence of alcohol lasts for only few hours. I have no concern getting along those fellow citizens as soon as they come out of that influence. 

But I am highly afraid about these intellectual maestros who don't need to consume anything to be abnormal. And there is no hope that they will ever come out of an influence which makes them feel that they can do better than anybody else in this country. Dear friends though I admire your courage and confidence towards that supremacy, I would humbly request you to take that first step towards making yourself acceptable by being dignified when presenting views about fellow countrymen who are also trying to do good for this country at their capacity. May be the methods may not sound reasonable to you, but I hope there is no difference of opinion on objective. 

When you goto Palika bazar and ask for price of a picture, seller may quote 2000. And you may negotiate for 300. Deal could satisfy either party. It happens indeed. What I meant to say is quoting 2000 may sound stupid, but as a seller he/she knows what makes a negotiator happy. When you deal with government you would indeed place riders which govt. want to negotiate so that the middle ground becomes reasonable for either party. Of course if you are a habituated buyer in showrooms you wouldn't have come across such experiences.

But is this the way we want our systems to be forever? Of course no, but let every fellow countrymen make some way ahead to their capacity.

Tuesday, August 23, 2011

Who owns civil society?

Don't know who owns civil society? Problem lies with media refering any group of civilians as civil society. Looks like media must draft a guideline on eligibility to mention any group as civil society by consulting experts like Aruna Roy, Arundhati Roy etc..

If thy are all fighting for better society, don't they have some diligence that soldiers follow. Fight headon with points of conflict on subject of discussion which in this case is a bill. Why make provocative statements about methods and modus operandi? Let people exercise their freedom and do what they deem appropriate for a situation as long as it is peaceful and non-violent.

It's completely inappropriate to label Anna's movement as a dangerous phenomenon breeding impatience in the youth of this country. Anyway no need to substantiate that, as readers can distinguish it obviously.

Now I don't know if I would get classified as mass, though I have no concern over it, if I say that I don't mind supporting any cause that makes this country better including Anna's movement. Tomorrow if anyone else asks me to support their form of fight, either in the form of a movement or discussion or whatever that could be, I would support it if I see a clear benefit for this country. For that matter I would do so for every other cause to the extent feasible for me.

Everyone got their freedom of speech, but as a soldier fight with spirit against enemy, which in this case is corruption, rather than a tool and method used by other soldiers. Everyone cannot afford sophisticated ammunition, but if a latti is handy, what is wrong if anyone chooses to defend the community using a latti? Do you say they are not defending community and they can not claim themselves as community?

Saturday, August 06, 2011

Checking for integer ranges - C# to C

I had tough time explaining what should be the correct mechanism for checking integer range for a developer coming from C# to C.

Intention is to check a value within the range of 0 to 4. Anything less than 0 and above four is invalid.

Expression written is

((http_method > -1) && (http_method < 5))

I wrote a review comment to change expression as

(Method >= 0) && (Method <= 4))

Comment is not accepted and led to a discussion, rather argument.

I said I have a problem with first part of expression

(http_method > -1)

The '-1' could be tricky depending upon type of http_method.

And in this case http_method is unsigned int and returned false even for correct range.

It took a while to explain the expression is invalid.

Though C# has an 'uint' type, an 'int' would suffice the need in most of the scenarios.

So using correct data type is one part of it. Also when it comes to checking ranges it is always recommended to check inclusive ranges rather than outer ranges. One simple reason for that is test cases. Test cases with inclusive range are considered as positive test cases and boundary range are considered as negative test cases.

Technically there is no binding to follow inclusive range check. But it is a good convention to follow.

Changing diff/merge tool

I have been using Winmerge for years. Never expected that I would find any limitation with it. But it is failing to show diff view of c file modification in git repository with tortoise front end.

Moving to DiffMerge from SourceGear.

Though licensing is not so encouraging, it is a proving to be a good choice.

Shell integration is neat. No noise in diff view. Advantage with reference view and edited view.

So far so good.

Friday, July 22, 2011

Devloping web2.0 user interface for self hosted WCF services using HTML5, CSS3 and JQuery

WCFWebApp Image - maximum width is 600 pixels


Link to article

Introduction


This article describes a method to utilize WCF self hosted services to be able to serve web 2.0 user interface as well as web services.

By using this method tools or applications can be built using web 2.0 technologies like HTML5, CSS3 with self hosted WCF service as backend business layer. Thus developers can benefit from advanced javascript libraries like JQuery or Underscore etc.. to build user interface. This eliminates need to install .Net framework on client machines.

Traditionally self hosted WCF services has user interface built using WinForms and WPF technologies. And to be able to use browser as UI platform ASP.Net and IIS becomes hard dependencies. For tools and applications which typically are executed out of a single machine or intranet with limited users, IIS is considered as an overkill. Thus browser as a UI plarform with HTML5, CSS3 and backed by powerful javascript engines is very promising option for self hosted WCF services.


Background


Intial versions of WCF could only work with SOAP messages. With bindings like WebHttpBinding from .Net3.5 onwards WCF could offer direct support to consume web services from ajax calls from javascript. However consuming dataformats like JSON is still not so much so an out of box experience. Effort to write DataContracts for every argument and return types is quite high. And with other data formats like XML, client end couldn't directly benefit from javascript libraries due to extra step involved to convert from XML to JSON.


This method considers 'Stream' as input and out type for UI interfacing operations. It also supports basic authentication which can be extented for advanced usage. And no customization is done at any layer and just works based on out of box features of WCF in .Net 3.5. This can also be used with .Net 4.0. However for JSON.Net is used to format json objects.


Using the code


Download and build source. You can use Visual Studio 2010 or VS command line. (Code is built for .Net 4.0 but can be used with .Net 3.5 also)

  1. Start WCFWebApp.exe. If port 2011 is not free, change to different port. And you need admin previleges
  2. When server is running, open any browser with javascript support and navigate to "http:/:/index.htm"
  3. Enter username # 'user' and password # 'pass' and click on login. You will login and an about page is loaded
  4. Click on States link
  5. Check on visited option for any state and click on Update
  6. Change page to About and come back to States and observe that last selection is perisisted.
  7. Click on 'Logout' on right top corner.

All these operations are run out of a self hosted WCF service. And this demonstrated features like authentication, fetching static files, getting as well as setting and data. Following sections walk through code.


Server code


Main class just starts a WCF service using WebHttpBinding and WebServiceHost.

class Program
  {
    static void Main(string[] args)
    {            
      string baseAddress = "http://" + Environment.MachineName + ":2011/";
      using (WebServiceHost host = new WebServiceHost(typeof(WebApp), new Uri(baseAddress)))
      {
        WebHttpBinding binding = new WebHttpBinding();
        host.AddServiceEndpoint(typeof(IWCFWebApp01), binding, "").Behaviors.Add(new WebHttpBehavior());
        host.Open();
        ... other lines left for brevity
      }
    }
  }

Service contract defines a method 'Files' to serve all static html files, another method 'Links' serves all linked files like javascript, stylesheets and data. Other resources like login. logout, States and State are service operations. Observable point here is 'Stream' data type for input as well as output.

[ServiceContract]
    public interface IWCFWebApp01
    {
      [OperationContract, WebGet(UriTemplate = "/{resource}.{extension}")]
        Stream Files(string resource, string extension);

      [OperationContract, WebGet(UriTemplate = "/{path}/{resource}.{extension}")]
        Stream Links(string path, string resource, string extension);

      [OperationContract, WebInvoke(Method = "POST", UriTemplate = "/login")]
        Stream Login(Stream request);

      [OperationContract, WebInvoke(Method = "POST", UriTemplate = "/logout")]
        Stream Logout(Stream request);

      [OperationContract, WebGet(UriTemplate = "/states")]
        Stream States();

      [OperationContract, WebInvoke(Method = "POST", UriTemplate = "/state")]
        Stream State(Stream request);
    }

Now coming to service implementation. As this method is primarily intented for self hoseted WCF services, singleton isntance with concurrent threads is good enough. Consider sessions as applicable. But unlike IIS hosted services, self hosted services would nomally serve limited users and thus default concurrency is good enough. And on functional line constructor is just loading data onto local member.

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single,ConcurrencyMode=ConcurrencyMode.Multiple)]
    public class WebApp : IWCFWebApp01
  {
    JObject states;

    public WebApp()
    {
      if (states==null)
        states = JObject.Parse(File.ReadAllText("web\\data\\states.json"));
    }

    ... other lines left for brevity

  }

Now that server is running, when user tries to access for the first time, several htm, css and javascript files are served.
These are handled by methods 'Files' and 'Links'. Links are files refered in index.htm in head section like JQuery. And in 'Files' method different types of files are picked up from seperate folders based on extension. Switch cases can be extended based types of files.

public Stream Links(string path, string resource, string extension)
    {
       ... other lines left for brevity
    }

    public Stream Files(string resource, string extension)
    {
      switch (extension)
      {
        case "htm":
           ... other lines left for brevity
        case "js":
           ... other lines left for brevity
      }
    }

When user makes a login request, basic authentication token is sent in standard header "Authorization".
That is validated in a seperate method 'Authenticate' described later. Also username is sent as JSON object in request stream which is parsed into JSON object using JSON.Net library. Logout method is similar to login

public Stream Login(Stream request)
    {
      if (!Authenticate()) return null;
         ... other lines left for brevity
      JObject o = JObject.Parse(data);
    }

When user clicks on 'States' request reaches following method.
As this resource doesn't have any extension, request will not go through 'Files' method. Here request is authenticated and data is sent from member variable.

public Stream States()
    {
      if (!Authenticate()) return null;

      WebOperationContext.Current.OutgoingResponse.ContentType = "application/json";
      return new MemoryStream(Encoding.ASCII.GetBytes(states.ToString()),false);
    }

When user does a modification and clicks on 'Update', following method would be invoked. This parses state id and update class member variable and returns updated list back to client.

public Stream State(Stream request)
    {
      ... other lines left for brevity
      JObject data = JObject.Parse(new string(buffer));
      int id = ((int)data["id"]) -1;
      states["states"][id]["visited"] = true;

      return States();
    }

Authentication. Methods which require authorization invokes following method.

public bool Authenticate()
    {
      string userName = "user";
      string password = "pass";

      string basicAuthCode = Convert.ToBase64String (Encoding.ASCII.GetBytes (string. Format ("{0}: {1}", userName, password)));
      string token = WebOperationContext.Current.IncomingRequest.Headers["Authorization"];
      if (token.Contains(basicAuthCode))
      {
        return true;
      }
      else
      {
        WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Unauthorized;
        return false;
      }
    }


Client code


Client code is placed in seperate folder by name 'web'. At the root of this folder all static htm files are placed. And seperate sub-folders are included for images, javascript and stylesheets. These are refered from 'Files' method in server code based on extension.


Client follows Single Page Application design. Thus only 'index.htm' is a full html page. Other html files are filled into 'content' division using ajax calls as shown below for states

function StatesPage () {
  this.loadStatesPage = function (data) {
    content = undefined;
    $.each (data, function (index, value) {
      if (data[index]["id"]=="content") {
        content = data[index].innerHTML;
        $("#content")[0].innerHTML = content;
        $("#b_update")[0].onclick = updateStates;
        loadStatesTable();
      }
    });
    if (content == undefined) {alert("Failed to load page: Content missing"); return;} 
  }
      ... other lines left for brevity
}

Authentication: Client side authentication token is in login class. This token is added in header section in 'beforeSend' function of each call after login. Other code in client requires understanding abour Jquery, javascript and ajax concepts which is well explained on web.


Points of Interest


If windows authentication is required, service host can be customized

More structured javascript libraries with MVC architecture can also be used without making any change to server side code.

Consider using JQuery UI plugins for common look and feel

As UI is browser based, extending UI for handheld devices becomes quite easy.



Saturday, May 14, 2011

Off line access and chromebooks

Just curious to know, how to perceive on local storage and off line access of chrome books. Chrome is HTML 5 compliant and thus every site can leverage local storage, session storage and web SQL anyway. And I guess web SQL in chrome is nothing but a SQLITE instance. When all you can do is accessed through browser and each site having a site specific solution, is there still any need for disk storage on chrome books? If yes what could be that scenario?

Monday, May 09, 2011

Reusability and user experience

Reusability

Are you finding a phenomenon like use and throw with software applications?

Do you have anything about one time usability of applications? Often I get trickled about usability and reusability. An year back I was advised to emphasize more and more on usability and if at all I could build something reusable in it, it is just out of luck.

With rapid development frameworks and high fidelity needs designing anything for reuse is nothing but being stereotyped. There were times when reusability was discussed at every stage of development life cycle. Tools and technologies of those times asked for it. But we built runtime frameworks like Java, .Net etc. They are offering well tested reusable code for every possible computational need. Now what we are building is, nothing but application specific functional codebase. And there could only be a marginal scope  in it for reusable design. There is still scope but it is significantly low. That raises a question on what should be the strategy with respect to reusability in design. 

Another aspect is rapid prototyping,  dynamic languages, shorter delivery cycles, built-in user accepted mechanisms for application upgrades, well informed user, UX demanding networked systems. 

We are not building isolated apps like calculator and paint anymore. Even configuration, profiling and diagnostic tools are networked. 

And it is UX that matters at the end of the day. Now UX is a subject of taste for same need like hunger. It can't be same dish for breakfast, lunch and dinner. Then where is reusability in application development. Just like food need to be consumed while it remains fresh, app remains fresh for sometime only. 

With this background we need to adopt new strategies. It goes like software offers solutions for several problems surrounding human livelihood; but at the same it solves its own problems by looking at patterns of real world.

How does fabric design industry solve this problem. How does chefs solve and what entertainment industry does. And now the gadgets. 

Apps markets solved one side of this problem. Gone are the days where Microsoft builts one app to suit needs of whole world. Now there are several options for same need like calendar in markets. There is no one size fit for all. Yes there are some mostly downloaded apps. But there are several others too. Each one suits for someones taste. 

With markets gadget builders shielded themselves to great extent. Now they can concentrate on building just the platform. 

Now that leaves other side of the story up for discussion. What is in it for app developer with respect to reuasability.

1) Nurture multiple design options. Don't throw away anything just because it is not the best. More the time you spend time with need of the app the more you would meet expectations of broader userbase. 
Nurture multiple designs thinking that you are rich enough to build against each design. This is what fabric industry do.

Here you reuse understanding about characteristics of product for building against multiple designs rather reusing design.

2) Integrate services not userbase. Calendar app for world cup season is different from calendar app for competitive exams. Now you can build multiple views in same app. But building two distinct apps solves the problem in better way because the intended users are different even though program constructional aspects are same. Same story is told as book, documentary, movie etc..

3) Build reusable software just for multiple versions of same application than new application. Cost of building and maintaining reusable components is not economical anymore. As mentioned earlier there shouldn't be any hour spent specially to build a reusable component for next project. Moreover app development on different design is cheaper than maintenance. Most of the reusable stuff is used in enhancements than new development.  

4) Let users know the makers signature rather than technology. There is nothing called reusability of UX. It's called copyright violation. Tree controls are not looking like traditional tree controls, combo boxes are presented in so many ways where it's difficult to make it out as CB. So spend time to give facelist to your primitive controls for application specific look and feel. Your app should look like what it is meant for rather than Java app or winforms or wpf or PHP. You are not selling app to procurement manager or dealer. So there no one to  market your app. It should market for itself.

Sunday, November 14, 2010

Windows live services

eeks

this is how skydrive partal shows up this morning. Windows live gone
for a toss today.

Tuesday, June 15, 2010

Back to blog

Breaking silence. As new means of sharing information like twitter, wave, buzz etc.. came out I thought blog is kind of out dated platform. But I am not finding them as a perfect alternative thus thought of resuming blogging again.

Sunday, January 03, 2010

Happy New Year 2010

 Wish you and your family a very Happy, Prosperous and Cheerful Newyear 2010.

Monday, December 28, 2009

ArraySegment<T> Class

Somehow I missed such a useful class in .Net framework this now. This class is useful when we are working on one dimensional arrays and need to segment arrays.

One quick use case is network packets. Where we will allocate buffer upfront and fill segments to form a packet.

Good part of this class is multiple arraysegment objects can refer to same instance of array. Mean what we get is reference to original object rather than a copy. Any updates to segment will automatically update original array.

Isn’t useful? I feel so.

Saturday, December 19, 2009

Hosting IronRuby in MSBuild

This post builds on earlier post in this series and provides a mechanism to host IronRuby in MSBuild.

Basics of MSBuild

A very brief introduction of MSBuild is present here. MSBuild is a modern build file format built on XML technologies.
Important components of MSBuild are

  1. Project
  2. Target
  3. Task
  4. ItemGroup
  5. PropertyGroup
  6. Imports

Project stands as root element with a default namespace declaration. Find declaration in following example

<Project DefaultTargets = "HelloMSBuild"
xmlns="http://schemas.microsoft.com/developer/msbuild/2003" >

In this DefaultTargets attribute is of interest. Target is the set of actions that msbuild will perform against the project by default.

To understand better let us create a sample project by name “test.msproj”.

1) Create a new text file

2) Add Project element as shown above

3) Add target ‘HelloMSBuild’ as shown below

<Project DefaultTargets = "SayHello"
xmlns="http://schemas.microsoft.com/developer/msbuild/2003" >

<Target Name="SayHello">
<Message Text="Hello MSBuild" />
</Target>

</Project>

From visual studio command prompt run “msbuild test.msproj”. That is the simplest helloworld with MSBuild where target executes only task “Message”. “Message” is a built-in task. Built-in tasks are included by default. Thus we don’t find any declaration about where Message task is defined.

<Project DefaultTargets ="Lab02"

xmlns="http://schemas.microsoft.com/developer/msbuild/2003" >

<ItemGroup>

<
Items Include="Item1" />

<Items
Include="Item2" />

</
ItemGroup>


<
PropertyGroup>

<
PropertyA>Property1</PropertyA>

</
PropertyGroup>

<
TargetName="Lab02">


<
Message Text="$(PropertyA)"/>

<
Message Text="@(Items)"/>


</Target>

</
Project>

That gives a basic idea about using items and properties. A project can contain more than on ItemGroup elements. All items in ItemGroup must be of same type. In this case they are of “Items”. But a different ItemGroup can contain different kind of elements. We can only refer to items as a group. In this case we referred them @(Items). But properties can be referred individually. Actually we can refer to properties individually only. Format to access a property is $(PropertyName).

So far we have see built-in task “Message”. Now let us see how to build a custom task

Getting started with Custom Task

Here I describe the procedure to build a custom task by name SimpleTask. This task does nothing fancy, but this exercise provides some insight about working with custom tasks. Look at MyTasks01.dll custom task. And we are using UsingTask option to refer to custom task.

<Project DefaultTargets = "CreateDirectory"
xmlns="http://schemas.microsoft.com/developer/msbuild/2003" >
<
UsingTask AssemblyFile="D:\MsBuildTasks\MyTask01.dll" TaskName="SimpleTask"/>

<
ItemGroup>
<
Param Include="Param1" />
<
Param Include="Param2" />
</
ItemGroup>

<
PropertyGroup>
<
Param3>Param3</Param3>
</
PropertyGroup>

<
PropertyGroup>
<
Status />
</
PropertyGroup>


<
Target Name ="CreateDirectory">

<
SimpleTask MyProperty ="@(Param)" >
<
Output TaskParameter="MyMessage" PropertyName="Status"/>
</
SimpleTask>

<
Message Text="$(Status)"/>

<
SimpleTask MyProperty ="$(Param3)" >
<
Output TaskParameter="MyMessage" PropertyName="Status"/>
</
SimpleTask>
<
Message Text="$(Status)"/>

</
Target>

</
Project>

Alternative approach for UsingTask is importing external project as a whole. Sometimes this would be useful as the task needs more specific parameters or item groups. In such case all those parameters and item groups can be defined in external project and imported as a whole. To do this create a file by name “MyTasks.Targets” in same directory as task MyTask01.dll.

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<
UsingTask AssemblyFile="D:\MsBuildTasks\MyTask01.dll" TaskName="SimpleTask"/>
</
Project>

And to import this file in project file replace UsingTask element with

<Import Project="D:\MsBuildTasks\MyTasks.Targets"/>

Building Custom Task

Now let us see how to write a custom task. Create a library and refer to libraries (You can choose version 2.0 or 3.5)


  1. Microsoft.Build.Framework
  2. Microsoft.Build.Utilities

Then update class file as shown below

using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;

namespace MyTasks
{
public class SimpleTask : Task
{
public override bool Execute()
{
//Parameters are semi column seperated values
string[] parameters = myProperty.Split(';');
foreach (string paramter in parameters)
myMessage += paramter + " - Done\n";
return true;
}

private string myProperty;
public string MyProperty
{
get { return myProperty; }
set { myProperty = value; }
}

private string myMessage;
[Output]
public string MyMessage
{
get { return myMessage; }
set { myMessage = value; }
}
}
}


Here observe that we added ‘Output’ attribute to MyMessage. And that is taken into status property in output element of SimpleTask. Then the value is printed through Message task.

With this background about MSBuild, we can move to hosting IronRuby in MSBuild source.

IronRuby Task

This part creates a new task to host IronRuby Task.

Create a new class library. Add references to MSBuild libraries and IronRuby libraries which include

IronRuby, IronRuby.Libraries, Microsoft.Build.Framework, Microsoft.Build.Utilities.v3.5, Microsoft.Dynamic, Microsoft.Scripting, Microsoft.Scripting.Core.

Then replace source contents with following

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using IronRuby;
using IronRuby.Runtime;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;

namespace ABB.INCRC.MSBuildTasks
{
public class IronRubyTask : Task
{
#region Properties

string script;

[Required]
public string Script
{

get { return script; }

set { script = value; }

}

string status;
[Output]
public string Status
{
get { return status; }
}


#endregion
public override bool
Execute()
{
try
{
ScriptEngine engine = Ruby.CreateEngine();

ScriptSource source = engine.CreateScriptSourceFromString(script, SourceCodeKind.Statements);

Object result = source.Execute();

status = result.ToString();
}
catch (Microsoft.Scripting.SyntaxErrorException syntaxError)
{
status = "SyntaxErrorException : " + syntaxError.Message;
return false;
}
catch (MemberAccessException maex)
{
status = "MemberAccessException : " + maex.Message;
return false;
}
return true;
}
}
}

Build this library and copy to folder like D:\MsBuildTasks\IronRubyTask. Note that execution of this task depends on referred libraries. Thus you need to copy all libraries to this folder. In last post we have seen how to refer a task with UsingTask element.

Here we take a better approach by using an external task definition.

External Project Reference

Create a new file by name MyMSBuildTasks and place following content. This script does lot of work


  • Makes a reference to IronRubyTask
  • Creates property group to hold script elements, which increment AssemblyFileVersion. This is done by updating AssemblyInfo.cs file in properties folder. BuildNumber is persisted in a separate BuildNumber.txt file
  • Creates tasks to execute scripts
  • Scripts are concatenated from multiple properties thereby keeping scripts modular
<?xml version="1.0" encoding="utf-8"?>
<
Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

<
UsingTask AssemblyFile="D:\MsBuildTasks\IronRubyTask\IronRubyTask.dll" TaskName="IronRubyTask"/>

<
PropertyGroup>
<
GetBuild>
<![CDATA[
#Get Build

def getBuild(buildIndexFile)

begin

file = File.new(buildIndexFile, "r")

while (line = file.gets)
@token = line.split("=")
if (@token[0] == "build")
@build = Integer(@token[1])
end
if (@token[0] == "revision")
@revision = Integer(@token[1])
end
end

file.close

rescue => err

err
end

end

@build = -1
@revision = -1

getBuild("D:\\BuildNumber.txt")

]]>
</
GetBuild>

<
SetBuild>
<![CDATA[

#Set Build
def setBuild(buildIndexFile)
begin
buildIndex = "build=#{@build}\r\nrevision=#{@revision}"
File.open(buildIndexFile,"w") {|f| f.write(buildIndex) }

"Updated : #{buildIndexFile}"

rescue => err
err
end
end
]]>
</
SetBuild>

<
DefineFileVersion>
<![CDATA[

#update AssemblyVersion

def updateFileVersion(assemblyInfoFile)


if(@build > 65536)
@build = 0
end

if(@revision > 65536)
@revision = 0
end


assemblyInfo = File.read(assemblyInfoFile)

assemblyInfo = assemblyInfo.gsub(/AssemblyFileVersion\(\"1\.0\.(\d+)\.(\d+)\"\)/,
"AssemblyFileVersion(\"1.0.#{@build}.#{@revision}\")")
#puts assemblyInfo

begin
File.open(assemblyInfoFile,"w") {|f| f.write(assemblyInfo) }
"Updated : #{assemblyInfoFile}"
rescue => err
puts err
err
end


end
]]>
</
DefineFileVersion>

<
UpdateFileVersion>
<![CDATA[

#Execution Starts here

if @revision > 0
@revision = @revision + 1
else
@build = @build + 1
end

updateFileVersion("D:\\MsBuildTasks\\Properties\\AssemblyInfo.cs")

]]>
</
UpdateFileVersion>


<
SetBuildNumber>
<![CDATA[

#Execution Starts here

@build = @build + 1
@revision = 0

setBuild("D:\\BuildNumber.txt")

]]>
</
SetBuildNumber>

<
SetRevisionNumber>
<![CDATA[

#Execution Starts here

@revision = @revision + 1

setBuild("D:\\BuildNumber.txt")

]]>
</
SetRevisionNumber>

</
PropertyGroup>

<
Target Name="UpdateFileVersion">
<
IronRubyTask Script="$(GetBuild)$(DefineFileVersion)$(UpdateFileVersion)">
<
Output TaskParameter="Status" PropertyName="Status" />
</
IronRubyTask>
<
Message Text="$(Status)" />
</
Target>

<
Target Name="SetBuildNumber">
<
IronRubyTask Script="$(GetBuild)$(SetBuild)$(SetBuildNumber)">
<
Output TaskParameter="Status" PropertyName="Status" />
</
IronRubyTask>
<
Message Text="$(Status)" />
</
Target>

<
Target Name="SetRevisionNumber">
<
IronRubyTask Script="$(GetBuild)$(SetBuild)$(SetRevisionNumber)">
<
Output TaskParameter="Status" PropertyName="Status" />
</
IronRubyTask>
<
Message Text="$(Status)" />
</
Target>

</
Project>

Referring target file

Now create a test project file and refer above file.

<Project DefaultTargets = "Test"

xmlns="http://schemas.microsoft.com/developer/msbuild/2003" >

<
Import Project="D:\MsBuildTasks\ABB.INCRC.MSBuildTasks"/>

<
Target Name="Test" DependsOnTargets="UpdateFileVersion;SetBuildNumber;SetRevisionNumber" />

</
Project>

Here we use “DependsOnTargets” to call multiple targets from referred file.

Hope this post provided a use-case to host dynamic languages like IronRuby for useful tasks. Advantage of this approach is you need to build only one custom task. All other needs can be achieved using scripts. And scripts are part of msbuild project in the form of properties.

Tuesday, December 15, 2009

Hosting IronRuby in .Net applications - Part2

In last post of this series we have seen few examples of IronRuby. That is just a glimpse of IronRuby.
With this background we can take a look at integrating these snippets in a .Net application.

I would like to provide some basic introduction about Dynamic Language Runtime (DLR) and then present an example.

DLR Overview

DLR infrastructure provides solutions for different purposes which include

  1. port dynamic languages to .NET
  2. add dynamic features to existing language
  3. author libraries whose objects support dynamic operations
  4. employ (host) dynamic languages in applications and frameworks
But this post is oriented towards hosting scenarios only.

DLR is built on top of Common Language Runtime (CLR). Microsoft .Net framework is designed to support multiple programming languages on CLR. It provides common services like GC, JIT etc. for static languages like C#, VB.Net etc. The CTS and CLI infrastructure allows sharing libraries written in any language with any other language targeting CLR. And we rarely realize need to host CLR explicitly, as it is done automatically by various CLR executable modules due to modifications done to Portable Executable format.

DLR extends CLR with services required for dynamic languages like python, ruby. In similar lines it first extends type system to be dynamic. Then, incase of statically typed languages, meta data provides necessary relative virtual addresses at compile time for method invocations. These virtual pointers turn into realistic pointers during JIT compilation process and remain as is as long as execution engine is alive. This is not the case with dynamic languages which require a dynamic method dispatching mechanism. Also applications need to explicitly host Dynamic Runtime Engines. But DLR eases some effort here by providing a common hosting API for all dynamic languages targeting DLR. So if we summarize, key components of DLR would include

  1. dynamic type system
  2. dynamic method dispatching system
  3. common hosting API

Dynamic type system and dispatching system provide services for first three purposes mentioned at the beginning of ‘DLR Overview’. Common hosting API provide services for last purpose in that list.

Hosting Scenarios

As such there could be several scenarios in which DLR can be employed (hosted). Such scenarios include

  • executing a script in a given scope using default script-host
  • executing several scripts in multiple scopes using custom script-host
  • controlling on how to pre-compile and improve executing performance, an advanced scenario

This part of the series confines to first scenario in which one script is executed in a given scope.

Execution Overview

As mentioned above, this post is presenting the very basic mode of executing a script.
Steps involved in this process include

  • Create Script Engine for Ruby
  • Create Scope object from engine and set scope
  • Create code
  • Execute code within a given scope

Example

Following step by step procedure makes up a simple application to host IronRuby

  1. Start Visual Studio and create a new console application. Copy required
  2. Refer following dependent assemblies from ~\<Program Files>\IronRuby 0.9.2\bin
    IronRuby.dll
    IronRuby.Libraries.dll
    Microsoft.Dynamic.dll
    Microsoft.Scripting.Core.dll
    Microsoft.Scripting.dll
  3. Add following using statements
  4. using IronRuby;
    using Microsoft.Scripting.Hosting;
    using Microsoft.Scripting;

  5. Add following code in Main

  6. ScriptEngine engine;
    ScriptScope scope;

    String code;

    Int32 i1 = 20;
    Int32 i2 = 10;

    engine = Ruby.CreateEngine();
    scope = engine.CreateScope();

    scope.SetVariable("i1", i1);
    scope.SetVariable("i2", i2);

    code = @"def compareValues()
    return $i1 > $i2
    end

    $i1 = i1;
    $i2 = i2;

    comp = compareValues();

    puts comp";

    engine.Execute(code, scope);

    Console.WriteLine("Press any key to continue");
    Console.ReadLine();


  7. Build and run code.

If everything goes well you should see true on screen.


Friday, December 11, 2009

Our Patent

SYSTEM AND METHOD FOR GENERATING CONTROL SYSTEM DATABASE AND GRAPHICS FROM SCHEMA-BASED INTERMEDIATE DESCRIPTIONS
PCT Link (WO 2009/108328 A1 - 03 September 2009) US Patent Link (US 2009/282067 A1 - Nov. 12,2009)

Wednesday, December 02, 2009

Hosting IronRuby in .Net applications - Part1

This post provides necessary information to host IronRuby in .Net applications. I assume no knowledge of Ruby or DLR from reader. It starts with basic introduction to IronRuby and then provides information on DLR and hosting options.

Ruby is a dynamic, open source programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write. IronRuby is a Open Source implementation of the Ruby programming language for .NET, heavily relying on Microsoft's Dynamic Language Runtime.

This is the first part of this series. This part familiarizes the ruby language as much required for this series. For better understanding of ruby language reader can refer to Ruby Programming, IronRuby Documentation, Ruby Learning Tutorial, Ruby Manual.

Getting started

Though prior knowledge of Ruby is an added advantage a novice can still follow this post to get started with Ruby.

Before we can start Download IronRuby 0.9.2 msi. After installing the msi you should find “~\IronRuby 0.9.2\IronRuby Console” in Start –> Programs. This is an interactive console. We can also run a script using “ir.exe <script>”. ir.exe can be found at “<installation path>\IronRuby 0.9.2\bin\ir.exe".

Enter following lines in a notepad and save the file with .rb extension.

ex01.rb

puts 'Hello World'
print "Hello World\n"
puts "Hello World"
puts "Hello World";

Now run this example from command prompt. “ir.exe ex01.rb”. You can test these three lines from interactive console also.

Observations from this example are


  • puts or print either one works to print a message

  • semi-colon at the end of a line is optional

  • Single quote or double quotes, either one works. There is subtle difference between them regarding allowed escape sequences line new line etc.

  • There is no need of main or class to start a hello world program

OK we have just written a ruby script. There is no main/Main here. OK that doesn’t mean we can’t have functions. Let us see them.

ex02.rb

def sayHello
puts 'Hello World'
end

sayHello
sayHello()
sayHello();

Place this code in ex02.rb and run “ir.exe ex02.rb”. All three statements produces same result.

Observations from this example are


  • functions are defined as def and end blocks

  • there is no return type specified. In ruby we don’t specify a return type

  • definitions must be declared prior to calling them

  • all definitions should start with small letter. Though a capital letter as starting character works sometimes, that is not a good practice. Avoid it

  • definition can be called is all three forms. It there are no arguments braces are optional. Again last semi-colon is optional

Fine. Let us pass an argument and get a return parameter.

ex03.rb

def getSQRT(arg)
Math.sqrt(arg)
end

sqrt = getSQRT(ARGV[0]);

puts sqrt

Place this code in ex03.rb and run “ir.exe ex03.rb 4”. Square root of 4, 2.0 is printed on screen.

Observations from this example are

  • command arguments are in ARGV array starting from index zero

  • arguments doesn’t take any type parameter

  • return call is optional. If no return statement is coded, result of last statement is passed as return value

  • sqrt parameter is a local variable, but there is no type specified. It hold return value of getSQRT call

  • Math is a module which is implicitly available. We didn’t write anything line using/import Math

Now let us see how comparison works.

ex04.rb

def compareValues()
return $i1 > $i2
end

$i1 = ARGV[0]
$i2 = ARGV[1]

comp = compareValues();

puts comp

Place this code in ex04.rb and run “ir.exe ex04.rb 2 1”. ‘true’ is printed on screen

Observations from this example are

  • return keyword is specified though it is optional

  • global variables as prefixed with $. This ‘$’ sign specifies that the variable is a global variable.

  • Variable scopes are

    • Local variable : Defined with a block. Starts with lower case letter or ‘_’. ex: var1, _var2

    • Instance variable : Defined within a class (classes are covered later) as a member. Starts with ‘@’ ex: @inst1, @inst2

    • Class variable: These are like static variable in a class. Only one instance is allowed and the same is shared among all objects. Starts with ‘@@’. ex: @@cls1, @@cls2

    • Global variables: These are accessible for all definitions. Starts with ‘$’. eg: $g1, $g2

    • Constants are started with a upper case letter. ex: PI, SpecificGravity

  • There are some commonly used built-ins as mentioned below

    • self - Execution context of the current method

    • nil - Expresses nothing

    • true - Expresses true

    • false – Expresses false. nil also is considered to be false, and every other value is considered to be true

Its time to take big bite.

ex05.rb

class ClassA
attr_accessor :dict

def initialize()
@dict = System::Collections::Generic::Dictionary[String,Object].new
self.dict.Add 'Argument', 12.243
end

def addElements
begin
if @dict['Argument'] == 12.243
@dict.Add 'Key1', 1
self.dict.Add('Key2','TWO')
@dict.Add('Key3', 8.765);
end
rescue StandardError => ste
puts 'StandardError occurred : ' + ste
end
end
end

clsA = ClassA.new

clsA.addElements



for i in clsA.dict.Keys
puts clsA.dict[i]
end

Place this code in ex05.rb and run “ir.exe ex05.rb”. Following results are printed on screen

12.243
1
TWO
8.765

We covered lot of ground here.

Let us start with a small pie

  • Class name to start with a capital letter.
  • attr_accessor creates a get set accessors like properties. We can declare multiple accessors in one statement like
    attr_accessor :dict, :hach, :lict
  • def initialize() is a paramterless constructor

Instance variable

  • As mentioned earlier instance variables are declared with prefix ‘@’. They can be accessed using ‘@’ notation or self.<variable> notation. Observe two lines in constructor and usage of either notation

Using CLR types and object creation

  • CLR types can be used in IronPython with syntax mentioned here.

    Observe minor difference in scope resolution operator ‘::’ and generic template notation with square brackets.

  • Also observe the notation to create objects with <Type>.new method. eg: Dictionary[String,Object].new and ClassA.new

  • We can use all methods of CLR type as is. Observe usage of ‘Keys’ property and ‘Add’ methods

Exception handling

  • ‘begin’, ‘rescue’, and ‘else’ sequences are exception handling blocks. Exceptions are raised using ‘raise’ keyword

  • rescue is like catch while raise is like throw. => operator provides a reference to current exception into the variable on right side.

  • there is option of else to catch all other exceptions

    begin
    raise 'Error occured'
    rescue Exception1 => ex1
    rescue Exception2 => ex2
    else
    Other exceptions
    end

for loop

  • Here for loop is used with iterator.
  • There is no need to specify type for iteration variable. eg. for i in clsA.dict.Keys

There is so much in it. Now let us see what ruby offers for delegation of control

ex06.rb

def AuthenticateUser(l)
if l.call('ruby', 'gem')
puts 'Authentication Successful'
else
puts 'Authentication Failed'
end
end

#Function pointer
fp = proc { |username, password|
if username == 'ruby' && password == 'gem'
return true
end
}

AuthenticateUser(fp)

#Method pointer
class Authenticate
def initialize(username, password)
@username = username
@password = password
end
def validateCredentials(username, password)
if username == @username && password == @password
return true
end
end
end

a = Authenticate.new('ruby','gem')

mp = a.method( :validateCredentials )

AuthenticateUser(mp)

Place this code in ex06.rb and run “ir.exe ex06.rb”. Two ‘Authentication Successful’ messages are printed on screen.

Here Authenticate method takes a delegate as argument. This argument is a pointer to a routine on which method can invoke a call. Above code demonstrates passing the routine as function pointer and method pointer within a class.

Observations from this example are

  • Invocation of a routine is done with .call method
  • Function pointers are obtained using ‘proc’ keyword. It can be done using keyword ‘lambda’ also. There is a subtle difference between them regarding invocation context. More details can be found at link
  • The usage within | | is arguments for routine being called followed by implementation using these arguments. It is like anonymous method in C#
  • To get the reference to a method within a class we use ‘.method’ function.

Some more examples in Part-2. And then part-3, I will cover about integrating ruby scripting feature in .Net applications.

Saturday, November 21, 2009

TIOBE Programming Community Index for November 2009

Check TIOBE index for 2009.

I guess this year C will be declared as programming language of the year. And with GO in league we know some dynamics will change by next year.

What I am interested to know what is driving PHP so strong. And between Python and Ruby, ruby is picking up.

Thursday, November 19, 2009

Its 5 years of blogging

I started blogging since 12 Nov 2004. Probably this is the only hobby that I liked so much for so long. Ofcourse after starting twitter mainstream blogging is reduced.
Anyway it gave me so much pleasure in last 5 years and keeping me motivated to persue it further.

Tuesday, November 03, 2009

Just installed VS2010 Beta2

Just installed VS2010 Beta2.

Though the general layout is not new, editor is not looking a bit sluggish. Personally I am impressed with emphasis given UML. But couldn’t understand what is that InstallShield 2010 doing in VS2010 rather I was expecting WIX there.

Yet to explore UML support completely. But first look is OK. It looks like there is way to generate code using extensions. I am still going to through the articles and yet to get a hang it. But I am amused to know the fact that MEF is playing a key role here.

Also I am liking Architecture views, especially the dependency (directed) graph by class and its analyzer features to check circular, hub and unreferenced nodes.

But I am not sure, what are improvements on metrics. I don’t see any changes.

And coming back to XML. New viewer is somewhat OK but I am really missing what we had in VS2005.