softwaregreenhouses.com Blog

February 1, 2008

Handling .NET Assembly Licenses (.licx, .license) Dynamically at Runtime

Filed under: .LICX, ComponentModel, Licensing — Marty Nelson @ 10:30 pm

One of the frustrating things about the .NET licensing system is that although you can embed the licenses into a non-executable assembly, they will not be loaded and recognized at runtime.  The must also be embedded into the running executable.

This can be a real hassle if you are loading types dynamically from dll’s that may contained valid licensed third-party components.

After experimenting a bit, deugging through the LicenseManager, LicenseContext, and other .NET classes using the new nifty VS2008 source files, here is a simple solution that works.  And we didn’t even need to use Reflection :) .

It turns out that when you call GetSavedLicenseKey() on the statically scoped CurrentContext LicenseContext class, it actually reads the embedded licenses keys from the supplied resource assembly and stores them.

Assembly assembly = Assembly.LoadFrom(@”C:\Your\assembly\path”);

LicenseManager.CurrentContext.GetSavedLicenseKey(typeof(string), assembly);

Notice that the type doesn’t matter, it just needs to be a non-null value.  Of course if you have the type, you may end up writing something more like:

Type type = Type.GetType(typeName);

LicenseManager.CurrentContext.GetSavedLicenseKey(type, type.Assembly);

//This will not throw a licensing exception:

object instance = Activator.CreateInstance(typeName);

Enjoy…

Powered by WordPress