Saqib Ullah

BootStrapper Know How

  Home  |   Contact  |   Syndication    |   Login
  93 Posts | 1 Stories | 341 Comments | 15 Trackbacks

News



Article Categories

Archives

Post Categories

Blogging websites

Favourite Blogs

Private Links

Sites

Thursday, August 06, 2009 #

We had a Situation when we want to check different binaries files for managed assembly. In our case we had more than 100 files in which 50 of them are .Net assembles and we want to check all of them and load all of .Net assemblies for verification. The very common approach that comes in our mind is AppDomain. But the problem with AppDomain.CurrentDomain is that it not unload the loaded assemble from current AppDomain and keep in mind that we had around 50 .net assembles that we need to check.

Here is come a very handy utility I found in Microsoft.Build.Tasks.dll

 

        public bool FileIsAssembly(string assemblyName)

        {

            bool _loadAss = false;

            AssemblyIdentity identity = null;

            try

            {

              identity = AssemblyIdentity.FromFile(assemblyName);

 

              if (identity != null)

                  _loadAss = true;               

            }

            catch (Exception ex)

            { }

            return _loadAss;

        }

 

Enjoy geeks...

Assemble is not load in Current AppDomain so no need to unload that.


Saturday, August 01, 2009 #

After a very long time I am writing this blog about one of the vital topic of the programming industry yes I am talking about Asynchronous programming. Today I gone a show you how to write a pure Async call in C#.

 

I saw lot of geeks are talking about how the actual asynchronous perform, how automatically callback calls oop it looks a rocket science but if you ask me or senior developers it not. Asynchronous call is simple as simple synchronous function calls.

By default System.Delegate provide us BeginInvoke and EndInvoke function that does actually the same operation for us. Today I am not writing this blog to show you guy how to write and use a delegate I am instead going to talk about how things work. For complete understanding Async operation we need some interfaces and classes that we required for our custom Async File Stream operation.

 

Interfaces

  • IAsyncHandler
  • IAsyncAction (not as such mandatory)

 

Classess

  • AsyncFileRead (Main class that read file and return stream)
  • AsyncFileStream (Implement IAsyncHandler)
  • AsyncOperation (Operate on AsyncFileRead class)

 

 

namespace AsyncApp

{

    public interface IAsyncHandler

    {

        IAsyncResult BeginRequest(AsyncCallback cb,object data);

        void EndRequest(IAsyncResult result);

    }

}

 

Defines methods that must be implemented for custom Async Operation in our case AsyncFileStream is the class that implement IAsyncHandler interface. AsyncFileStream class override BeginRequest and EndRequest function.

 

namespace AsyncApp

{

    public class AsyncFileStream : IAsyncHandler

    {

        private long _count = 1;

        Thread thread;

        #region IAsyncHandler Members

 

        public IAsyncResult BeginRequest(AsyncCallback cb, object data)

        {

            AsyncFileRead fileRead = new AsyncFileRead(cb, data);

            AsyncOperation operation = new AsyncOperation(fileRead);

            ThreadStart threadAction = new ThreadStart(operation.Process);

            thread = new Thread(threadAction);

            thread.Name = "Async_File" + _count.ToString();

            thread.Start();

            _count++;

            return fileRead;

        }

 

        public void EndRequest(IAsyncResult result)

        {

            AsyncFileRead read = result as AsyncFileRead;

 

            if (read.Stream != null)

                read.Stream.Close();

        }

 

        #endregion

    }

}

 

 

In BeginRequest function we take two parameters first is AsyncCallback and second is object. Here we create AsyncFileRead object by passing two args. We instantiate AsyncOperation class by passing it AsyncFileRead object and start new Thread from [operation.Process]AsyncOperation object. File open operation has been perform in this Thread.

 

EndRequest function take IAsyncResult as a parameter. In this function I casting result param into AsyncFileRead [in this case AsyncFileRead is my target class] and close the open stream.

 

namespace AsyncApp

{

    public class AsyncFileRead : IAsyncResult, IAsyncAction

    {

        private AsyncCallback m_callBack;

        private object m_data;

        private bool m_isComplete = false;

        private object m_lock = new object();

        private ManualResetEvent m_complete = null;

        private System.IO.Stream m_stream = null;

 

        public System.IO.Stream Stream

        {

            get { return m_stream; }

            set { m_stream = value; }

        }

 

        public AsyncFileRead(AsyncCallback callBack, object data)

        {

            m_callBack = callBack;

            m_data = data;

        }

 

        #region IAsyncResult Members

 

        public object AsyncState

        {

            get

            {

                return m_data;

            }

        }

 

        public System.Threading.WaitHandle AsyncWaitHandle

        {

            get

            {

                lock (m_lock)

                {

                    if (m_complete == null)

                        m_complete = new ManualResetEvent(false);

 

                    return m_complete;

                }

            }

        }

 

        public bool CompletedSynchronously

        {

            get { return false; }

        }

 

        public bool IsCompleted

        {

            get { return m_isComplete; }

        }

 

        #endregion

 

        public void Complete()

        {

            lock (m_lock)

            {

                if (m_complete != null)

                    m_complete.Set();

            }

            m_isComplete = true;

            if (m_callBack != null)

                m_callBack(this);

        }

 

        #region IMyOperation Members

 

        public System.IO.Stream Run(string filePath)

        {           

            Uri uri = new Uri(filePath);

            System.IO.FileStream fstream = null;

            if(System.IO.File.Exists(uri.AbsolutePath))

                fstream = File.OpenRead(uri.AbsolutePath);

            else

                throw new FileNotFoundException(uri.AbsolutePath);

 

            return (Stream)fstream;

        }

 

        #endregion

    }

}

 

AsyncFileRead class inherit from IAsyncResult and IAsyncAction interfaces. This class provide core implementation of Asynchronous operation. I am not going in detail of how to implement IAsyncResult interface reither then show the detail of IAsyncAction implementation.

 

namespace AsyncApp

{

    public interface IAsyncAction

    {

        System.IO.Stream Run(string filePath);

    }

}

 

Run function take file name as a parameter and open that file if exist other wise FileNotFoundException  has throw and if file exist return stream object of the file.

 

namespace AsyncApp

{

    internal class AsyncOperation

    {

        private AsyncFileRead m_AsyncResult;

 

        public AsyncFileRead AsyncResult

        {

            get { return m_AsyncResult; }

        }

 

        public AsyncOperation(AsyncFileRead obj)

        {

            m_AsyncResult = obj;

        }

 

        public void Process()

        {

            try

            {

                string _fileName = m_AsyncResult.AsyncState as string;

 

                m_AsyncResult.Stream = m_AsyncResult.Run(_fileName);

            }

            finally

            {

                m_AsyncResult.Complete();

            }

 

        }

    }

}

 

Process function of AsyncOperation class actually call the Run(string filePath) function of AsyncFileRead class in a thread.

Main Calling class code of AsyncFileStream

static void Main()

{

  AsyncCaller cal = new AsyncCaller();

  while (true) { }

}

 

class AsyncCaller

{

    IAsyncHandler read;

    public AsyncCaller()

    {

        read = new AsyncFileStream();

        read.BeginRequest(End, @"F:\CentOS_5.2-f001.vmdk");

    }

 

    void End(IAsyncResult result)

    {

        AsyncFileRead res = result as AsyncFileRead;

        Console.WriteLine("File Name {0}, File Length {1}", res.AsyncState.ToString(), res.Stream.Length);

        read.EndRequest(result);

    }

}

 

There is a lot of room available for the improvement in this example I am looking for yours feedback.

 


Tuesday, November 11, 2008 #

In my last blog we saw how to create netmodule any code in .net. Today we well see that how we can use it in an application. So for the implementation of the netmodule in my code I would like to show you a little Managed C++ application that easily consumed it.
 
// HelloWorld.h
#using <mscorlib.dll>
#using "CSharpHelloWorld.netmodule"
 
using namespace System;
 
// This code wraps the C# class using Managed C++
public __gc class HelloWorldC
{
public:
      CSharpHelloWorld __gc *t; // Provide .NET interop and garbage collecting to the pointer.
 
      HelloWorldC() {
            t = new CSharpHelloWorld(); // Assign the reference a new instance of the constructor.
      }
 
      void callCSharpHelloWorld() {
            t->displayHelloWorld();
      }
};
 
Note:-
            You get the CSharpHelloWorld class code from my last blog post. Where you also find the command how to create netmodule. For successfully run the above code you need to place the CSharpHelloWorld.netmodule and CSharpHelloWorld.dll in the same folder of Managed C++ application output folder because netmodule always required its respective .dll file for running.

Thursday, November 06, 2008 #

Hello geeks after a long time, I write some thing that basically tell what the actually difference between .net assembly and Netmodule file. I illustrate this blog by using the following piece of code block.
 
using System;
 
public class CSharpHelloWorld
{
      public CSharpHelloWorld() {}
 
      ///<summary>
      ///
      ///</summary>
      public void displayHelloWorld()
      {
            Console.WriteLine("Hello World, from C#!");
      }
}
 
.Net Assembly File
Basically .Net assembly is a compile library that contains code in CIL (Common Intermediate Language) form, which is generated form actual source code and assembly manifest that is a metadata for assembly. It’s practically possible that assembly consist of more than one files e.g. resource file, .netmodule file.
 
Figure 1: [CSharpHelloWorld.dll] Contain assembly manifest and metadata
 
Netmodule File
Netmodule is a unit of compilation. Basically code file is a single module. This is the feature of the specific compiler to compile the source code into assembly or a netmodule. Netmodule only contain type metadata and compiled code (netmodule does not required assembly manifest information). But there is a limitation with netmodule files; it has to be required assembly linking for execution [you can use /addmodule switch of compiler to link the netmodule into assembly].
 
Figure 2: [CSharpHelloWorld.netmodule] Contain only metadata information.
 
Note:-
            Type the following command on Visual Studio Command prompt to generate netmodule file
            csc.exe /t:module HelloWorld.cs                                
            This blog contain only initial level of information. *

Tuesday, August 19, 2008 #

After view and review of dozens of dozens of blogs and articles about SOA I concluded that lot of bloggers and writers still defining SOA (Service Oriented Architecture) definition with their own way and every definition are perfect with the respect of respective environments. I want to define SOA in my own words.

 

“SOA is all about the granularity of Organization IT assets.”

 

If assets are coarse-grained its mean greater flexibility and reusability of assets across different organization department internally and by external business partners as well. In short term all services should be coarse-grained rather then fine-grain. By coarse-grained we achieve loose coupling between services.


Monday, August 11, 2008 #

Analysts and architects should consider the following point when they go for SOA project.
  • Not only create pieces of software (try to break up systems into reusable services). 
  • Select best practices from organizational and technical sides. 
  • Apply new thinking and best practices into project. 
  • Select mature technologies (design models, messaging and architecture services). 
  • Create business-oriented services, later will be utilized in enterprises.

Monday, July 28, 2008 #

Hello geeks after a long gap I come back with a very arousing blog. When ever you see .Net Framework or any Microsoft patterns & practices library configure, they allow the developer to load the external components through some configurations in Web.config or App.Config file and that will be later called by the framework at runtime. Ok let take an example of Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.ILogFormatter Interface that require to format a LogEntry in a way suitable for wire transmission and when you open your configuration file you will find the following key.
 
    <formatters>
      <add template="" type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null"
           name="Text Formatter" />
    </formatters>
 
What that mean, when Enterprise library going to write log it will automatically use the above specify TextFormatter for text logging. Microsoft Enterprise library has the provision for the developer to create custom formatter by implementing ILogFormatter Interface. 
 
Now you have an idea what I am going to implement. Let suppose I have a Theme Configuration management framework for my Windows application and my framework disclose some interfaces for custom implement like IGUIControl. 

namespace ThemeFramework
{
   public interface IGUIControl
   {
      void Render();
      void Draw();
   }
}
If you want to develop a control for my framework you need to implement the IGUIControl interface for creating GUI controls, so it’s also the responsibility of the developer to Implement IGUIControl and configure it so Theme framework get that assembly. Here I only explain the static factory function of my framework that load all define assemblies from configuration file. Generic knowledge is prerequisite. 

public static T[] LoadInstances<T>() where T : class
       {
           //You can use any other way read from configuration file.
           //It utilize the .net 2.0 feature. The main target is to get all assemblies names.
           Settings.Default.Reload();
           StringCollection TypeColl = Settings.Default.Types;
 
           List<T> components = new List<T>();
 
           foreach (string TypeInfo in TypeColl)
           {
               try
               {
                   string[] typeInfo = TypeInfo.Split(',');
                   string assemblyName = typeInfo[1];
                   string typeName = typeInfo[0];
 
                   if (string.IsNullOrEmpty(assemblyName) || string.IsNullOrEmpty(typeName))
                   {
                       continue; // invalid type info
                   }
                   assemblyName = assemblyName.Trim();
                   typeName = typeName.Trim();
 
                   string exeDir = Path.GetDirectoryName(Application.ExecutablePath);
                   if (!File.Exists(Path.Combine(exeDir, assemblyName + ".dll")))
                   {
                       continue; // invalid type information
                   }
 
                   Assembly assem = Assembly.Load(typeInfo[1].Trim());
                   // Dynamic instance creation
                   T instance = assem.CreateInstance(typeInfo[0].Trim()) as T;
                   if (instance != null)
                   {
                       components.Add(instance);
                   }
               }
               catch(Exception ex)                  
               { }
           }
           return components.ToArray();
       }
In preceding code I use Settings.setting class for loading assembly’s names, you can use any other provider to get all custom assemblies names from configuration files. After that I try to find the give assembly in the application execution folder and load it into generic List<T> array.  

IGUIControl[] dogs = FrameworkTest. LoadInstances<IGUIControl>();
         foreach (IGUIControl control in loadControls)
         {
             Control.Draw();
         }
Above code snippet load all assemblies that implement IGUIControl and call it Draw() method to draw the entry control.
 

Wednesday, June 11, 2008 #

Code debugging is one of the most important parts of any development life cycle because it gives you the technique to find the problem and how to resolve it. When we talk about the visual debugging Visual Studio has tremendous potential in the term visual debugging features in the form of DataTips. DataTips tool provide a handy way to view information about your variables in visual studio during debugging only. In old versions of Visual Studio DataTips were limited in the amount of the information they could display. Now in Visual Studio particularly after VS2005 DataTips have been enhanced to give more detail information about the simple and complex variables. By the help of DataTips tool programmer easily visualize different variable data types in their Visualizers.

Visualizer is a new component in Visual Studio debugger user interface that give us a completely new way to view the structure of object or variable in a meaningful way. The first question that comes in your mind is what is actually Visualizer is all about and simple answer of this question is “it’s a dialog box or other interface to display appropriate types in a meaningful way.” Default Visual Studio debugger comes with four standards visulaizers and these are following

Text

HTML

XML visualizer

Dataset visualizer (Dataset, DataTable and DataView objects.)

 

When a debugger variable show a magnifying glass icon on the variable so it’s mean it has an appropriate visualizer.

 

 

In the preceding figure Visual Studio debugger show a DataTable Visualizer when you click the magnifying glass icon debugger show datatable visualizer.

In the following image I want to show image loading in the picture box in debug mode.

 

 

In the above image Visual Studio debugger not able to load image visualizer because there is no visualizer is available.

 

Ok this is an over view of very high level story and now I am going to write custom Image visualizer. Please follow the following steps.

1.       Create a Class Library project in Visual C#.

2.       Name it “VisualDebugger”.

3.       Add following Assemblies References.

a.       Microsoft.VisualStudio.DebuggerVisualizers.dll

b.       System.Drawing.dll

c.       System.Windows.Forms.dll

4.       Rename the class1 to ImageDebugger.cs

5.       Copy the following codes.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Drawing;

using System.Windows.Forms;

using Microsoft.VisualStudio.DebuggerVisualizers;

 

[assembly: System.Diagnostics.DebuggerVisualizer(
typeof(
VisualDebugger.ImageDebugger),
typeof(
VisualizerObjectSource),
Target = typeof(
System.Drawing.Image),
Description =
"Image Visualizer")]

namespace VisualDebugger

{

    public class ImageDebugger : Microsoft.VisualStudio.DebuggerVisualizers.DialogDebuggerVisualizer

    {

        protected override void Show(Microsoft.VisualStudio.DebuggerVisualizers.IDialogVisualizerService windowService, Microsoft.VisualStudio.DebuggerVisualizers.IVisualizerObjectProvider objectProvider)

        {

            System.Drawing.Image image = (Image)objectProvider.GetObject();

 

            Form frm = new Form();

                frm.Text = "Custom Visualizer - " + image.HorizontalResolution.ToString() + " " + image.VerticalResolution.ToString();

                frm.Width = image.Width;

                frm.Height = image.Height;

 

            PictureBox pic = new PictureBox();

                pic.Image = image;

                pic.SizeMode = PictureBoxSizeMode.AutoSize;

              

            frm.Controls.Add(pic);

            frm.ShowDialog();

        }

    }

}

 

Class should be inherited from Microsoft.VisualStudio.DebuggerVisualizers.DialogDebuggerVisualizer and overrider the Show() method of DialogDebuggerVisualizer class to display your custom interface. The next most important and vital part of this visualizer is IVisualizerObjectProvider parameter because you going to caste this interface into apporipate type and in my case it is System.Drawing.Image class(it could be any thing like XML document, your specific class). I used System.Windows.Form class to host my picture box control. One thing that you should keep in mind is apply DebuggerVisualizerAttribute on your class.

 

Note:
First parameter is your custom class, Second parameter is your visualizer source, Third parameter is target object type like XML Document and last is the description of visualizer.

 

Deployment of Visualizer

Copy the DLL to either of the following locations:

Install path\Microsoft Visual Studio 9\Common7\Packages\Debugger\Visualizers\

—or—

My Documents\Visual Studio 2008\Visualizers\

 

Test Visualizer

1.       Create a new application of Windows Forms Application

2.       Give it name

3.       And write the following code.

 

            Image img = Image.FromFile(@"C:\Documents and Settings\sullah\My Documents\My Pictures\ozzie1.jpg");

            PictureBox pic = new PictureBox();

            pic.Image = img;

 

4.       Set the Breakpoint on pic.Image = img;

 

Following are the outputs.

 


You can clearly see the new Image Visualizer in the preceding image and click on the magnifying glass icon and get output.

 

 


Thursday, June 05, 2008 #

I found a bug in Visual Studio 2008 SP 1 when I installed it on my VS 2008. Basically the problem is when you install VS 2008 SP 1 its override the setting of your Visual Studio 2008 and set to default setting.
 
Solution:
The solution of this problem is very simple you first export the setting of Visual Studio 2008 from Tools-> Imports and Exports Setting and save it on your desire location. Install the Visual Studio 2008 SP1 on VS 2008 and imports the setting again into VS 2008.

Oop .NET Framework Client Profile was a great reply from .Net team because it’s full fill the need of those customers how are wary and ask questions from Microsoft for small .Net framework for its client application deployment. One thing that I want mention here is .Net Framework Client Profile is a subset of .Net 3.5 and it’s available in .Net Framework 3.5 SP1. Download .Net Framework Client Profile is came into begin with following things keep in minds.

  • Small framework runtime.
  • Smart, faster application deployment.
  • Client Application focused feature set:

o    Common Language Runtime (CLR)

o    ClickOnce  application deployment

o    Windows Forms

o    WPF

o    WCF



Fig.1 .Net Framework Client Profile

Beta release of .Net 3.5 Sp1 contains the following assemblies in the Client Profile.

·          BCL, "Core FX," and LINQ

CustomMarshalers
ISymWrapper
mscorlib
sysglobl
System
System.AddIn
System.AddIn.Contract
System.Configuration
System.Configuration.Install
System.Core
System.Security

·          Visual Basic and Visual C++ Language Support

Microsoft.VisualBasic
Microsoft.VisualC

·          XML

System.Xml
System.Xml.Linq

·          Windows Forms

Accessibility
System.Drawing
System.Windows.Forms

·          WPF

PresentationCore
PresentationFramework
PresentationFramework.Aero
PresentationFramework.Classic
PresentationFramework.Luna
PresentationFramework.Royale
PresentationUI
ReachFramework

System.Printing
System.Windows.Presentation
UIAutomationClient
UIAutomationClientsideProviders
UIAutomationProvider
UIAutomationTypes
WindowsBase
WindowsFormsIntegration

·          ClickOnce

System.Deployment

·          WCF, Web Services, Remoting, and Serialization

System.IdentityModel
System.Runtime.Remoting
System.Runtime.Serialization
System.Runtime.Serialization.Formatters.Soap
System.ServiceModel
System.ServiceModel.Web
System.ServiceModel.Install
System.Transactions
System.Web.Services

·          Data Access

System.Data
System.Data.SqlXml
System.Data.DataSetExtensions
System.Data.Services.Client

·          Peer to Peer

System.Net

·          Active Directory and Enterprise Services

System.DirectoryServices
System.EnterpriseServices

Above assemblies are necessary assemblies for any .Net application, so that why all of them are available in .Net Framework Client Profile  according to the .Net team.