ResolveEventHandler handler = new ResolveEventHandler(LicenseCompiler.OnAssemblyResolve);
AppDomain.CurrentDomain.AssemblyResolve += handler;
对第一部参数分析出来的组件列表,依次循环,为它们产生授权许可
复制代码 代码如下:
DesigntimeLicenseContext creationContext = new DesigntimeLicenseContext();
foreach (string str in compLists)
{
key = reader.ReadLine(); hashtable[key] = Type.GetType(key); LicenseManager.CreateWithContext((Type) hashtable[key], creationContext);
}
最后,生成许可文件并保存到磁盘中,等待CSC编译器将它编译成资源文件,嵌入到程序集中。
复制代码 代码如下:
string path = null;
if (outputDir != null)
{
path = outputDir + @"\" + targetPE.ToLower(CultureInfo.InvariantCulture) + ".licenses";
}
else
{
path = targetPE.ToLower(CultureInfo.InvariantCulture) + ".licenses";
}
Stream o = null;
try
{
o = File.Create(path);
DesigntimeLicenseContextSerializer.Serialize(o, targetPE.ToUpper(CultureInfo.InvariantCulture), creationContext);
}
finally
{
if (o != null)
{
o.Flush();
o.Close();
}
}
这种方式是.NET Framework推荐的保护组件的方式,与我们平时所讨论的输入序列号,RSA签名不同。
来看一下,商业的组件是如何应用这种技术保护组件的。
复制代码 代码如下:
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
namespace ComponentArt.Licensing.Providers
{
#region RedistributableLicenseProvider
public class RedistributableLicenseProvider : System.ComponentModel.LicenseProvider
{
const string strAppKey = "This edition of ComponentArt Web.UI is licensed for XYZ application only.";
public override System.ComponentModel.License GetLicense(LicenseContext context, Type type, object instance, bool allowExceptions)
{
if (context.UsageMode == LicenseUsageMode.Designtime)
{
// We are not going to worry about design time Issue a license
return new ComponentArt.Licensing.Providers.RedistributableLicense(this, "The App");
}
else
{
string strFoundAppKey;
// During runtime, we only want this control to run in the application
// that it was packaged with.
HttpContext ctx = HttpContext.Current;
strFoundAppKey = (string)ctx.Application["ComponentArtWebUI_AppKey"];
if(strAppKey == strFoundAppKey)
return new ComponentArt.Licensing.Providers.RedistributableLicense(this, "The App");
else
return null;
}
}
}
#endregion
#region RedistributableLicense Class
public class RedistributableLicense : System.ComponentModel.License
{
private ComponentArt.Licensing.Providers.RedistributableLicenseProvider owner;
private string key;
public RedistributableLicense(ComponentArt.Licensing.Providers.RedistributableLicenseProvider owner, string key)
{
this.owner = owner;
this.key = key;
}
public override string LicenseKey
{
get
{
return key;
}
}
public override void Dispose()
{
}
}
#endregion
}
首先要创建一个类型,继承于License类型,再创建一个继承于LicenseProvider的类型,用于颁发许可证,包含在设计时许可和运行时许可,从上面的例子中可以看到,设计时没有限制,可以运行,但是到运行时,你必须有序列号,它才会生成许可对象,而不是返回null给.NET Framework类型。整个验证过程由.NET完成。
你只需要像下面这样,应用这个许可保护机制:
复制代码 代码如下: