Friday, October 17, 2014

MVVM PasswordBox, SecurePassword and SecureString


PasswordBox implementation using MVVM is one of the widly debated topic around MVVM arena. Problem statement is how to bind Password property of PasswordBox to a property in a ViewModel. This problem stems from the fact that Password property of the PasswordBox is not a dependency property for obvious security reasons, hence we cant bind it as we would normally do.


Now there are many solutions and workarounds like having event in ViewModel that is registerd in view and acts as the password catcher, passing whole PasswordBox to ViewModel in command paramter of login button Command, having content control binding to the property in ViewModel of type PasswordBox, handling password change in code behind and creating PasswordBoxHelper attached behaviour etc.

You can find the discussion and solutions in below thread :-

http://stackoverflow.com/questions/1483892/how-to-bind-to-a-passwordbox-in-mvvm

What I found well suited in accordance with the MVVM implementation is having attached property extend the PasswordBox and provide much needed dependency property for binding. Below is sample of PasswordHelper class that extends the PasswordBox and provide dependency property BindablePassword for binding.

Sample is based on below blog post

http://blog.functionalfun.net/2008/06/wpf-passwordbox-and-data-binding.html

I have modified the PasswordHelper class to incorporate following :-

1) Implementation of SecureString type for dependency property instead of String.

2) Binding SecureString type property from ViewModel to PasswordBox's SecurePassword property instead of Password property.

3) Utility method to convert from SecureString to String and vice versa.

These all have been implemented to tackle the security issues with implementing dependency property as String. Which I will shortly demonstrate.

PasswordHelper
public static class PasswordHelper
{

public static readonly DependencyProperty BindablePasswordProperty =
DependencyProperty.RegisterAttached("BindablePassword",
typeof(SecureString), typeof(PasswordHelper),
new FrameworkPropertyMetadata(string.Empty, OnPasswordPropertyChanged));

public static readonly DependencyProperty BindPasswordProperty =
DependencyProperty.RegisterAttached("BindPassword",
typeof(bool), typeof(PasswordHelper), new PropertyMetadata(false, BindPassword));

private static readonly DependencyProperty UpdatingPasswordProperty =
DependencyProperty.RegisterAttached("UpdatingPassword", typeof(bool),
typeof(PasswordHelper));

public static void SetBindPassword(DependencyObject dp, bool value)
{
     dp.SetValue(BindPasswordProperty, value);
}

public static bool GetBindPassword(DependencyObject dp)
{
      return (bool)dp.GetValue(BindPasswordProperty);
}

public static string GetBindablePassword(DependencyObject dp)
{
      return (string)dp.GetValue(BindablePasswordProperty);
}

public static void SetBindablePassword(DependencyObject dp, SecureString value)
{
      dp.SetValue(BindablePasswordProperty, value);
}

private static bool GetUpdatingPassword(DependencyObject dp)
{
      return (bool)dp.GetValue(UpdatingPasswordProperty);
}

private static void SetUpdatingPassword(DependencyObject dp, bool value)
{
      dp.SetValue(UpdatingPasswordProperty, value);
}

private static void OnPasswordPropertyChanged(DependencyObject sender,
DependencyPropertyChangedEventArgs e)
{
     PasswordBox passwordBox = sender as PasswordBox;
     passwordBox.PasswordChanged -= PasswordChanged;
     if (!(bool)GetUpdatingPassword(passwordBox))
    {
         passwordBox.Password = (string)e.NewValue;
    }
    passwordBox.PasswordChanged += PasswordChanged;
}

private static void BindPassword(DependencyObject sender,
DependencyPropertyChangedEventArgs e)
{
     PasswordBox passwordBox = sender as PasswordBox;
     if (passwordBox == null)
           return;
     if ((bool)e.OldValue)
    {
        passwordBox.PasswordChanged -= PasswordChanged;
     }
     if ((bool)e.NewValue)
    {
        passwordBox.PasswordChanged += PasswordChanged;
    }
}

private static void PasswordChanged(object sender, RoutedEventArgs e)
{
    PasswordBox passwordBox = sender as PasswordBox;
    SetUpdatingPassword(passwordBox, true);
    SetBindablePassword(passwordBox, passwordBox.SecurePassword);
    SetUpdatingPassword(passwordBox, false);
}
}

View Model

public class MainWindowViewModel

{
   SecureString networkPassword;
   public SecureString NetworkPassword
   {
      get
      {
          return networkPassword;
      }
      set
     {
          networkPassword = value;
      }
}

public MainWindowViewModel()
{
     //Just for demo
     NetworkPassword = SecureStringUtility.ConvertToSecureString("SomeString");
}
}

View

<xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:PBinding"
Title="MainWindow" Height="350" Width="525">

  
       
<  local:PasswordHelper.Password="{Binding Path=NetworkPassword, Mode=TwoWay,      

      UpdateSourceTrigger=PropertyChanged}"
      Height="80"
      Margin="2" />
  


  Sample is simple containing window with PasswordBox control, a ViewModel with single property NetworkPassword to bind to PasswordBox, PasswordHelper class to extend PasswordBox and Utility methods to convert from SecureString to String and vice versa.

Let come to the reason for implementing SecureString in PasswordHelper class. If we go by the orignal sample PasswordAssistant class from above blog which is implementing String as dependency property, we would get into some security risk as below screenshot shows. Password can be easily reterived using WPF sniffer tool like Snoop which I have used.


So as we can see Password in password field of PasswordAssistant class is easily visible if Dependency Property is of Type String in PasswordAssistant class.

Now below is the screen shot of same application using PasswordHelper class with SecureString implementation.



SecureString is type from System.Security namespace and PasswordBox in WPF also contains property SecurePassword along with Password property. These both properties are not Dependency properties so can't be used in binding. For that reason we have to come up with Attached dependency property for PasswordBox with with we can bind our ViewModel's property. Now property in ViewModel should also be SecureString type as we have to bind it with SecureString type dependency property.

So in our application,Password remains as secure string and can be converted from Secure string to string and vice versa wherever needed. This can be done using utility methods ConvertToUnsecureString and ConvertToSecureString.

public static string ConvertToUnsecureString(SecureString securePassword)
{
    if (securePassword == null)
    throw new ArgumentNullException("securePassword");
    IntPtr unmanagedString = IntPtr.Zero;
    try
   {
     unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(securePassword);
     return Marshal.PtrToStringUni(unmanagedString);
    }
    finally
   {
       Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
   }
}

public static SecureString ConvertToSecureString( string password)
{
    if (password == null)
    throw new ArgumentNullException("password");
    unsafe
   {
      fixed (char* passwordChars = password)
      {
          var securePassword = new SecureString(passwordChars, password.Length);
          securePassword.MakeReadOnly();
          return securePassword;
      }
}

These methods proper implementation has been taken from the blog :-
http://blogs.msdn.com/b/fpintos/archive/2009/06/12/how-to-properly-convert-securestring-to-string.aspx

We have just modified the PasswordHelper class to provide secure and proper MVVM based implementation for PasswordBox. Hope it will be helpful.

Sunday, October 12, 2014

Visual Studio Team Foundation Server (Visual Studio Online )

These are very exiting times and a lot of things are going around technologies and businesses. The competitive market is demanding continuous, improved, innovative and affordable products. There is race among companies to introduce next big thing in there respective arenas. Need for continuous release of products in market to get early feedback and rapid prototyping, demands tools and processes that will facilitate rapid development, resourcefulness, optimized cost and better project tracking.

This led me to explore Visual Studio Team Foundation Server (Visual Studio Online) for complete Application Life cycle Management (ALM) solution. Experience was quite good with my setup of Visual Studio 2014 CTP and Visual Studio Online.

Here is the snapshot of Visual Studio 2012 team explorer that integrates with Visual Studio Online portal for our team project. There are options to choose Version control system for code repository from : VS TFS and Git


We can easily navigate to Visual Studio Online to get the project stats. Below is the home screen for portal.

Here on portal you can see link Home, Code, Work , Build and Test. These are the base categories which are fully configurable to individual project requirements. On home screen we can find various options for :-
1) Managing Team members
2) Managing Work areas
3) Creating Schedules and iterations.
4) Managing Backlogs and sprints.
5) Kanban Boards
5) Team Boards etc

Once code has been uploaded to repository on TFS or GIT here is view under code menu.



From home screen we can configure our Sprints and schedules, below are screenshots from sample project:-





Once we have planned our sprints, we can manage backlogs, assign work items and track sprints.



An intuitive interface to manage all the project activities.
Automated build process and testing, these are the areas which I still need to explore, but overall a good experience so far. Will keep on posting about further exploration.

http://msdn.microsoft.com/en-us/library/dd286521.aspx

Sunday, September 25, 2011

Java api in .Net (JavaIntrop)

In my previous blog I have said something about using a java library in .Net . My case demanded me to use a java library in .Net . Many times we find  a decent and clean library to use but its a java library and some time we find a java library that is impossible to ignore , in that case we hope for a way to use java api in .Net . I roamed the net and tried the fit and that fit happened to fit my case.  That is IKVM.Net by Jeroen Frijters .

http://www.ikvm.net/index.html

IKVM.net is a open source  java implementation , that comes with the OpenJdk  implementation  in .Net and various tools to interop between  java and .Net  . Whole JVM is implemented in  .Net and its very easy to convert java jar files to .Net assemblies and .Net assemblies to java  jars (interface and stub classes ).

Taking on my case to convert java jar files to .Net assemblies , there comes a command line utility with IKVM called ikvmc.exe . To generate the .Net assembly for a jar file we first specify the command line switch [-target:library] for generating  a dll .  Without this command line switch ikvmc.exe will generate a exe for a jar file if it encounters a main method in a class.  On command prompt we change directory to IKVM binaries folder and specify command :

C:\IKVM>ikvmc.exe –target:library  hapi-base-1.2.jar

The jar file is in same directory as ikvm binaries , this will generate the hapi-base-1.2.dll . There will be many warnings by ikvmc.exe of noclassdeffound  , this is because we haven’t specified the dependency dll’s. IKVM comes with the OpenJdk implementation in .Net and they are in form of dll’s. Now we have to specify the OpenJdk dll’s that our jar file depends upon to rectify the warnings.

C:\IKVM>ikvmc.exe –target:library  hapi-base-1.2.jar –reference:IKVM.OpenJDK.Core.dll  -reference:IKVM.OpenJDK.Util.dll

In example I have only referenced some of OpenJdk dll’s , but we have to reference all the dll’s that our jar file depends upon.  Upon completion of the command a hapi-base-1.2.dll will be generated . Now moving on to next jar file (hapi-structures-v21-1.2.jar).

C:\IKVM>ikvmc.exe –target:library  hapi-structures-v21-1.2.jar –reference:IKVM.OpenJDK.Core.dll  -reference:IKVM.OpenJDK.Util.dll

As this new jar file have dependency on previous jar file , we have to reference the dll of previous jar file to make a successful porting of this jar file to a dll.

C:\IKVM>ikvmc.exe –target:library  hapi-structures-v21-1.2.jar –reference:hapi-base-1.2.dll  –reference:IKVM.OpenJDK.Core.dll  -reference:IKVM.OpenJDK.Util.dll

And so on we can create dll’s from jar files resolving the dependency using the [-reference:<dllname>] .Now these dll’s are ready to be used in your .Net project . We have to at least add reference of IKVM.Runtime.dll in our project and other OpenJdk dll’s that out converted jar dll’s depend upon.  Keep on porting .

Friday, September 23, 2011

Health Standard 7 (HL7) Development - C#

Getting into the development of  HL7 system , there are not many free libraries on net to start with.  HL7 being the standard way to talk between various components in a modern medical infrastructure is a way too old format to work with (except with new xml based HL7 3.0).  This lend to the complexity while dealing with the HL7 development. 

HL7 messages is a flat text with standard specifying the format of the message. HL7 message is divided into segments to hold the medical record information of various types (ex patient details, insurance details,patient visit etc). These segments are separated by carriage returns. 

MSH|^~\&|DDTEK LAB|ELAB-1|DDTEK OE|BLDG14|200502150930||ORU^R01^ORU_R01|CTRL-9876|P|2.4 CR 
PID|||010-11-1111||Estherhaus^Eva^E^^^^L|Smith|19720520|F|||256 Sherwood Forest CR
EVN|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||CR OBR|1|948642^DDTEK OE|917363^DDTEK LAB|1554-5^GLUCOSE|||200502150730||||||||| CR

Segments  are  divided into fields separated by the pipe (|) and further fields are divided into   components and subcomponents separated  by  “ ^ “ .  There has been many versions of HL7 standards with several updates and new additions, primarily we can deduct most important versions to be  2.1,  2.3,  2.4,  2.5,  2.6  (2.x version) . Out of which 2.5 is most widely used and  stable version . Version  3.0 of  HL7 is a move to shift from flat file base to new xml based HL7 standard format,  but it is not yet that much accepted in common use.

Now coming on to the development of HL7 standard from the view point of .Net developer, what many option do we really have ?.  Having good knowledge of what to implement is easy as there are many resources available to make our self familiar with nitty-gritty of HL7 standard  , but having the tools to implement HL7 is another matter.  There is support from Microsoft on HL7 in form of BizTalk Accelerator for HL7 ( http://www.microsoft.com/biztalk/en/us/accelerator-hl7.aspx )   , but as you guessed its not free  . Second option is to write a new library to deal with HL7, but its not a trivial task , as HL7 standard is divided into various versions and industry implement all these versions to certain degree . Another option is to write only specific demand based api for HL7 , targeting a single module or implementation of certain feature of HL7, but that's also not a very good solution as what happens when that specific api expands to accommodate multiple version of HL7. Why to reinvent the wheel , there should be some thing on web that targets the HL7 development in  .Net.  

Two top notch free solution for HL7 development are Hapi and NHapi . Hapi is open source extensive  java library   to deal with almost all the versions and angles of HL7 development.  Nhapi is  .Net implementation of the Hapi project.

Hapi:-  http://hl7api.sourceforge.net/

NHapi:- http://nhapi.sourceforge.net/home.php

So we do have .Net open source library for HL7 development . NHapi supports versions from 2.1  to  2.5 and will suffice for most of HL7 related development.  API’s are simple and easy to use . It creates a Object model for a HL7 message being parsed and can convert that into HL7 standard xml for easy use or for transformation via xslt. Using the HL7 message object model we can do variety of things related to the HL7 parsing and creation. 

Downside is that Nhapi is not as extensive as Hapi (Java library).    HL7 message validation is not there except for some low level validation (e.g  MSH segment validation , primitive validation etc ) . HL7 communication module is not there . Support up to 2.5 version of HL7 as comparison to  Hapi support up to 2.6 version . Most important of all there has been no activity recorded for Nhapi for some time and it makes future dependence on Nhapi a little scary (although its a open source and anybody is invited to contribute and extend ). 

Hapi is on the top list when it comes to the HL7 library , they recently released  Hapi 1.2 in June and forums are abuzz with discussions . Support for 2.6 is included and future support for HL7 3.0 and more are anticipated. HL7 message validation is very mature and there is good support for HL7 message communication .

So the question is how we,  .Net developers can leverage Hapi project and use it in our .Net applications . The answer can be  in using   java in [ .Net] ,  is it possible ? . Yes we can use java libraries in [.Net] , as they are [.Net] libraries and can use  full feature of  Hapi project.

Java interop tool developed  Jeroen Frijters (who is contributed for bringing  J# to its demise)  is the best and easy bet to use Hapi java api in .Net . I have done it and it works great . I will be soon writing on how to convert java jar files to .Net assemblies.

Technorati Tags:

Friday, July 15, 2011

Microsoft Extensibility ( MEF 4.0) :-

Writing an extensible application is always a challenge , considering the incorporation of future functionalities that are not known at the time of designing application architecture.  Extensible application basically consists of the core framework that has to remain unchanged and work as the base engine for application , extending the application at runtime.

One very good example of extensible application can be seen in design architecture of the Sharp-develop  IDE.  I have previously blogged about the Sharp-develop and its design . Sharp-develop application consists of base engine -SharpDevelop.Core ,  which is the responsible for loading up all the add-ins and extending the application at runtime.  

SharpDevelop uses add-in based extensibility . Microsoft has always provided the extensibility framework to design our application upon . Add-in based framework such as Add-in pipeline framework let us to create a host application and expose its Object model to be extended by the application addins . There is well defined architecture for this kind of application development  consisting of Host,  Hostadpter, Addinadpater, Addin . You can look my previous blogs on add-in pipeline development for detail into architecture. One good example of application that follows the Add-in pipeline development is VSTA  (Visual studio tools for application) which uses the addin framework provided in System.Addin and its sister namespaces. Details for VSTA can also be found in my previous blog entries.

The new child on the block in the arena of extensibility from Microsoft is MEF (Microsoft Extensibility Framework). It is projected as the extensible framework and also have the capability of DI (Dependency Injection) as Unity framework. While Unity framework is DI framework , MEF work as extensibility framework along with DI capabilities . For detail in to MEF programming you can check my previous blog entries .

I have my share of experience  of developing application using MEF .  Although MEF acts great whereas its DI capabilities and functionalities are concerned , but lack of support for standard publish/subscribe mechanism and modularity functionalities within the framework itself  is somehow concerning.  We have to use MEF extensions provided within PRISM library to fully achieve extensibility features.  PRISM with MEF is great , where we have to develop an extensible UI based application . It provides us with standard publish/subscribe mechanism which is loosely coupled with in the application and uses weak references for events. Then we have Modularity in form of IModule which help us to get a extensible UI based application. There are all other great  features of PRISM , but if we can get the above said features right in MEF it will  greatly ease the development of application which is not UI based .

Hopefully I will write some details upon MEF extension within PRISM 4.0 .

Friday, March 4, 2011

C# :- Imaging ( AForge.net )

If you are doing some image processing there is an interesting and cool open source project called AForge.net .  It contains many routines and filters for image processing.  I started playing with Glyph’s Recognition,  glyph’s recognition engine is provided by AForge Framework.   There is  GRATF  (Glyph Recognition and Tracking Framework)  project  based upon  AForge framework.  GRATF framework mainly deals with the Glyph recognition algorithm and glyph tracking  , utilizing the AForge.Net  image processing library. 

To  get started with Glyph recognition , download the GRATF source code from source code repository at Google :-

http://code.google.com/p/gratf/downloads/list 

After downloading the source  you can start exploring the  code. There is an application that comes with download called Glyph’s Recognition Studio.  It lets you to specify the particular glyph to be recognized and also support 2d augmentation , that lets you to place a particular image over the recognized glyph.   Implementation and description of the glyph recognition algorithm is described at :-  http://www.aforgenet.com/articles/glyph_recognition/.

Glyph to be recognised is created on a white paper with outermost white border , then black border with glyph inside.

Glyph’s recognition make use of various image filters from the AForge Framework. It starts all with the bitmap to be processed , its the managed bitmap captured from the source . Bitmap image is converted into Unmanaged image using the UnmanagedImage class of AForge.Imaging namespace.  UnmanagedImage class takes the BitmapData as a parameter in its constructor and converts the Bitmap image into unmanaged image. With unmanaged image we do not have to lock image bits before processing the image pixels , as with managed bitmap image , so overhead of locking and unlocking bitmap is avoided

BitmapData bitmapData = image.LockBits( new Rectangle( 0, 0, image.Width, image.Height ),
                ImageLockMode.ReadOnly, image.PixelFormat );

UnmanagedImage unmanagedImg = new UnmanagedImage( bitmapData ) ;

With our unmanaged image , first step is to apply the GrayScale filter to unmanaged image . GrayScale filter processes the image pixels and returns only the pixels within gray range from 0 to 1 . Gray range is from complete white to black and varied gray component in-between . As we are only concerned with the intensity of the pixels, so we discard the colour information  by applying the GrayScale filter of AForge framework.

UnmanagedImage grayImage = UnmanagedImage.Create( image.Width, image.Height, PixelFormat.Format8bppIndexed );
Grayscale.CommonAlgorithms.BT709.Apply( image, grayImage );

After we have reduced the image with only gray intensity pixels, we apply DifferenceEdgeDetector filter on the grayscale image to detect the edges in the image .

DifferenceEdgeDetector edgeDetector = new DifferenceEdgeDetector();
           UnmanagedImage edgesImage = edgeDetector.Apply(grayImage);

Then we apply Threshold filter to the image to convert gray range pixels into  black or white pixels using the threshold value taken as constructor parameter by Threshold filter.

Threshold thresholdFilter = new Threshold(40);
           thresholdFilter.ApplyInPlace(edgesImage);

We use BlobCounter class to get all the detected blobs in the image of particular size and width.

BlobCounter blobCounter = new BlobCounter();
          blobCounter.MinHeight = 48;
          blobCounter.MinWidth = 48;

blobCounter.ProcessImage(edgesImage);
           Blob[] blobs = blobCounter.GetObjectsInformation();

We iterate over all the blobs detected and use SimpleShapeChecker to check if the blob is of a particular shape.

List<IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]);
List<IntPoint> corners = null;

if (shapeChecker.IsQuadrilateral(edgePoints, out corners))
              

After passing the IsQuadrilateral check of SimpleShapeChecker we calculate the average brightness of the pixels from both the sides of the edges of Quadrilateral . If the average brightness exceeds a predefined value we further process to get the glyph value.  We apply QuadrilateralTransformation filter on the corners of the Quadrilateral and get the rectangle image of the glyph.

Once we have the rectangle image of the glyph we can iterate over all the pixels of the image using the UnmanagedImage pixel byte pointer and calculate the intensity of the pixels for the each cell of the image and then checking it with the glyph database for glyph recognition.

http://www.aforgenet.com/projects/gratf/

http://www.aforgenet.com/projects/gratf/code_samples.html

Wednesday, March 2, 2011

Silverlight Video Streaming and IIS Smooth streaming

Previously , I have written a blog about the WCF streaming  (here) .  I have got many responses on this blog entry and now I will further explore the streaming with Silverlight streaming and the IIS smooth streaming .

Silverlight streaming make use of Microsoft Expression encoder to package the media content with a silverlight media template . Microsoft Expression encoder is the application which comes with the expression suit applications from Microsoft.  It lets you to adjust the bitrates and resolution of your media content and package it along with the silverlight media template to play it in. Microsoft expression encoder lets you to publish the media content to the silverlight services and azure cloud.

We can download the expression encoder from here download encoder . Hosting of media contents with silverlight services has been discontinued as it was in beta phase. Now we have option of hosting our media content on Azure.

These are the some links to get started with the silverlight streaming and azure media hosting using Microsoft Expression Encoder .

Silverlight Services hosting (Discontinued)

Hosting videos on Azure

Apart for hosting our media on the Azure cloud , we can host the media on our web server and take the benefit of the  IIS Smooth streaming feature .  Here are some links that will get you started with configuring and using IIS Smooth streaming.

Getting started :- IIS Smooth streaming

IIS Smooth streaming sample application

Installing and configuring IIS Smooth streaming

Smooth Streaming fundamental

There are many possibilities to build the media content delivery system on top of these streaming choices.                          Happy streaming…..

Saturday, February 19, 2011

C# :- GetHashCode() : HashTable and Dictionary

In C# when coming to data structures  HashTable and Dictionary provide us with the ability to search for the element in them based on the data rather that the index .  Arrays are stored contiguous in memory and to access the item in array there is constant asymptotic runtime  O(1)  , because we only have to know the index of the value to be retrieved. Searching through an unsorted  array has linear runtime of   O(n) and through sorted array of O(log n).  Array are useful when we have to directly access the value based on ordinal value.  But when dealing with complex data we do rarely use the index based  approach for accessing and searching items.

We are more concerned on accessing and searching items based upon real information in a data set ,  that can be anything from enrolment no’s  , credit card  no’s or complex alphanumeric sequences.  Here comes the HashTable and Dictionary , these data structure allows us to use our complex data information for indexing . To do so these structure uses hashing function to compress our complex  indexer to a reasonable space limit  and  optimal  asymptotic runtime.

Hashing function simply compresses the indexer we are using , so that a optimal set of indexer can be created  from original indexer.  If we would have to use our original complex indexer then we would have to accommodate all the values of indexer , which would be very large set of indexers to maintain relatively small set of values.  So, hashing function is the mapping from the original set of indexer to the compressed and optimal set of the indexer.

But hash values generated by the hashing function is not unique.  So we have multiple original indexers values having same compressed or hashed indexer value. This is known as hashing collisions. Collision avoidance primarily depends upon the implementation of hash function  algorithm . There are different collision resolution strategy , among them are Linear Probing and Quadratic probing. 

In linear probing  , we create the hash and place the value at the hashed indexer, but if we find that there is already a value allocated to the indexer (as same hashed indexer could have been generated previously by hash function)  , we simply move on to next indexer (i + 1 ….   i +n)  until we find an empty indexer slot.  In Quadratic probing we use same method as linear probing but when a indexer is encountered having the some value we move on to (i + 1^2), if it is also occupied we look at  (i-1^2)  indexer and keep on looking till we find a empty indexer slot in pattern  (i + 2^2), (i -2^2) …. (i + n^2), (i-n^2) .

HashTable and Dictionary uses different collision resolution techniques called rehashing and chaining . In .Net the HashTable contains the method GetHashCode()  that is inherited from Object class , which is responsible for creating a unique integer value .  GetHashCode() method generate unique integer for any value whether its string or any other type ,  as all types are derived from Object class. This hashcode is used as indexer to allocate a slot for coming values.

HashTable also contains a property LoadFactor that is ratio of total number of items in hashtable to  total number of available slots. Optimal loadfactor as stated by .Net is  0.72 .  So whenever we push a new item into hashtable,  .Net checks to see that loadfactor is not exceeded . In hashtable hash values are calculated based upon the loadfactor , so for a insertion of a value , hash table is rehashed to maintain the loadfactor.

Dictionary is strongly type as it uses generics in comparison to HashTable and it also uses different collision resolution technique known  as chaining . In dictionary a separate data structure is used to hold  the conflicting mapping.

As we have seen in Linear and Quadratic probing that we use a pattern to probe for next available slot for value , but in dictionary a data structure is maintained at the conflicting hashed indexer to hold all the values at that indexer. So we have same hashed indexer for different values in a data strcuture / linked list .  As the accessing and searching in HashTable and Dictionary does not depend upon the number of items due to loadfactor, the  asymptotic runtime  is         O(1) as compared to O(n) in arrays, which is fast.  

http://msdn.microsoft.com/en-in/vcsharp/default.aspx?pull=/library/en-us/dv_vstechart/html/datastructures_guide.asp

http://msdn.microsoft.com/en-us/library/ms379571(VS.80).aspx

Monday, January 31, 2011

Microsoft Help Viewer 1.0 or MS Help 3.0 :- VS 2010

Along with Visual Studio 2010 , we have new help system from Microsoft .  Previously there was Document explorer based help system  known as MS Help 2.x ,  now we have new browser based help system known as Microsoft Help Viewer 1.0  or MS Help 3.x . Starting with VS 2010 we will get our help documentation  in browser instead of Document Explorer window.  Integration of  our own library documentation with MS Help 3.0 has changed from previous process of MS Help 2.0 where we have to register our collection with help system.

Targeting  MS Help System 3.0  requires generating help files in Help 3.0 format ( i.e  .msha, .mshi, .mshc ) . To generate help documentation from source code commenting we have excellent tool called Sandcastle help file builder. Sandcastle support varied help document formats and MS Help 2.0 & MS Help 3.0 are among the generated help documentation formats.  Sandcastle is available at codeplex  : -- http://shfb.codeplex.com/ . We can provide project or solution file to Sandcastle for help documentation generation from source code commenting in MS 2.0 or MS 3.0 format.

After our help files are generated  we have .mshc (help container file), .mshi (index file), .msha (product manifest file)  as help files.  If  you already have help documentation in MS Help 2.0 format , you can use mshcmigrate tool to convert MS Help 2.0 files to new MS Help3.0 files instead of  using sandcastle .   Mshcmigrate tool can be found at :- http://mshcmigrate.helpmvp.com/home#TOC-Download

Now we have our help files in place , the only thing that is left is to integrate our help documentation with MS Help system 3.0 .  New Microsoft Help System or MS Help Viewer 1.0 is not a standalone product and is only installed along with VS2010 or Windows 7 sdk.  New help system comprises of  two services Help Library Manager and Help Library Agent.  Help Library Manager is the application that we are going to use for our help documentation installation.

To launch the help library manager application we go to All Programs –> Microsoft Visual Studio 2010 –> Visual Studio Tools-> Help Library Settings.

This will launch help library manager that will ask for the location of local help content store if not already configured. Next step is to navigate to our .msha file through Help Library Manager and select the .msha file for installation.  Help library Manager gives us the option of installing , removing and updating help contents.

In new help system ,  Help Library Agent is the service responsible for opening the help document urls in browser .  As new help is browser based so we have new url protocol to open the  Help 3.0 document pages . This protocol ms-help:// is associated with Help Library Agent. So we used Help Library Manager to install our library help in local help store. We can access our help documentation using the VS studio help menu , which shows all the help content installed or we can use the H3Viewer utility to access and see our help documentation . H3Viewer utility can be found at :---------http://mshcmigrate.helpmvp.com/viewer . 

Now if we are installing our custom help 3.0 files through installer , we can  use Help Library Manager exe with some command line parameters . For installing the help files silently using  Help Library Manager, without showing the dialog for installation option , we have to package our help content into a cab files  and then digitally sign it. We can use makecab tool and create digital certificate to sign out cab file using  signtool utility.

http://helpware.net/mshelp3/intro.htm

http://visualstudiogallery.msdn.microsoft.com/6a1211d5-1be9-4768-92a8-aa8af2c8cba4/

Wednesday, December 8, 2010

C# 4.0

I have been working with C# for almost  4 years straight , not all but I have seen some awesome changes in C#, from  being  a statically bound language to Dynamic one.  C# evolved as it accumulated features of different  programming disciplines .

Generics,  Closures , anonymous delegates, var  (Type-inference),  Eval and  Yield  keywords  , Lamda Expression, Dynamic keyword  :-  all these features adopted from functional or dynamic disciplines of programming languages. There are numerous threads on internet discussing object oriented, functional and dynamic nature of C#.

But how C# got so far ,  can be better understood by examining the nature of  the language  that is :-  Multi-Paradigm Design. 

While wandering over net I stumbled upon some great blogs from Ted Neward, you can check them out at following links : --  

http://msdn.microsoft.com/en-us/magazine/ff955611.aspx

http://msdn.microsoft.com/en-in/magazine/gg232770(en-us).aspx

http://msdn.microsoft.com/en-in/magazine/gg309185(en-us).aspx

http://msdn.microsoft.com/en-in/magazine/gg490357(en-us).aspx

Enjoy reading …

Saturday, November 27, 2010

NDepend :- Part II

Quite from some time I was thinking about using NDepend to check my code with the yardstick of standard metrics . I finally got free and started to dig , how I can use NDepend to catch loose points in the code ?  NDepend analysis is the process of capturing all the information from the code that can be used as a metrics for measuring and calculating the quality and stability of the code.

Metrics has always been used in other sciences as a measure of the property of some tangible element. But in software development process, where software as an outcome is considered intangible , applying metrics and deducting the meaning out of them has been subject to open discussion. But with advance in the process of software development , many standard and time tested metrics has been setup. NDepend is based on these standard metrics. Tool provides the way to capture the information and present us with the detailed report of all these metrics.

So to utilize the NDepend to its full potential , we have to look at two core component of NDepend , NDepend metrics and CQL. Starting with metrics,  NDepend provides the list of all the metrics it uses and also the values for metrics that should be considered as standard for good quality code (http://www.ndepend.com/Metrics.aspx ). NDepend's metrics page also provides some links to the patrick smacchia blogs at codebetter.com, that can helps us to understand the usefulness and relevance of the code metrics in relation to code analysis.  Some of the links that you might want to check out are :-

http://codebetter.com/blogs/patricksmacchia/archive/2007/10/05/why-is-it-useful-to-count-the-number-of-lines-of-code-loc.aspx

http://codebetter.com/blogs/patricksmacchia/archive/2008/02/15/code-metrics-on-coupling-dead-code-design-flaws-and-re-engineering.aspx

http://codebetter.com/blogs/patricksmacchia/archive/2008/03/07/a-simple-trick-to-code-better-and-to-increase-testability.aspx

After understanding one of key component of NDepend ,  NDepend’s metrics. We now can move forward to other core component CQL (Code Query Language). CQL is easy to use query language , used in NDepend .It is similar to SQL and we can easily write intuitive queries . CQL works on metrics and code structure of .Net application and fetches the result for the query. NDepend constraints are based on the CQL and checks for any violation.

CQL is one of my favourite feature of NDepend , as it is similar to SQL so it is easy for me or any developer to write queries against the .Net code structure and metrics. We can easily write a query to find out all the methods in particular namespace where the no of lines of code or IL code is greater than 250 and then can factor out these big methods in small ones .

Ex:-

WARN IF Count > 0 IN SELECT METHODS OUT OF NAMESPACES "MyNameSpace.GUI"  WHERE NbILInstructions > 200

CQL editor of NDepend provides intellisense for query writing and we can turn our CQL queries into constraints and check for any violation with successive builds.  To see the power of CQL and various samples,  you can check out this link:- 

http://www.ndepend.com/CQL.htm

NDepend also presents a visual layout of analysis as Dependency Graph and Dependency Matrix , we can use these visual tools to see entire picture of our codebase and its composition with perspective of metrics.

But with knowledge of software metrics and instrument as CQL we can explore and have control over the process of software development to achieve high quality code.

I am still new to NDepend and feeling like I have just discovered the tip of iceberg.

Tuesday, November 23, 2010

C.L.R :- .NET Debugging

If you ever get curious enough to know how .Net debugging works,  there is an excellent source of knowledge :-                     http://blogs.msdn.com/b/jmstall/.

I got curious and found excellent posts from the insider Mike Stall , one of previous team member of Microsoft Managed Debugging Team. My curiosity lead me to  unmanaged api ICorDebug  (COM api). Next I was in search of managed wrapper around the CorDebug.idl, my search lead me to Managed Stack Explorer, a command line managed debugging tool . You can get your hands on source code at  http://mse.codeplex.com/.  Once you get hold of code, you get all the managed wrappers (C#) around the COM api of ICorDebug . Wrappers are manually created using ComImport   attributes in C# , so you do not have to go through laborious process of creating each and every wrapper around classes, interfaces and structures.  Apart from manually created wrappers , you also get p-invoke methods from mscoree.dll within the source code:--

[DllImport("mscoree.dll", CharSet=CharSet.Unicode, PreserveSig=false)]
public static extern Debugger.Interop.CorDebug.ICorDebug CreateDebuggingInterfaceFromVersion(int debuggerVersion, string debuggeeVersion);

[DllImport("mscoree.dll", CharSet=CharSet.Unicode)]
public static extern int GetCORVersion([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder szName, Int32 cchBuffer, out Int32 dwLength);

These dll-import method gets the current ICorDebug version and creates the ICorDebug interface which is encapsulated within the ICorDebug managed wrappers.  You have to call Initialize() and SetManagedHandler()  on the ICorDebug managed wrapper , to initialize the ICorDebug interface and set the managed call-back interface for all the call-backs returned from the ICorDebug interface.  ICorDebugManagedCallback interface is also the wrapper around the com interface.

ICorDebug rawDebuggingAPI;
          rawDebuggingAPI = NativeMethods.CreateDebuggingInterfaceFromVersion((int)CorDebuggerVersion,debuggerVersion);

rawDebuggingAPI .Initialize ();
           rawDebuggingAPI .SetManagedHandler (new ManagedCallback(this));

When ever we want to start debugging, we create ICorDebug interface and spawn out a CorDebug process from the call to CreateProcess() method on ICorDebug interface providing the information of the debugee process .

ICorDebugProcess process = CorDebug.CreateProcess(
                            filename,   // lpApplicationName
                              // If we do not prepend " ",

                           " " + arguments,                       // lpCommandLine
                            ref secAttr,                       // lpProcessAttributes
                            ref secAttr,                      // lpThreadAttributes
                            1,//TRUE                    // bInheritHandles
                            0x00000010 /*CREATE_NEW_CONSOLE*/,    // dwCreationFlags
                            IntPtr.Zero,                       // lpEnvironment
                            workingDirectory,                       // lpCurrentDirectory
                            (uint)pprocessStartupInfo,        // lpStartupInfo
                            (uint)pprocessInfo,               // lpProcessInformation,
                            CorDebugCreateProcessFlags.DEBUG_NO_SPECIAL_OPTIONS   // debuggingFlags
                            );

or we can attach to existing process by calling DebugActiveProcess method on ICorDebug interface which returns the ICorDebugProcess.

m_debugger.DebugActiveProcess ((uint)processId, win32Attach ? 1 : 0, out proc);

Whatever method we choose to start debugee process under debugger , the call backs from the creation of debugee process are send to us via ICoreDebugManagedCallback. There are all kinds of call-backs related to debugging  that we get  (LoadAppDomian,  LoadModule, CreateProcess,  Breakpoint, StepComplete,EditAndContinue etc).  Using the call-backs we can keep track of all the ICorDebug elements for current session.

Call-back also includes notification for the creation of ICorDebugThread . We can keep the track of this thread and can utilize this com wrapper to get the hold of current stack frames. We can call EnumerateChains method on ICorDebugThread and loop through the ICorDebugChain element. ICorDebugChain represent the one segment of call stack for ICorDebugThread and consists of ICorDebugFrame collection. ICorDebugFrame is the stack frame for current call stack segment (ICorDebugChain). We can get the collection of stack frames by invoking the method EnumerateFrames on ICorDebugChain element.

 

uint corChainIndex = CorThread.EnumerateChains().GetCount();
                foreach(ICorDebugChain corChain in CorThread.EnumerateChains().GetEnumerator()) {
                    corChainIndex--;
                    uint corFrameIndex = corChain.EnumerateFrames().GetCount();
                    foreach(ICorDebugFrame corFrame in corChain.EnumerateFrames().GetEnumerator()) {
                        corFrameIndex--;
                  try {
                         ------------

                    } catch (COMException) {

                            continue;
                        };
                        yield return corFrame ;
                    }
                }

Once we get ICorDebugFrame from the ICorDebugChain, we get the method or function (ICorDebugFunction ) at that frame by calling GetFunction() on ICorDebugFrame element.

ICorDebugFunction func = corFrame .GetFunction();

Setting breakpoint on specified line number:--------------

From ICorDebugManagedCallBack we also get the notification of the current module through ICorDebugModule parameter from LoadModule call-back.  ICorDebugModule contains the method GetMetaDataInterface() for retrieving the IMetaDataImport interface which is the interface that provides the metadata information for the current ICorDebugModule . Having got the metadata interface next step is to create the CorSymBinder_SxSClass instance and cast it into ISymUnmanagedBinder interface. Now we can call the method GetReaderForFile that takes the path of pdb file for current module and metadata interface as parameters to return ISymUnmanagedReader. This method opens the pdb file and returns the ISymUnmanagedReader , which is responsible for reading the debugging symbols from the pdb file.

Guid guid = new Guid("{ 0x7dac8207, 0xd3ae, 0x4c75, { 0x9b, 0x67, 0x92, 0x80, 0x1a, 0x49, 0x7d, 0x44 } }");
  IMetaDataImport     metaData = (IMetaDataImport)pModule.GetMetaDataInterface(ref guid);

ISymUnmanagedBinder symBinder = new Debugger.Interop.CorSym.CorSymBinder_SxSClass();
  ISymUnmanagedReader reader   =  symBinder.GetReaderForFile(metaData, fullname, searchPath);

Now we can get ISymUnmanagedDocument collection from the ISymUnmanagedReader by calling GetDocuments method on ISymUnmanagedReader. ISymUnmanagedDocument is the document referenced by the pdb symbol store.

Through ISymUnmanagedDocument we can get the closest line to the sequencepoint , providing our line number for the function that we want to debug. Sequencepoints are the places that IL marks as the points that can be used for stopping and debugging purpose. We do so by invoking method FindClosestLine on ISymUnmanagedReader providing our line number.

FindClosestLine returns the closest line number to the relevant Sequencepoint in IL corresponding to our provided line  number. Using this line number we can get the function at this line number and all the sequence points for this function.

uint validLine = symDoc.FindClosestLine((uint)line);
  ISymUnmanagedMethod    symMethod = symReader.GetMethodFromDocumentPosition(symDoc, (uint)validLine, (uint)column);

SequencePoint[] seqPoints = symMethod.GetSequencePoints();

Now we can iterate through all the sequence points and get the ICorDebugFunction .

ICorDebugFunction func =  pModule.GetFunctionFromToken(symMethod.GetToken());

On this ICorDebugFunction we can place our breakpoint.

ICorDebugFunctionBreakpoint corBreakpoint = func .GetILCode().CreateBreakpoint((uint)ILStart);

ILStart parameter:- we get it through sequencepoint

int ILStart=(int)sqPoint.Offset;

Above code was taken by me  for study purpose from Managed Stack Explorer and SharpDevelop Debugging Addin  source code.

ICorDebug is feature rich debugging api, so it has numerous functionalities that I have yet to cover. Hope this blog will be useful.

Sunday, November 21, 2010

Android :- VOIP & SIP

Mostly we  use  PSTN (public switched telephone network) for making and receiving the voice calls and pay the call charges as per call plan.  But with the use of VOIP for mobile or mVOIP we can set up our own small  mVOIP (mobile voice over IP) network  and communicate with our group members  (pbxes.org) or can call anyone having VOIP enabled phone .  VOIP over mobile phone  is achieved  using different kind of protocols , but most popular SIP (session initiation protocol) is the most widely used standard. VOIP uses the SIP standard for signalling and controlling the voice or video over IP (Internet Protocol). 

SIP is peer-to-peer protocol so it requires very basic network over internet. VOIP converts the analog voice signals to digital , creates the data packets and transmits the packets over internet. SIP plays the role of signalling and controlling protocol for these data packets.

Like me if you have a droid and access to Wi-Fi ,  you can install a SIP client and make  voice / video  call using the Wi-Fi.   SIP client installed on phone makes the phone act as  SIP phone. SIP protocol needs the SIP clients , which are SIP network endpoints to communicate. As SIP is peer-2-peer protocol so we do not need any other network element in- between, but SIP service providers will put a SIP server in-between which will act as proxy server connecting different clients with each other.

To get a SIP number you can create a account with any SIP provider  (ipetel,   tpad, worldnet etc) .You will get a SIP number , password, SIP proxy. I used ( https://secure.tpad.com/signup/) to get my SIP number .  For android the best available SIP client is Sipdroid , it is open source SIP application and is generally available via gnu licence.  Go to android market on your phone and download sipdroid . After installing Sipdroid , start the sipdroid . It will ask for phone number and calling party address, it also give option to create new pbx account and link it to your google voice account. You can create a account with pbxes.org or you can use sipdroid as normal SIP client without pbx account associated with it .

To use Sipdroid without pbx account go to settings and select SIP Account .  Provide the SIP number for authorization name field, type in your password for password and enter the SIP proxy for server or proxy field.  All these information was available to us from SIP account creation with SIP provider. Check mark the use WLAN if you are using Wi-Fi .
After configuration, if you connect to Wi-Fi you will get a green dot in your notification pad on phone , confirming the sipdroid online.  Now to connect to any other SIP client just dial the SIP number and get connected.  SIP clients provide us with free VoIP calls over IP , condition phone should be  IP enabled. 

If you have fring account , you can download fring mobile app for android which is free and also can use it as SIP client along with normal fring calls.

Friday, November 19, 2010

SharpDevelop:- ToolBoxProvider Service

In this blog , we will look at ToolBoxProvider service of SharpDevelop. SharpDevelop ToolBox window  uses this service for creating the categories and  loading the controls inside  the ToolBox . This service is provided by FormsDesigner AddIn.  Default controls loaded  in the SharpDevelop’s ToolBox are from various assemblies (System.Windows.Forms, System.Data, System.Drawing etc ) . Information regarding these controls assemblies and components inside them is stored by SharpDevelop in a  xml file called  “SharpDevelopControlLibrary.sdcl” , this file is located at  “..\data\options”. If we want our custom controls  to be  added to the ToolBox , we have to use the services of ToolBoxProvider.  Lets us see how to add the components from controls library . 

public static void LoadToolBoxItems()
   {
       List<ToolComponent> lstToolsComponent = null;

       string ControlsFilePath = System.Configuration.ConfigurationManager.AppSettings["Controls_File_Path"].ToString();

       Category myCatagory = new Category("MyCatagory");
       myCatagory.IsEnabled = true;

       ToolboxProvider.ComponentLibraryLoader.Categories.Add(myCatagory);

       //Add the controls file controls
       Assembly asm = Assembly.LoadFrom(ControlsFilePath);
       lstToolsComponent = AddComponentsToList(asm, Path.GetDirectoryName(ControlsFilePath));
       foreach (ToolComponent comp in lstToolsComponent)
       {
           myCatagory.ToolComponents.Add(comp);
       }

       ToolboxProvider.SaveToolbox();
       ToolboxProvider.ReloadSideTabs(true);
   }

Above routine gets the control library’s path from config and loads the assembly at runtime to fetch the components from the assembly . Another routine AddComponetsToList()  takes the assembly and assembly directory path as parameter and returns the list of  ToolComponent instances. At last we call SaveToolBox on ToolBoxProvider and reload the toolbox. SaveToolBox routine populates the “SharpDevelopControlLibrary.sdcl” file with our assembly and components information and saves it. ReloadSideTabs routine reads the .sdcl file and fills the components in ToolBox.

AddComponentsToList routine :--

static List<ToolComponent> AddComponentsToList(Assembly assembly, string loadPath)
    {
        List<ToolComponent> lstToolsComponent = new List<ToolComponent>();
        if (assembly != null)
        {
            try
            {

                foreach (Type t in assembly.GetExportedTypes())
                {
                    if (!t.IsAbstract)
                    {
                        if (t.IsDefined(typeof(ToolboxItemFilterAttribute), true) || t.IsDefined(typeof(ToolboxItemAttribute), true) || typeof(System.ComponentModel.IComponent).IsAssignableFrom(t))
                        {
                            object[] attributes = t.GetCustomAttributes(false);
                            object[] filterAttrs = t.GetCustomAttributes(typeof(DesignTimeVisibleAttribute), true);
                            foreach (DesignTimeVisibleAttribute visibleAttr in filterAttrs)
                            {
                                if (!visibleAttr.Visible)
                                {
                                    goto skip;
                                }
                            }
                            ToolComponent toolComponent = new ToolComponent(t.FullName, new ComponentAssembly(assembly.FullName, loadPath), true);
                            lstToolsComponent.Add(toolComponent);

                        skip: ;
                        }
                    }
                }
                return lstToolsComponent;
            }
            catch (Exception e)
            {
                return lstToolsComponent;
            }
        }
        return lstToolsComponent;
    }

Thursday, November 18, 2010

Android :- Google voice India

How to activate google voice account for myself ?  After tolling hours on net to find the procedure for getting a google voice account for myself (in India) , I finally got something  nice from Harsh Agrawal’s article at http://www.callingallgeeks.org/how-to-get-google-voice-account-india-country-world/ . After following all the procedure from the articles , I was finally able to get a free US based phone number from Redmond   and a Google voice account .  This blog is just a short description of my experience  based on Harsh article. As described I signed up for Tpad account (https://secure.tpad.com/signup/) and provided my mail address and a password. After setting up an account with Tpad, I got a  mail , providing me with a Tpad number (SIP number) and Tpad proxy  “sipx.tpad.com” (SIP proxy) .

Next step was to download Softphone (Ninja Lite)  app and install it, download link is provided within received mail . Starting softphone app will ask for Tpad number and password, Tpad number is SIP number we received via mail and password is the same password we used to create Tpad account. Next step is to sign up for IPkall account (http://phone.ipkall.com/) , information required are Tpad number (SIP) and Tpad proxy (SIP) that we received in mail  from Tpad account creation. After finishing the IPkall account creation we will receive mail from IPkall having a US based IPkall number  and our SIP number and SIP proxy associated with it. So far so good.

Next we have to set up a google voice account that will need a US based number and also for me google voice is not available in my home country (India). To get hold of google voice website in regions where it is not available we have to use proxy , I downloaded the UltraSurf proxy client and it worked for me. Using proxy I was able to get to google voice site . Google Voice website asks  us to choose a google voice number based on area  code or phrase. I choose Redmond as area code and selected a google number from available numbers.  After first step site ask us to set a four digit PIN number and then ask us to set a call forwarding number. Set call forwarding number,  the number we got from IPkall confirmation mail (US based number).  After setting the call forwarding number , google voice site ask us to make a call via google number that is forwarded to the IPkall number .

To test the google number keep the softphone (Ninja Lite) on. Select make a call from google website option , option also show us a two digit number that we have to dial on out softphone when we receive a google forwarded call. When we receive google forwarded call and after dialling the code we will be asked for a sample voice recording and a greeting voice recording , after finishing this step our google voice account is activated.

After activating the Google voice number , visit the m.google.com/voice on your android mobile phone . There is download link for installing the google voice application on your android mobile from android market.

After installing the google voice application , start the google voice application from your mobile. Login to your google voice account. At application start-up you will be given option for registering the google voice number or your exsisting phone  number for your android phone. Select the IPKall number that we received from IPKall registration as done through above said procedure (253**************).   After providing the phone number we will be asked for configuration of voicemail. After going through all the step google voice application wizard is completed. Soon we will get a voice mail from the google voice , confirming the completion of  setup for google voice on our android mobile.

Now with our google voice account set up we can call a another google voice number configured same way as our android phone.

Saturday, November 13, 2010

C# :- Dynamic Keyword and Reflection

With help Dynamic keyword in C# we can invoke methods on the types without specifying the types at compile time . Once the Dynamic keyword is used compiler do not try to infer the type from the context  as  var keyword do , but instead rely upon the runtime to resolve the call . I found Dynamic keyword very useful while using reflection . I got in the scenario were I have the types name specified in the xml file and I have to create the instance of these types using reflection.  Lets say for instance i have types  with names  type1 and type2  in a xml file,  having method RoutineOne()  in both classes  and there implementation in a  .dll ( implementation.dll ) .  To create the instances using reflection I have to do following :--

         Type refelectedType;
         Assembly refelectedAssembly = null;

refelectedAssembly = Assembly.LoadFrom(dllPathName);
refelectedType = refelectedAssembly.GetType(“type1”);

       type1 routine = (type1)Activator.CreateInstance(refelectedType);
        routine.RoutineOne();

and do same thing to get the instance of “type2”.  We can see that we have to typecast the instance into respective  type. Or we can create an Interface and get common method in this interface. Lets say interface  ICommonRoutines :-

public interface ICommonRoutines
    {
        void RoutineOne();

    }

After implementing the interface in both the classes we can again do :-

         Type refelectedType;
         Assembly refelectedAssembly = null;

refelectedAssembly = Assembly.LoadFrom(dllPathName);

foreach (string clsName in lstClassNames){ 

refelectedType = refelectedAssembly.GetType(clsName);

ICommonRoutines routine = (ICommonRoutines)Activator.CreateInstance(refelectedType);
routine.RoutineOne(); }

Here also we have to type cast the created instance into ICommonRoutine interface . We now can read the type name from xml file and create the instances using the common interface , but to do so we have to reference the implementation dll (Implementation.dll) to get the type ICommonRoutines for typecasting .

As the new types are added in the xml file we have to create the type definition and implement the interface in order for our code to be valid for instance creation.

Another way to do above thing is to use Dynamic keyword which removes the dependency on the implementation dll and bypasses the compilation time checking.

         Type refelectedType;
         Assembly refelectedAssembly = null;

refelectedAssembly = Assembly.LoadFrom(dllPathName);

foreach (string clsName in lstClassNames){ 

refelectedType = refelectedAssembly.GetType(clsName);

dynamic routine = Activator.CreateInstance(refelectedType);
routine.RoutineOne(); }

Using Dynamic keyword removes the need for typecasting during instance creation and dependency on implementation dll.  Now we can add any number of types in xml file and create their instances without worrying about availability of types for typecasting . As the compile time checking is ignored , it becomes little dangerous if all the types are not properly implemented . In this case it is still better to use an interface as a contract for all the types to follow and use dynamic keyword .

Wednesday, November 10, 2010

SharpDevelop :- ParserService

While working on SharpDevelop  , I got in situation where I have to construct the assembly name at runtime just before the build happens and set it as the assembly name of the SharpDevelop project.  Assembly name has to be in format  {NameSpace.ClassName.dll} . To construct this assembly name I have to parse the code file for example say MyClass.cs and get the namespace name and class name .

Previously I have done this in Visual Studio using  CodeDom (FileCodeModel, CodeElements etc).

In SharpDevelop to get the job done I followed the below algorithm :---

i)  Get the instance of currently opened project ( IProject ) . We can get it through ProjectService class     (ProjectService.CurrentProject) .

ii) Iterate the project items and find the code file/project item  to parse.

iii) Get the file path of this project item ( projectitem.FileName ) and create the instance of FileName class by calling   FileName.Create(<file path>).

iv) Create the instance of class ParsableFileContentFinder and call method Create on instance taking FileName instance as parameter (parsableContentFinderObject.Create(<FileName filename>)).This call on method parses the code file and buffers the content. This content is made available through the return type of Create method (ITextBuffer).

v) Call the ParserService.Parse(<filepath>, <ITextBuffer> ) method that takes the filepath and ITextBuffer as parameter. This method returns the ParseFileInformation object , that contains all the information related to the code elements .

Developed code on basis of above algorithm :
    
    public static void ParseNCreateWaspAssembly(string filename, out string assemblyName)  {

            assemblyName = string.Empty;
            IProject project = null;
            IEnumerable<ProjectItem> projectItems = null;
            ParseableFileContentFinder parseableFinder = null;
            string filepath = string.Empty;
            ITextBuffer contentBufferContainer = null;
            FileName targetCodefile = null;
            ParseInformation parseInfo = null;
            string projectName = string.Empty;
            string className = string.Empty;
            string nameSpace = string.Empty;

                project = ProjectService.CurrentProject;
                parseableFinder = new ParseableFileContentFinder();
                if (project != null){
                    projectItems = project.Items.AsEnumerable();
                    foreach (ProjectItem projItem in projectItems){
                        if (string.Compare(Path.GetFileNameWithoutExtension(projItem.FileName), filename,

StringComparison.OrdinalIgnoreCase) == 0){

                            filepath = projItem.FileName;
                            targetCodefile = FileName.Create(filepath);
                            if(ParserService.GetParser(filepath) != null){
                                contentBufferContainer = parseableFinder.Create(targetCodefile);
                                if(contentBufferContainer != null){
                                    parseInfo = ParserService.ParseFile(targetCodefile, contentBufferContainer);
                                    if(parseInfo != null){
                                        if (parseInfo.CompilationUnit.Classes.Count() > 0){
                                            assemblyName = parseInfo.CompilationUnit.Classes[0].FullyQualifiedName;
                                            project.AssemblyName = assemblyName;
                                            project.Save();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
        } 

That’s how we can search for the code file and get access to all the code elements .