New* .NET 3.5 Feature: AddIn Framework Resources (Part 2 of 2)

I was starting to write a 3 part series on the new AddIn Framework in .NET 3.5. However I came across some resources which makes me end this series and rather point to those posts and articles since they have already described it so nicely. Here are the articles and blog posts

MSDN Magazine : CLR Inside Out : .NET Application Extensibility by Jack Gudenkauf and Jesse Kaplan

This MSDN article introduces the concept of System.Addin namespace concepts and how it is structured. This actually provides

MSDN Magazine : CLR Inside Out : .NET Application Extensibility Part 2  by Jack Gudenkauf and Jesse Kaplan

This is the second article of the extensibility series that describes the pipeline architecture that was used, each of the components and how it is implemented. A must read anyone who wants to implement the addin model.

How To: Build an Add-In using System.AddIn by Guy Burstein

This is the practical hands on example with code examples and many screenshots. A tutorial cannot get any better than this. A must visit to the addin implementer. Make sure you visit this article, this is written by a tech evangellist at Microsoft.

CLR Add-In Team Blog

This is the .NET based blog of the people who made the framework and contains many inside information you may not find in the documentation. It is a nice place to visit every once in a while.

Everything you need to know to get started with System.AddIn by James Green

This is another good start point for addin examples with visual diagrams.

kick it on DotNetKicks.com


New* .NET 3.5 Feature: AddIn Framework ( Part 1 of 2 )

2ne of the new items that were included in the .NET 3.5 framework is a built in way to add extensibility to your application using add-ins, also known as plug-in. Many of us have already added extensibility in our own application using interfaces. However this framework comes with a few built in features for addin lifetime management, security isolations etc.

Sandbox Isolation

If we want to add termination features to an addin we would need to load it to to different appdomain since we may want to unload it or reload it when any error happens. Also when the addin runs in a separate domain space it is less likely to corrupt any part of the application.

sandbox

Please also note that when an addin is unloaded, the unloading causes the other assemblies to be unloaded as well on which the addin is dependent upon. This happens because the AppDomain is unloaded.

Discovery

The new framework also supports discovery of addins within a folder. Also you can also search for a certain addin. According to the documentation each addin has its own folder and its own set of assemblies.

Security

The security of the sandboxed addin can be created when we create the application domain for the addin to run on or we can even use the policy level security to control the addin behavior.

Versioning

Versioning is provided via contract isolation, both the addin host and the addin itself can version independently of each other. A concept of adapter assembly is present for both the add in and the host so that the implementation can change independently.

Termination

Due to running the addin in different AppDomain boundary termination of the AppDomain automatically clears memory and all other resources. However if we needed to do this manually then we would have to find the application domain that hosts the assembly and unload it. The framework provides a nifty class to unload the addin and its AppDomain

AddInController.GetAddInController(addin).Shutdown();

Next

Related Post:

Dll heaven: Executing multiple versions of the same assembly

kick it on DotNetKicks.com


Dll heaven: Executing multiple versions of the same assembly

Everyone wants their application to be backward compatible and if the application is based on a plug-in based architecture then such a feature can be a nice addition. When can such a feature be useful? Suppose we have a plug-in subsystem which we have upgraded to newer plug-in system and we want to support older systems.

So if we want to load 2 different versions of a same assembly what do we need to do?First, each version needs to be loaded into 2 different AppDomains.

Why ?

Because when an assembly is loaded it cannot be unloaded so if we have 2 different assemblies once a type has been loaded from one of them, it will be reused each time we want to instantiate a type. But an assembly loaded into an AppDomain can be unloaded by unloading the AppDomain itself. I am going to demonstrate how to load 2 versions of the same assembly into same executable and run them simultaneously.

Example Step 1: In order to make it simple and avoid the reflection trouble I am going to create an interface and put it into a dll and reference the interface to the concrete dll. So here is code for the interface class in a simple dll that will be used to invoke methods.

namespace InterfaceLib
{
    public interface IExecute
    {
        string Execute();
    }
}

Example Step 2:I will build this into a single dll and then reference it to the interface. We need to make the class inherit from MarshalByRefObject since we want to communicate across AppDomains.

namespace AssemblyVersionTest
{
    public class SimpleClass : MarshalByRefObject,
        InterfaceLib.IExecute
    {
        public string Execute()
        {
            return "This is executed from version 1";
        }
    }
}

So we have a class that is referenced from MarshalByRefObject and implement our interface. Lets compile this dll and after doing so ... take the dll and rename it to AssemblyVersionTest1.dll

Lets now change this line

return "This is executed from version 1;

to

return "This is executed from version 2";

Then again compile the dll and rename it to AssemblyVersionTest2dll

Example Step 3:Now we come to our third application, the console executable. Lets put the 2 versions of the dll to the bin path of the console executable and use the following code

// Create an app domain
AppDomain appDomain1 = AppDomain.CreateDomain("Version1");
// Instantiate the object from the app doamin and the first version file
object obj= appDomain1.CreateInstanceFromAndUnwrap(
    AppDomain.CurrentDomain.BaseDirectory + "\\AssemblyVersionTest1.dll",
    "AssemblyVersionTest.SimpleClass");
IExecute iex = (IExecute)obj;

// Instantiate the object from the app doamin and the second version file
AppDomain appDomain2 = AppDomain.CreateDomain("Version2");
object obj2 = appDomain2.CreateInstanceFromAndUnwrap(
    AppDomain.CurrentDomain.BaseDirectory + "\\AssemblyVersionTest2.dll",
    "AssemblyVersionTest.SimpleClass");
IExecute iex2 = (IExecute)obj2;

Console.WriteLine(iex.Execute());
Console.WriteLine(iex2.Execute());

Now observe that we have had renamed the different versions of the dlls and loaded them explicitly. The output of the above code should be ...

This is executed from version 1
This is executed from version 2

Now we can see that the domains have loaded 2 different versions of the same class in the same executable and executed them.

kick it on DotNetKicks.com


WeakReference: GC knows the Best

When I first read about weak references in .NET more than 5 years ago back my first thought was to use it for Caching. The concept was already present in Java before .NET since Java had garbage collection before. Still today I don't see many developers using this awesome class.

What is a Weak Reference?

We all know that garbage collectors start cleaning memory for objects that do not have any reference. A weak reference is a way to have some pointer to an object that does have any reference (strong reference). When we need to access a weak referenced object we can just check if the object is alive and then access it if the object is alive at all. Since .NET is a garbage collection based runtime environment, like all GC based runtimes it does not immediately clean up the memory allocated for the instantiated objects. 

Why should we use it?

Not having a strong reference to the object but at the same time having a pointer to the object enables this class to be well suited for caching. 

When to use Weak Reference?

Since GC executes when there is memory pressure and cleans objects that are in memory. At the same time if memory and processing is expensive for your application then you can reduce pressure on memory and processing at the same time. Let try an example ... 

Lets assume that we have an object that contains is 500KB of data and when we fetch it it quite expensive to get because of the IO operation required to fetch it from database and we need to validate it with some rule. And at the same time we have to have 1000 of these objects instantiated with different sets of data. 

We can use traditional cache but that would use too much memory or we can fetch the instance each time for database. Both solutions have its own flaw. The first uses too much memory and the second one uses too much processing. This would be the best solution to use weak reference 

There are 2 cases possible when we need to access any instance of the object in question 

1. It may not be garbage collected: So the object is still in memory and we can associate a strong reference to it and use it. This saves performance but uses memory without any extra pressure since GC takes the best decision when to collect. 

2. It may have been collected and does not exist anymore: In this scenario we will fetch the object again. So we would be using processing power. The memory pressure was high and GC decided to collect and our onject went with that so we need to fetch the object again. Here again we are letting GC decide when the memory pressure is enough that we would to a high processing action. 

So the basic belief behind WeakRefernce is that "GC knows best". It will clean up memory when needed and we puny humans should respect its decision on memory management. 

How to use WeakReferences?

All you need to do is create a WeakReference class with the object in question passed into the constructor. Keep a storng refence to the weak reference object. When need later then check if obect is alive by checking 'IsAlive' property and then use it. The code sample below shows the lifetime of an object when using a weak reference ...

// Create the object
Book book = new Book("My first book", "Me");
// Set weak reference
WeakReference wr = new WeakReference(book);
// Remove any reference to the book by making it null
book = null;

if (wr.IsAlive)
{
    Console.WriteLine("Book is alive");\
    Book book2 = wr.Target as Book;
    Console.WriteLine(book2.Title);
    book2 = null;
}
else
    Console.WriteLine("Book is dead");
            
// Lets see what happens after GC
GC.Collect();
// Should not be alive
if (wr.IsAlive)
    Console.WriteLine("Book is alive");
else
    Console.WriteLine("Book is dead");

The output should be

Book is alive
My first book
Book is dead

So folks ... that all about weak references.

kick it on DotNetKicks.com


Controlling Windows Firewall using C# via COM Interop

Firewall Windows firewall is the built in firewall that ships with Windows XP and Windows Vista. This firewall can be controlled from any .NET language via COM interop. The windows firewall UI is a little clumsy to work with so anyone can make his own frontend using any .NET based language.

Setting up

Start by adding a reference to the COM dll that provides the functionality to control the windows firewall. The filename is hnetcfg.dll which can be found at the system32 folder inside windows. So add the file to your C# project.

File location: \Windows\System32\hnetcfg.dll
Then add these using statements to import the COM Objects

using NATUPNPLib;
using NETCONLib;
using NetFwTypeLib;

Obtaining a reference to the firewall manager

The first step toward controlling the windows firewall is to obtain a reference to the firewall manager class. For this we will use the CLSID of the class which is

   {304CE942-6E39-40D8-943A-B913C40C9CD4}

So our code looks like this

private const string CLSID_FIREWALL_MANAGER = 
      "{304CE942-6E39-40D8-943A-B913C40C9CD4}";
private static NetFwTypeLib.INetFwMgr GetFirewallManager()
{
    Type objectType = Type.GetTypeFromCLSID(
          new Guid(CLSID_FIREWALL_MANAGER));
    return Activator.CreateInstance(objectType)
          as NetFwTypeLib.INetFwMgr;
}

The above code shows how to get a reference to the firewall manager

Check if the firewall is turned on

If the firewall is not turned we should look into the current profile and find out then turn it on.

INetFwMgr manager = GetFirewallManager();
bool isFirewallEnabled =
    manager.LocalPolicy.CurrentProfile.FirewallEnabled;
if (isFirewallEnabled==false)
    manager.LocalPolicy.CurrentProfile.FirewallEnabled=true;

Give full trust to your executable

If we want to authorize some application with full trust then we need to create a FirewallAuthorizedApplication (INetFwAuthorizedApplication) object and add it to the authorized application list.

// ProgID for the AuthorizedApplication object
private const string PROGID_AUTHORIZED_APPLICATION =
    "HNetCfg.FwAuthorizedApplication";

public bool AuthorizeApplication(string title, string applicationPath,
    NET_FW_SCOPE_ scope, NET_FW_IP_VERSION_ ipVersion )
{   
  // Create the type from prog id
  Type type = Type.GetTypeFromProgID(PROGID_AUTHORIZED_APPLICATION);
  INetFwAuthorizedApplication auth = Activator.CreateInstance(type)
      as INetFwAuthorizedApplication;
  auth.Name  = title;
  auth.ProcessImageFileName = applicationPath;
  auth.Scope = scope;
  auth.IpVersion = ipVersion;
  auth.Enabled = true;

  INetFwMgr manager = GetFirewallManager();
  try
  {
    manager.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(auth);
  }
  catch (Exception ex)
  {
    return false;
  }
  return true;
}

The above code is for a function that adds an authorized application. Let see the use by authorizing notepad full internet access!

AuthorizeApplication ("Notepad", @"C:\Windows\Notepad.exe", 
                NET_FW_SCOPE_.NET_FW_SCOPE_ALL,
                NET_FW_IP_VERSION_.NET_FW_IP_VERSION_ANY)

Walla! Now notepad has internet access.

Opening a Port Globally

Sometimes we may want to open a port for any application no matter what. Windows Firewall can be instructed to open a port globally for all applications by adding a port to the globally open ports list. Let try to write a function that opens up a port globally ...

private const string PROGID_OPEN_PORT = "HNetCfg.FWOpenPort";
public bool GloballyOpenPort(string title, int portNo,
    NET_FW_SCOPE_ scope, NET_FW_IP_PROTOCOL_ protocol,
    NET_FW_IP_VERSION_ ipVersion)
{
  Type type = Type.GetTypeFromProgID(PROGID_OPEN_PORT);
  INetFwOpenPort port = Activator.CreateInstance(type)
      as INetFwOpenPort;
  port.Name = title;
  port.Port = portNo;
  port.Scope = scope;
  port.Protocol = protocol;
  port.IpVersion = ipVersion;

  INetFwMgr manager = GetFirewallManagerCached();
  try
  {
    manager.LocalPolicy.CurrentProfile.GloballyOpenPorts.Add(port);
  }
  catch (Exception ex)
  {
    return false;
  }
  return true }

Going further

Since we have demonstrated how to access the windows firewall manager and control its various aspects, now anyone can explore the Windows Fireall API and do a lot more that presented in this post. I would like to point to several MSDN references for further read.

MSDN Windows Firewall Reference
Loads of VBScript samples to do various things, you can translate the code to C#

Since windows firewall can be controlled via COM, any application running in your system can enable/disable or modify the firewall settings. I would suggest to use a third party firewall. For real security geek I would recommend Outpost Firewall ( I use the Outpost Security Suite) as the paid firewall and Comodo Personal Firewall as the best free firewall. Both these firewalls are way superior to other available firewalls.

kick it on DotNetKicks.com

Web 2.0 Bubble

Got this video from someone ... the perfect description of web 2.0 phenomena. I love this ... this guy has taken words out of my mouth and put in his video.

Independent Thought

The certificate of 925-201b hold questions about principles of network security and fortigate configurations. On the other hand, 70-624 certifications belong to deploying and maintaining vista client and office system 2007. E22-128 training question belongs to EMC technology fundamentals and is a very essential course. Whereas, E20-570 also belongs to the EMC technology but hold more advance questions. HH0-110 certification belongs to the Hitachi data storage foundation and person need 65% marks in order to pass the exam. EC0-350 holds all the questions related to ECCOUNCIL Ethical Hacking and Countermeasures.


Fun with Generics: Using constraints to limit Generics applicability using the 'where' keyword

Generics was introduced in .NET with version 2.0. One feature that is very useful but rarely used is the constraints for Generics. Constraints allows the developer to limit the type that is used instead of any object. Let us try to understand this with a sample. Lets assume that we have a in memory cache class for a certain type of object which we will simulate in the sample using a dictionary. Lets look at the code sample

class MyCache<K, T>
{
    Dictionary<K, T> _store = new Dictionary<K ,T>();
    void CacheItem(K key, T obj)
    {
        _store[key] = obj;
    }

    T GetFromCache (K key)
    {
        if (_store.ContainsKey(key))
            return _store[key];
        else
            return default(T);
    }
}

Generics constraint for Reference Type

The above class looks pretty simple and easy to use. Now lets assume that we want to cache classes that are reference types and this MyCache class should not be use with any struct or value types. How can we do that? Here is how ...

class MyCache<K, T> where T: class

This 'where' keyword is telling the compiler that MyCache type can by applied on the reference types only.

Generics constraint for Value Type

Similarly we would use the following syntax for structs

class MyCache<K, T> where T: struct

Generics constraint for a specific interface

What if we have a specific requirement for the type to be disposable? For example when cache is disposed we want all the items that are in  the cache to be disposed as well. If we had no constraints in MyCahe class then we would have to write

public void Dispose()
{
    foreach (K key in _store.Keys)
    {
        IDisposable d = _store[key] as IDisposable;
        if (d != null) d.Dispose();
    }
}

Observe that we are casting to disposable type and then disposing the object. What if someone had used a type that does not implement IDisposable? Lets try to impose a constraint that says the the type T must be disposable.

class MyCache<K, T> : IDisposable where T:IDisposable

... and our dispose code should look like this ...

public void Dispose()
{
    foreach (K key in _store.Keys)
    {
        _store[key].Dispose();
    }
}

Please observe that since we have specified that the type T is a IDisposable type we can directly call the Dispose method.

Generics constraint on multiple types

Now suppose that I have a class named EntityBase that we are using for all our entity classes and the functionality of the MyCache to apply to the entity classes only. How do we tell generics to restrict MyCache to classes that derive from EntityBase and implements IDisposable? This is how ...

class MyCache<K, T> : IDisposable 
      where T:EntityBase, IDisposable

In the above code we are saying the that the type T must be subclass of EntityBase class and must be disposable. Please note that we would also be able to call methods and properties of the EntotyBase class directly without explicit casting as we have already shown in the disposable example.

Generics constraint on multiple items

What if we wanted the the key to always a value type? Let try to add that to our definition.

class MyCache<K, T> : IDisposable 
      where K:struct
      where T:EntityBase, IDisposable

Specifying a default constructor

Sometimes we might want to write code like new T() to instantiate a variable of type T. This will not work if the class do not have a default constructor. In order to make sure that T has such a default constructor we would write ...

class MyCache<K, T> : IDisposable 
     where K:struct
     where T:EntityBase, IDisposable, new()

The new() keyword will make sure that the T has such a default constructor, otherwise it will not compile.

An interesting tip : Aliasing

We can also use aliases to use generic types in our classes. Sometimes too much generic expression makes the code look bad with lots of <> and <>. This can be avoided via aliasing. You can give a alias or name to a certain generic type and use it from the class. See example below

using StringQueue = System.Collections.Generic.Queue<string>;

Here we are making a generic Queue class bound with string to be named as StringQueue which later used in code like this ...

StringQueue queue = new StringQueue();
queue.Enqueue("Sometext");

Fun, isn't it?

The Last Word

Unfortunately the above feature of generics is usually overlooked and rarely used in code. Better OO design can result from using these features. Lets try to use this when we design object model in our daily life.

kick it on DotNetKicks.com


Internationalization: Creating a custom culture

.NET Runtime ships with several languages and support for creating a custom language. But the Operating System or the .NET did not have built in support for my native language "Bangla". In order to implement Bangla in my program I had to create a custom culture and write the resource files for that custom language. Once a language has been created and registered it does not need to be created again. So in a windows PC the registration code should run only once. See the code below which shows how to achieve this by using CultureAndRegionInfoBuilder class.

CultureAndRegionInfoBuilder builder =new CultureAndRegionInfoBuilder("bn",
              CultureAndRegionModifiers.Neutral);

// there is no neutral Bengali culture to set the parent
builder.Parent = CultureInfo.InvariantCulture;
builder.CultureEnglishName = "Bengali (Bangladesh)";
builder.CultureNativeName = "বাংলা";
builder.ThreeLetterISOLanguageName = "ben";
builder.ThreeLetterWindowsLanguageName = "ben";
builder.TwoLetterISOLanguageName = "bn";
builder.IetfLanguageTag = "bn-BD";
builder.KeyboardLayoutId = 1081;
builder.TextInfo = CultureInfo.InvariantCulture.TextInfo;
builder.CompareInfo = CultureInfo.InvariantCulture.CompareInfo;

// Register the culture
builder.Register();

How do use this custom culture in our code? Here is how ...

Thread.CurrentThread.CurrentCulture = 
         CultureInfo.CreateSpecificCulture("bn");
Thread.CurrentThread.CurrentUICulture = new CultureInfo("bn");
This should be done before loading the UI. I am assuming that the reader know all about custom resource files and how to use them

kick it on DotNetKicks.com


In love with Enso: C# Plugin framework for Enso with sample text replace plugin

I have fallen in love with Enso, which is an application launcher and much more from Humanized, Inc. It has potential to do so much more than application launch ... it is a awesome productivity enhancer. It takes me a 3 seconds to do stuff that took half a minute. It is better than Launchy and the other products on the market. It is like Quicksilver for windows. I have decided to write my own plugins for Enso and within a few hours did so.

In order to write this extension I needed to find the extension API which was located here. Also you need to download the Enso Developer prototype ( still at version 0.1.1). Unfortunately there was no SOAP support at the moement, all I found was the Xml-Rpc procedures. So I looked for a Xml Rpc library written in .NET and found Cook computings open source implementation at http://www.xml-rpc.net/.

The first step was to create a class that could access all of Enso's exposed functions. The following class below is the proxy class for the Xml-Rpc support in Enso.

public interface IEnso: IXmlRpcProxy
{
    [XmlRpcMethod("displayMessage")]
    bool DisplayMessage (string text);

    [XmlRpcMethod("getFileSelection")]
    string[] GetFileSelection();

    [XmlRpcMethod("getUnicodeSelection")]
    string GetUnicodeSelection();

    [XmlRpcMethod("insertUnicodeAtCursor")]
    void InsertUnicodeAtCursor(string text, string fromCommand);

    [XmlRpcMethod("registerCommand")]
    bool RegisterCommand(string url, string name, string description, string help, string postfixType);

    [XmlRpcMethod("setCommandValidPostfixes")]
    bool SetCommandValidPostfixes(string url, string name, string postfixes);

    [XmlRpcMethod("setUnicodeSelection")]
    bool SetUnicodeSelection(string text, string fromCommand);

    [XmlRpcMethod("unregisterCommand")]
    bool UnregisterCommand(string url, string name);
}

Then I wrapped a nice class called 'EnsoControl' around the proxy. Now to make an extension ...

Now our extension must implement a method that is invoked by Enso when the command is typed by the user. The interface looks like the one below ..

 public interface IEnsoExtension
 {     [XmlRpcMethod("callCommand")]     void callCommand(string name, string postfix);
 }

The extension needs to implement this method in our class.

Try seeing the sample class inside the extension framework zip file which provides a simple replacement command in Enso. Also I had to add an http handler ( details are in the Xml Rpc site) to server the XmlRpc calls.

You can download the source code for Download EnsoExtension.zip .

See the Enso sample replacement extension in action

kick it on DotNetKicks.com

Threading posts temporarily discontinued

I have started a five part series of posts on threading in .NET and the first part was published. But it seems that there is a free web e-book available on threading. So I have decided to postpone the posts on threading. Instead I will be posting on new stuff on .NET and whatever interesting stuff I stumble on.

Independent Thought

Now, online companies offer 000-890 question packages that hold similar questions that are asked in IBM certification. Other than IBM, Citrix certification 1Y0-327 is also provided which hold 66 questions that can be answered in 90 minutes. Solaris 310-302 on the other hand is different from above given certificates and that is due to the difference in questions. Novel 50-686 certification is similar to the certification of IBM holding computer based questions. The 642-533 is the IPS Implementing Cisco Intrusion Prevention Systems exam which is associated with the Cisco Certified Security Professional certification. Whereas, 70-229 is the MCSD.NET SQL Server 2000 Design exam which includes 409 questions, and 178 study notes. Adobe technology introduces 9A0-045 training.