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 .

Monday, October 25, 2010

NDepend

Recently I was presented with an opportunity and the pro licence by Patrick Smacchia lead developer NDepend tool , to test run the NDepend 3.2.0.5097 and list its unique and amazing features.


NDepend is the great tool for analysing the .Net code base and measuring the quality of code via various code metrics presented by the NDepend analysis. Analysis of the code is presented in nice visual layout , so it is easy to get a quick summary of all the related information. Its makes the job very easy while you are trying to understand the code workflow designed by others .


I am currently in process of exploring the NDepend tool and running it against various small and large code bases to effectively check out and understand the analysis presented by NDepend.


I will be soon writing some detailed benifits of NDepend and its impact on overall software quality. Until then I will like my readers to check out the amazing features of NDepend at


http://www.ndepend.com/# .


If you find it interesting enough then you can download the trial version of NDepend from :-


http://www.ndepend.com/NDependDownload.aspx


and check out yourself for the
effectivness.

SharpDevelop:- ProjectItems

This blog entry will be all about adding the projectitem to the SharpDevelop project. In SharpDevelop we get project service from the class "ProjectService" that lets us to add various type of project item to the SharpDevelop project and bind to the the different project related events. ProjectService class can be found in main base addin ("\Project\Src\Services\ProjectService\ProjectService.cs"). SharpDevelop project item can be of different types like cs/vb files , project references , webreferences etc. Main base class for all the project items in SharpDevelop is "ProjectItem" Class from which all the derived project item classes evolve like FileProjectItem, ReferenceProjectItem, WebReferenceProjectItem etc.
In this blog we will see the addition of assembly references and the addition of cs/vb class files to the SharpDevelop Project at runtime.

Once the project is opened in the SharpDevelop we can access the current project via ProjectService class ( "ProjectService.CurrentProject" property ).

To add the assembly reference at runtime we have to create the instance of ReferenceProjectItem and provide the current project instance and the assembly name in the constructor.

ReferenceProjectItem item = new ReferenceProjectItem(ProjectService.CurrentProject, Path.GetFileNameWithoutExtension(my_exsistingCSFilePath));

Prior to adding the assembly reference to the Project , we can check if assembly reference is already added to the Project. We can check that by checking all the current project items .

IProject project = ProjectService.CurrentProject;


ProjectItem proitem = (from proI in project.Items.AsEnumerable() where Path.GetFileNameWithoutExtension(proI.FileName) == Path.GetFileNameWithoutExtension (my_exsistingCSFilePath) select proI).SingleOrDefault();


if (proitem != null){ ProjectService.RemoveProjectItem(project, proitem);
}


After checking for the exsistence of the assembly reference we can add the assembly reference to the Project at runtime by:-


ProjectService.AddProjectItem(project, item);


project.Save();


ProjectBrowserPad.RefreshViewAsync();


To add the cs/vb project item to Project at runtime , we have to create the instance of "FileProjectItem" and provide appropriate parameters to the constructor.

IProject project = ProjectService.CurrentProject;


string relFileName = FileUtility.GetRelativePath(project.Directory, filePath);


FileProjectItem fileProjectItem = new FileProjectItem(project, project.GetDefaultItemType(filePath), relFileName);


Then we can add the file to the current project , following the same procedure as we did in addition of assembly reference.

ProjectItem item = (from proI in project.Items.AsEnumerable() where Path.GetFileName(proI.FileName) == Path.GetFileName(filePath) select proI).SingleOrDefault();


if(item != null) {ProjectService.RemoveProjectItem(project, item); }


FileNode fileNode = new FileNode(filePath, FileNodeStatus.InProject);

fileNode.ProjectItem = fileProjectItem; ProjectService.AddProjectItem(project, fileProjectItem);

project.Save();

ProjectBrowserPad.RefreshViewAsync();


In this same way we can add WebReferences and all other project items to the SharpDevelop Project.

Friday, October 22, 2010

SharpDevelop :- ReferencePath

Adding Referencepath property to the SharpDevelop project property page programmatically. This is the topic of this blog. I wanted to add runtime generated reference path to the project property page. SharpDevelop provide Project service for managing the project related funtionality. ProjectService class contains many static method and events that can be used to load the new project to the solution or add exsisting project to the solution. ProjectService also exposes many events that are raised when project is added.removed or projectitem are added or removed.

I decided to add the dynamically generated reference path to the project after the project is loaded inside the SharpDevelop. For this I subscribed to the ProjectCreated event of ProjectService class .

ProjectService.ProjectCreated -= new ProjectEventHandler(ProjectService_ProjectCreated);

So whenever a new project is added to the solution , i can get the event and add my reference path to the project property. When we get the ProjectCreated event we get the ProjectEventArgs as the parameter. ProjectEventArgs contains the property Project which is of type IProject . We have to cast the Project property to MSBuildBasedProject .

MSBuildBasedProject is class that is responsible for the generating and setting the MSBuild items and properties from the in memory representation of project and project items.

Now we have to call the SetProperty method of MSBuildBasedProject with proper property /value and call the Save method on the MSBuildBasedProject.

void ProjectService_ProjectCreated(object sender, ProjectEventArgs e){
MSBuildBasedProject msProject = e.Project as MSBuildBasedProject;
msProject.SetProperty("ReferencePath", myRefPath);
msProject.Save();
}

Thursday, October 21, 2010

SharpDevelop :-- Project Template

This blog is about creating custom project template and integrating it with the SharpDevelop Studio. Whenever we wanted to create a new project whether it is winform project , class library ,usercontrol etc ,we are presented with predefined project template in New Project Dialog Box. In Visual studio or VSTA the project templates are the msbuild project templates and are installed with the IDE . ShareDevelop project templates are the custom project template files similar to the VS templates with xml format. PropertyService of SharpDevelop contains all the info about the configurable and global properties. To get the path of the SharpDevelop project templates we can use PropertyService to find the path. PropertyService member DataDirectory gives us the location where project and file templates are stored .

So SharpDevelop project templates are stored at location :--

Path.Combine(PropertyService.DataDirectory, "templates", "project");

Under this path there are folders named "CSharp" and "VBNet" .These folder contains the respective project template for these languages. SharpDevelop project templates are xml file with extension ".xpt".

Lets examine the project template for example "FormsProject.xpt" .



<Template created="06/10/2001" templateType="MyTemplateCS">
<TemplateConfiguration>
<Name>MyTemplate</Name>
<Category>C#</Category>
<Subcategory>MyCatagory</Subcategory>
<Icon>C#.Project.Library</Icon>
<Description>Template for Workflow.</Description>
<SupportedTargetFrameworks>v2.0;v3.5Client</SupportedTargetFrameworks>
</TemplateConfiguration>
<Actions>
<Open filename="Main.cs" />
</Actions>
<Project language="C#">
<ProjectItems>
<Reference Include="System" />
<Reference Include="System.Data" />
</PROJECTITEMS/> language=C# name="Data_Buzz.cs" Library<> <> >
<![CDATA[
/* Our code goes here */
]]>
<</File>
</Files>
</Project>
</Template>



We can see that SharpDevelop Project Template is similar to the msbuild project template. There is opening node "Template" that has some attribute defining the general info about the template. Then comes the "TemplateConfiguration" that tells the template configuration :-

Name :- name of the template

Category :- the main folder under which to show this template in New Project Dialogbox.

SubCategory :- the folder under main folder under which to show this project template in New Project Dialog box.

Icon :- icon to show on the project template shown in New Project Dialogbox.
Supported target framework :- the .net target framework.

"Actions" node tells us which file to open up in ShareDevelop IDE when the project template is loaded. It defines the child node "Open" with attribute "filename" that defines the file to open in SharpDevelop workspace after the project is loaded. Then comes the node "Project" defining the attribute "language" .

Under Project node comes "ProjectItems" which contains the child nodes of type "reference". These nodes of type "reference" tells us what assemblies to add up as references to the project when it is loaded up in SharpDevelop IDE.

Project node also contain the child node "PropertyGroup" which contains the node about the information of the project type (exe or library) under node "OutputType".
In case of msbuild project templates we have code file (.cs or .vb) in separate files and info of these file are stored in project templates. But in SharpDevelop the code files to generate along with the project are defined inside the project template. "Project" node in project template defines the node "Files" which in turn contains the child nodes "File". "File" node contains the attributes name and language defiining the name and language of .cs or .vb file . Under "File" node there is CDATA section which contains all the code for file .

Now lets see how these templates are loaded in SharpDevelop. We can locate the New Project DialogBox under the base addin code (ICSharpCode.SharpDevelop.Project.Dialogs) . Base addin is the project (ICSharpCode.SharpDevelop.csproj) and New Project DialogBox is located at "\src\gui\dialogs". The constructor of New Project DialogBox contains the method "InitializeTemplates()" . In this method project templates are iterated and filled up in the listview of the NewProject DialogBox. The collection of project templates are fetched from the ProjectTemplate class's public property "ProjectTemplates". If we go inside the ProjectTemplate class and look at ProjectTemplates property we can see the get part of property returns ProjectTemplate Collection after calling the "UpdateTemplate()" method.

"UpdateTemplate()" method is responsible for creating the project template collection.It contains the code to load all the project templates from the DataDirectory and create in memory representation of project template xml files. So the instance of class ProjectTemplate is the runtime representation of the project template files residing in the DataDirectory.

ProjectTemplate class also contains the public property ProjectDescriptor , this property is of type "ProjectDiscriptor". Instance of ProjectDiscriptor class is also created by the Project template class and it contains the information about the files of the Project . ProjectDiscriptor class holds the in memory representation of the file node in the ProjectTemplate xml file.

So to create our own project template we have to create the ".xpt" xml project template file and place it in the DataDirectory under relative language folder (CSharp or VBNet). SharpDevelop will automatically load the project when the New Project DialogBox is opend.

If your project files are generated at runtime from other system and you have to create new project template based on them , then you have to create the project template at runtime and save it to the DataDirectory. Then you have to call the static method UpdateTemplate() of ProjectTemplate class to reload the Project template .

Tuesday, October 19, 2010

SharpDevelop

Recently , I started working with the SharpDevelop , open source IDE for the .Net platform . It is same as NetBeans and Visual Studio IDE and provides almost same features . Previously I have worked on VSTA as tool for developing addin's for a application. VSTA is the subset of Visual studio and provided many ways to extend the IDE . I have done many customization in the IDE with VSTA programming interface. In VSTA using ENVDTE namespace we get hold of the extensibility framework for IDE and its funtionalities. We can provide our own custom menu, menuitems, toolbar,toolbar items , we can extend the contextmenus of IDE , get hold of many IDE command like build ,rebuild, edit many properties of the IDE like platform target, reference path, active configuration etc. Apart form all these we can define our own project templates, wizards (IDEWizards) etc and can add projects and project items at runtime. We can use CodeDom to generate code , create assemblies and build them.

Can I achieve same thing using ShareDevelop ? To find out that, I got source code of ShareDevelop and started digging it. Sharpdevelop is based on addin model . It consist of a small core and all its functionalities are held by addins . Core contains the code to extend the SharpDevelop via all the other addin's. SharpDevelop Addin's are simple xml files and the binaries associated with them (.dll etc). For example Addin name myaddin will have a single xml file with extension .addin :- myaddin.addin and one or more binaries having the implementation of addin (myaddin.dll ). Xml file contain some nodes specific to the addin general information .Main thing to notice in addin xml are the extension nodes .Extension nodes starts with the name path which has the attribute named "name" that defines the path where this extension will be added up on the SharpDevelop core.

<path name="/SharpDevelop/Workspace/MainMenu">;

SharpDevelop contains this concept of paths . SharDevelop core and the addin responsible for the base functionality of the SharpDelvelop (ICSharpCode.SharpDevelop.addin) defines some paths upon which the functionalities can be extended. Paths represent the way via which we can find a node in a tree where "/" defines the root node. In fact the SharpDevelop maintains the tree structure for all the addin's that extend it . So we can extend the base with a addin and that addin will become the tree node for addin tree.If that addin defines a extension point then further a next addin can extend this addin. This features of extending a existing addin is not there in VSTA framework. SharpDevelop core contains many services for basic functionalities like property, resource, gui etc handling. Another concept other than paths are codons. In addin xml file we can find the codons as :--


<Path name = "/SharpDevelop/Workspace/MainMenu">
<MenuItem id = "File" label = "&File">
<MenuItem id = "Separator1" label = "-"/>
<MenuItem id = "Exit"
label = "E&xit"
class = "NCvs.Gui.Commands.ExitCommand"/>
</MenuItem>
</Path>



-

We can see all the elements inside the path node . As i have said, path node defines the extension point in SharpDevelop and it also defines the node that will be added to MainMenu of SharpDevelop . What about the elements inside path node, they all are codons. Codons are the element that specify the behaviour of the elements inside the program. So path tells us the extension point and the menuitem "File" is added under this path node. Menuitem "File" also contains the element Menuitem "Seperator1 " and "Exit". These codons will arranged under the "File" codon which is under the MainMenu path. No we have a treenode under the path Mainmenu. What we get from example is that SharDevelop contains a AddIn Tree that contains the AddIn Tree Nodes , AddIn tree nodes conatin the AddIns and in turn Addins contain the Codons. Addin Tree contains various service to load the addins and build the tree. AddinTreeNode conatins the method BuildChildItems that returns the list of all the built codons from a addin. Addin class contains all the information about the codons inside it and all the info of assemblies needed to create the runtime object of the codon. It gets all this info from the xml file . Codon class contains a methos Buiditem that creates the runtime instance of the codon. So the built codon is the in memory representation of the codon item in addin xml file. Shardevelop core contains many builder and factory classes to load the assemblies containg the codon definitions and build the in memory tree for the Addin from addin xml file and entire AddIn tree.

But can I do all the stuff that I did with VSTA , described above at starting ? I think with the help of Base Addin i can start experimenting . In next post I will start with creating our own project template in SharpDevelop. Hope ,somebody will find it useful.

http://www.codeproject.com/KB/cs/ICSharpCodeCore.aspx
http://www.icsharpcode.net/opensource/sd/
http://sharpdevelop.codeplex.com/

Saturday, July 24, 2010

Python and Google App Engine

Quite from some time I was getting bored of working with .Net and for some recreational work I decided to start learning Python and google app engine (On Windows) .
After installing Google AppEngine for Python and Google data service,I was ready to dive in. Google app engine works on CGI standards. I decided to implement a feedback form and send mail to users informing them about other resources. I started with creating a working directory for my application.
Google app engine applications contains a configuration file (app.yaml) that tells about the runtime to use (in my case python) and the handlers that will redirect and process the request .


//////////////////////////////////
application: Feedback
version: 1
runtime: python
api_version: 1

handlers:
- url: /.*
script: feedback.py
/////////////////////////////////


In above app.yaml file url: section in handlers specify that request to the url /.* should be handled by the feedback.py python script file.

Google App engine web framework defines many modules that helps us to write handlers and processors for web requests.
Google Web application typically contains multiple classes that processes the request and generates the responses. WSGIApplication class instance is responsible for routing incoming request for a particular URL to one of the handler classes.Finally there is main method to start the application.


import cgi
from google.appengine.api import users
from google.appengine.api import mail
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

class MainPage(webapp.RequestHandler):
def get(self):
self.response.out.write("""
<html>
<Body>
<form method="post" action="/submit">
Name:</br> <input type="Text" name='name' width="100" />
</p>
Address:</br> <input type="Text" name='address' width="100" />
</p>
Email: </br><input type="Text" name='email' width="100" />
</p>
FeedBack:
</p>
<textArea name="name" rows="4" cols="60"></textarea>
</p>
<input type="submit" value="Submit"/>
</form>
</body>
</html>""")


class FeedBack(webapp.RequestHandler):
def post(self):
self.response.out.write('<html><body>Thanks for your feed back.')
self.response.out.write(cgi.escape(self.request.get('name')))
self.response.out.write('
<p>Email has been sent to you containing
futher resources.Thanks.
</body></html>
')
mail.send_mail(sender="Example.com Support <support@example.com>",
to=cgi.escape(self.request.get('email')),
subject="Your account has been approved",
body="""
Hello : ' + cgi.escape(self.request.get('name'))
+ ' </p>You can access the following resources .
<a href="" >Res1</a>
""")



application = webapp.WSGIApplication(
[('/', MainPage),
('/submit', FeedBack)],
debug=True)

def main():
run_wsgi_app(application)

if __name__ == "__main__":
main()


.
Above feedback (FeedBack.py) implementation contains two handlers classes (MainPage and FeedBack) inheriting the webapp.Requesthandler class. These classes implement the post and get method that handles the incoming requests. Self.request and Self.response are the objects that are used to get the request parameters and generate the response. Apart from the handlers classes, WSGIApplication instance is created that specifies the URL's mapped to the handler classes, debug=True specify to print the error info on page if any. Then there is main method that runs the application.

As configured in the app.yaml , the request at base Url initiate the feedBack.py, which then routes the request to the handler class , based on WSGIApplication mapping. Main handler displays the feedback form with post method and action equal to "/submit" url. On submitting the MainPage form , url is redirected to "/submit" url , which as defined in the WSGIApplication, routes the request to feedBack handler class. Feedback handler class creates the response and sends a mail to user.

To run the application we can use command line or Google App engine launcher.
Start the Google App engine Launcher and use add application option to add the working directory.Google App engine launcher provides a simple UI to run the application.

Google data services contains various modules that can be used to access and use various google services such as youtube , picasa , facebook etc. Routing mechanism is somewhat same as Asp.net MVC. What I found is that Google app engine development is tightly integrated with other google services and exposes rich api to interact with other google services.

Google App Engine


Python

Wednesday, July 7, 2010

Silverlight Video Streaming

Recently I was on as project , that involved playing the media files from the storage server in the browser. Silverlight was chosen to play the media files. Plan was to have a datagrid that shows media files filtered on the basis of date. After the user chooses the file , the file is fetched from the storage and played in the media element . Starting was the creation of the project structure , a silverlight application with asp.net project to host the silverlight application. In the silverlight application, a usercontrol with media element embedded is created.





















<mediaelement name="media" mediafailed="MediaElement_MediaFailed" autoplay="True">

Media Element has the property source and a method SetSource that set's the media file to be played in the media element. Source property takes the Uri of the media file and the SetSource method takes stream to be played in the media element. Setting the Source property was not a choice as the media files resided on the other server . Silverlight media element Source proerty do not support file:// or UNC path to set media files , files have to be on the webserver hosting the web app. So the solution to get the media files from the storage server and stream them to the silverlight client was to use WCF media streaming. At the silverlight client we use SetSource method of media element to provide the media stream.
WCF service will be hosted along side the web project on IIS . WCF service for silverlight application are little bit different from the normal WCF applications. WCF service has to be silverlight enabled. To create the silverlight enabled service goto :- Add New Item --> Silverlight --> Silverlight enabled WCF service , this will create a svc service file with default structure . We will start with creating a service contract interface IVideoService , having a method GetVideoFile that takes a string as parameter and returns the stream object. Method is decorated with the OperationContract and WebGet attribute.
.

[ServiceContract]
public interface IVideoService
{
[OperationContract]
[WebGet(UriTemplate = "media/{name}")]
Stream GetVideo(String name);
}


.
Now we create the implementation of the service contract by creating a class VideoService that implements the service contract . In silverlight enabled WCF service , we have attribute AspNetCompatibilityRequirements
on the service class. Service class implements the GetVideoFile method that takes as parameter the path of video (UNC or File://) and returns the filestream .


[AspNetCompatibilityRequirements
(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class VideoService : IVideoService
{
public Stream GetVideo(String name)
{
if(File.Exists(name))
{
return File.OpenRead(name);
}
return null;
}
}


.
Now our service class is in place, we create the WCF configuration for wcf streaming.We use basicHttpBinding with transferMode set to streamed , we also increase the maxReceivedMessageSize .With the service hosted on web app the endpoint address is always relative to the web address (Example : http://localhost:2310/Default.aspx --> http://localhost:2310/myservice.svc).






















At the silverlight client we add service reference to our WCF service and use proxy to get the media file and play it with media element.

VideoStreaming.VideoServiceClient client = new VideoStreaming.VideoServiceClient();
client.GetVideoCompleted += new EventHandler(client_GetVideoCompleted);
client.GetVideoAsync(@"\\Storage-pc\Files1\Encoded\myvideo.asf");


















We also have to create a clientaccesspolicy file and place it with service (.svc) file for making service available across appdomain boundries.











Now we are all set to stream the media file.

Network Security Access Restrictions in Silverlight
Making a Service Available Across Domain Boundaries
WCF Streaming Message Transfer

Saturday, June 5, 2010

WPF DockingManager :- AvalonDock

Some days ago , I was in need of a docking panel for a WPF project. I needed the collapse and expand functionality , floating windows etc . I was familiar with the DockingManager component from DevExpress for Win forms and wanted same type of functionality for my WPF project. So while searching I came across a open source initiative AvalonDock on CodePlex, it was quite the thing that I wanted.
I implemented the DockingManager of AvalonDock and got my Window working with several floating and dockable windows.

After making my main window have many dockable and floating windows , I needed another functionality , that was to make visibility off for close buttton on Dockablepane , apart from that I also wanted to style the Documentpane and Dockablepane . To make the close button visibility off for Dockablepane and Documentpane, there's the property IsCloseable on DocumentContent and DockableContent.

Using this property we can change the close button's visibility. To disable the floating of windows in DocumentPane , there is another property IsFloatingAllowed on DocumentContent . But there is no property to disable the floating of DockablePane yet. To style the DocumentPane and DockablePane I relied upon the Expression Blend. After opening my project in Expression blend , I navigated to the DockablePane and DocumentPane in Visual Tree and used the option "Edit Copy of Template". This option make's the default style of DocumentPane and DockablePane available to us, Now you are free to edit the style as you like. The default style contains the Control template for both DockablePane and DocumentPane in their respective styles. We can edit them to get our desired look .

But there is one issue , after we save our project in Expression Blend with edited styles, it seems that Expression Blend removes the command binding from the style of DockablePane for Close Button and AutoHide Button. So if we run the application you will notice that close and autohide button on DocakblePane no longer works. The solution is to reintroduce the command binding for close and autohide button by specifying Command="ad:DockablePane.ToggleAutoHideCommand" and Command="ad:DockablePane.CloseCommand" in the respective xaml Button tags.


<ad:DockingManager x:Name="dockManager" RenderTransformOrigin="0,0">
<ad:ResizingPanel Orientation="Vertical" >
<ad:ResizingPanel Orientation="Horizontal" >
<ad:DockablePane
x:Name="story" Style="{DynamicResource DockablePaneStyleMosaic}">
<ad:DockableContent StateChanged="Live_StateChanged"
IsCloseable="False" DockableStyle="DockableToBorders" Title="Live">
</ad:DockableContent>
</ad:DockablePane>

<ad:DocumentPane Style="{DynamicResource DocumentPaneStyleMosaic}" >
<ad:DocumentContent Title="Recorded"
IsFloatingAllowed="False" IsCloseable="False">
</ad:DocumentContent>
</ad:DocumentPane>

<ad:DockablePane Style="{DynamicResource DockablePaneStyleMosaic}">
<ad:DockableContent
StateChanged="Live_StateChanged"
DockableStyle="DockableToBorders" IsCloseable="False" Title="Reports">
</ad:DockableContent>
</ad:DockablePane>

</ad:ResizingPanel>
</ad:ResizingPanel>
</ad:DockingManager>



.
There is another catch , all the edited style that we have applied on DockablePane gets removed once the DockablePane is in floating state . So once the DockablePane is dragged in floating state , all the style is lost. To get around this problem we can use StateChanged event fired by the DockablePane whenever the state is changed from Docked to floating and vice-versa.



private void Live_StateChanged(object sender,
AvalonDock.DockableContentState state)
{
try
{

AvalonDock.DockableContent panel =
sender as AvalonDock.DockableContent;

if(state == AvalonDock.DockableContentState.Docked )
{
(panel.Parent as AvalonDock.DockablePane).Style =
this.FindResource("DockablePaneStyleMosaic") as Style;

}

//Floating
if (state == AvalonDock.DockableContentState.DockableWindow )
{
(panel.Parent as AvalonDock.DockablePane).Style =
this.FindResource("DockablePaneStyleMosaic") as Style;
}
}
catch (Exception ex)
{
LogWriter.WriteLog("", ex);
}
}




As long as Avalon dock fulfills the requirement of my project , I am going to stick with it.
http://avalondock.codeplex.com/

Sunday, May 16, 2010

Managed Extensibility Framework .Net 4.0

In the past, I have worked with projects that involved extensibility . I have been on projects that lets the functionality of the application to be extended. To achieve this in Microsoft.Net framework we have System.AddIn (AddIn pipeline), VSTA (Visual Studio tools for Application) Applications and Component Model. Open source ventures such as Spring.Net , Unity framework , Structure Map etc.

Previously I have blogged about Unity and AddIn pipeline development to achieve functional extensibility . With the release of .Net 4.0 , new kid is on the block MEF (Managed Extensibility Framework). This framework enables us to write extensible application using the Attribute Programming model, although framework is not restricted to a particular programming model and is itself fully extensible. When I began exploring the framework I found it simple and light weight . There was not that much effort as it took in System.AddIn development, to develop application, from either AddIn developer or hosting application side.

Microsoft them self made Visual Studio 2010 Editor extensible by using MEF. We can write extensions for VS2010 code editor and there are great samples available at CodePlex.

MEF attribute model allows as to extend application by using attributes on the parts, that we want to be composed dynamically. In .Net 4.0 System.Component Model.Composition.dll is the assembly to be referenced to start developing MEF application. Namespaces to be used are : -

using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;

In MEF the component that we want to take part in composition are called parts.Parts are the component on which the attributes are applied. We can apply attribute to the part to make it available for other parts to consume and attribute to request service of parts.

Export attribute is applied on the parts the we want to expose.
Import attribute is applied on the property or constructor of the parts, that wants the services of exported parts. Contracts are the identifiers of the Import and Export attributes. For example :--


public interface IStockService
{
}

[Export(typeof(IStockService))]
public class BSE : IStockService
{
}

[Export(typeof(IStockService))]
public class LSE : IStockService
{
}

[Export(typeof(IStockService))]
public class NSE : IStockService
{
}

public class MyStockApp
{
[ImportMany]
public IEnumerable<IStockService> StockService
{
get;
set;
}
}




.

We can also have multiple imports , all we have to do is mark property by ImportMany.
After we have defined our parts , we need code to initiate the parts and map importers to exporters. To do this we need a catalog to discover the parts , parts can be discovered from a assembly, assemblies in a directory, from specific type . MEF provide various catalogs :- AssemblyCatalog, TypeCatalog, DirectoryCatalog ,AggregateCatalog etc. Next we need container that composes all the parts , when we call compose method.


AssemblyCatalog catalog =
new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly());
CompositionContainer container = new CompositionContainer(catalog);
container.ComposeParts(this);


.

By default all the export parts are singleton, meaning they will have same instance for all the importing parts. But this features can be controlled by partCreationPolicies. We can provide new instance of export to each import.


[Export(typeof(IStockService))]
[PartCreationPolicy(System.ComponentModel.Composition.CreationPolicy.NonShared) ]
//[PartCreationPolicy(System.ComponentModel.Composition.CreationPolicy.Shared)]
public class BSE : IStockService
{
}



.

When we are importing many imports of a Contract , and want to decide which implementation to import , we can use ExportMetadata. ExportMetaData is applied on exports to separate them from other implementation.It takes a key and value as parameter to to its job.


public enum ServiceType
{
Furtures,
Corporate,
Forex
}

[InheritedExport ]
public class ServiceMetaData
{
public const string ServiceType = "ServiceType";
}

[Export(typeof(IStockService))]
[ExportMetadata(ServiceMetaData.ServiceType, ServiceType.Corporate)]
public class LSE : IStockService
{
}



.
After we have categorized our exports , at the importing end, we ImportMany in IEnumerable collection . We use System.Lazy to access the metadata and decide based on metadata which implementation to use. System.Lazy delays the initialization of the parts until the value of the part is actually accessed.



public class MyStockApp
{
[ImportMany]
public IEnumerable < System.Lazy <IStockService,
Dictionary< string,object >>> StockServices
{
get;
set;
}

public IStockService GetService()
{
var service =
from i in this.StockServices
where (ServiceType)i.Metadata[ServiceMetaData.ServiceType]
== ServiceType.Forex
select i.Value;

return (IStockService)service;
}

public void Compose()
{
AssemblyCatalog catalog =
new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly());
CompositionContainer container = new CompositionContainer(catalog);
container.ComposeParts(this);
}
}


.

[InheritedExport] can also be applied to the Export to define that the subclass of this Export will also provide export service. While importing many imports we can define [ImportMany(AllowRecomposition=true)], to define that all the new parts added to directory or assembly will be automatically discovered, composed and updated.

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

Friday, May 14, 2010

Garbage.Collector - 4.0

Managed memory management in .Net is done through Garbage Collector .It keeps track of all the used and unused memory through weak and strong references. With the release of .Net 4.0 ,G.C has been significantly enhanced. Lets see first the working of G.C and then what's new in .Net 4.0.

G.C traverses G.C roots and from roots it visit every object pointed by root and so on. This creates a object graph of objects that G.C maintains on heap and are marked as alive. All non referencing objects are freed and the memory compacted to avoid fragmentation.

G.C heap is allocated by the O.S and is the part of process working set. G.C heap is one continuous memory addresses block. To maintain the life time of objects G.C divides the heap in three generation Gen0,Gen1 and Gen2. Object that survives the G.C cycle are promoted to next generation.

Older the object its on lower memory addresses and newly allocated objects are on higher memory addresses. Size limits of each generation is limited and is dynamically changing to optimize the allocation, depending on the allocation rates.
Memory allocated to the generation is in segments and typically 16mb is assigned to the Gen0 and so on for Gen1, Gen2. New segments are only allocated to Gen1 and Gen2.
Older the object gets , it is promoted to the next generation and newly created objects are in Gen0. Performing G.C for Gen2 is expensive than for Gen0 and Gen1. So more objects we have in Gen1 and Gen2 , more time will they take to get deallocated.
Objects that are more than 85 KB in size are allocated on the Large Object Heap.

Most active heap generation is Gen0. G.C preforms collection and compactation in two ways :-

1) Full Collection that include the collection of all the
generations.

2) Partial Collections :- that include collection of ephemeral generation (Gen0 and Gen1).

Full collection is expensive, so CLR delays the G.C for full collection.
G.C collection is called when Gen0 reaches its threshold, GC.Collect() is called or system has low memory.

G.C can be divided into two types blocking G.C or Server G.C and Concurrent G.C or workstation G.C.

Server G.C is blocking G.C that means , when the G.C start the collection process all other managed threads are suspended for the application . After G.C has reclaimed the memory and finished the compaction of memory heap , all managed suspended threads are resumed.

In case of Concurrent G.C , we are allowed to allocate memory while the G.C is in progress, but this applies only to the full G.C. If its not the full G.C then its Ephemeral G.C (Gen0 and Gen1 G.C) , that means it is blocking G.C and not concurrent G.C . So , the server G.C and ephemeral G.C are always blocking G.C.

Concurrent G.C allows us to simultaneously allocate even if the full G.C is in progress. But if during the full G.C we exceeds the segment limit while doing allocation then we have to wait for the ephemeral G.C to be performed. So there is again issue of latency(Time period for which the application threads were suspended.).

In CLR 4.0 , there is the concept of the Background and Foreground G.C . Like concurrent G.C, when we are out of memory in ephemeral segment we do not have to wait for the another cycle of ephemeral G.C , but a foreground thread will be initiated to do ephemeral G.C , while the full G.C is in progress(Background G.C).So we can have both background full G.C going on along with foreground G.C for ephemeral generation. This reduces the latency time. As for now background G.C is only available for the workstation G.C and server G.C are still blocking G.C.

The G.C heap is allocated in segments and is part of the process working set.
When we allocate the memory for new objects and do enough allocation that one segment is full, now G.C will be allocated another segment by the O.S for new allocation. If both the segment are full and we haven't released objects of our application then these two segments are the committed memory from our process working set. Now if we start releasing the objects of our application, G.C will find unreferenced objects and will start collecting them. Memory will be freed and our process heap will have free memory available. But CLR may or may not release this free memory to the O.S , depending upon the memory emergency by the O.S.

CLR optimizes the memory management and can assume that application will be needing memory soon , resulting in free memory on process heap.

This free memory can be returned back to the O.S, if there is memory scarcity detected by O.S. This is why sometime we notice high memory working set in Task Manager but the indication of actual tied up memory is the memory committed.

http://blogs.msdn.com/maoni/archive/2008/11/19/so-what-s-new-in-the-clr-4-0-gc.aspx

http://blogs.msdn.com/salvapatuel/archive/2009/06/10/background-and-foreground-gc-in-net-4.aspx