提供北人写过的一段代码:许可,就是自己已经开发出服务器控件,怎样给正版用户使用,保护自己的开发成果。如可以使用日期限制,服务器域名限制,甚至服务器Cpu序列号,网卡序列号,硬盘序列号限制。我想这个功能大家都比较感兴趣。下面谈一下研究的心得,希望感兴趣的人可以继续研究下去。首先是名称空间:System.ComponentModel
接着是使用的类,微软提供了两个抽象类License,代表许可证,和LicenseProvider类,代表许可证的实现。这两个类都必须继承,以实现自己的功能。下面是一个简单的许可证实现例子:我开发了一个自定义服务器控件,功能非常强大。但是我不确认里面是否有bug,那么必须发布测试版。测试版没有功能限制(为了发现bug),但是有时间限制,我们假定在2003年10月1日到期,到期后这个测试版就不能用了。
PS:实际上这个功能可以在控件的OnInit内实现,一个判断就可以了,为了说明的清晰,我使用了日期判断。
以下是代码:
首先我们建立一个许可证的实例类,继承System.ComponentModel.License类,必须重写两个方法。
public class MyLicense : System.ComponentModel.License
{
    //指定许可证提供者,代码后面写
    private Sanxing.Mail.LicenseProvider owner;
    //指定许可证密钥,此密钥可以加密
    private string key;    //构造函数
    public MyLicense(Sanxing.Mail.LicenseProvider owner, string key)
    {
        this.owner = owner;
        this.key = key;
    }    //返回许可证密钥,定义属性
    public override string LicenseKey
    {
        get
        {
            return key;
        }
    }    //重写Dispose()
    public override void Dispose()
    {
        //无内容
    }
}
//- 下面是许可证提供者,主要用于判断是否发出许可证
//  许可证有两种方式,设计时和运行时,我们主要考虑运行时许可
public class class LicenseProvider : System.ComponentModel.LicenseProvider
{
    //定义到期时间
    private System.DateTime stop = new DateTime(2003,10,1);    //主要验证逻辑,负责判断并且返回合适的许可证
    public override System.ComponentModel.License GetLicense(LicenseContext context, Type type,object instance, bool allowExceptions)
    {
        //首先判断是否是设计时
        if (context.UsageMode == LicenseUsageMode.Designtime)
        {
             return new Sanxing.Mail.License(this,"+OK");
        }
        else
        {
             //获得目前时间
    System.DateTime now = System.DateTime.Now;
    //与规定时间比较
    int j = DateTime.Compare(now,stop);
    if (j < 0)
    {
//未过期
return new Sanxing.Mail.License(this,"+OK");
    }
    else if (j == 0)
    {
//时间相等
return new Sanxing.Mail.License(this,"+OK");
    }
    return null;
}
    }
}上面我已经建立了许可证,现在该使用了,使用非常简单
假设我们定义一个web控件,添加一个属性即可using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.Design; 
using System.ComponentModel;[LicenseProviderAttribute(typeof(LicenseProvider))
public class myWebControl: System.Web.UI.WebControls.WebControl
{
    public override Render(HtmlTextWriter output)
    {
        output.Writer("你好!");
    }
}只要在设计时属性中加入LicenseProviderAttribute即可。所有的功能由.net设计时调用。总结:
只要我们在GetLicense的重写方法内使用足够的判断逻辑,我们就可以使用强大的验证功能。
举个例子:我们可以使用Key文件的方式确认用户身份,我们可以建立一个key.config的xml格式文件,把要使用的用户的网卡序列号进行加密后写入此文件中,然后判断,如果合法,则发出正确的License,否则将引发LicenseException。
把这个方法扩展开去,我们可以对建立的Windows应用程序和Web应用程序同样可以适用此方法。