一、目的:在开发过程中,定义许可验证的方式有很多,下面演示系统自带的许可验证的使用方法
LicenseProvider 是 .NET 框架中的一个类,用于实现组件和控件的许可机制。它允许开发者为自定义控件或组件添加许可验证,以确保只有授权用户才能使用这些控件或组件。
如何使用 LicenseProvider
1. 创建自定义的 LicenseProvider:你需要继承 LicenseProvider 类并实现其 GetLicense 方法。
2. 应用 LicenseProvider:在你的自定义控件或组件上应用 LicenseProvider 特性。
3. 验证许可:在控件或组件的构造函数中验证许可。
LicFileLicenseProvider 是 .NET 框架中的一个内置类,用于从许可文件中读取和验证许可信息。它简化了许可验证的过程,使你不必手动实现从文件读取和验证许可的逻辑。
二、实现
首先,定义一个自定义控件MyButton
添加LicenseProvider特性,类型设置为自带LicFileLicenseProvider,
使用LicenseManager.Validate进行验证
[LicenseProvider(typeof(LicFileLicenseProvider))]
public class MyButton : Button
{
public MyButton()
{
using (License license = LicenseManager.Validate(typeof(MyButton), this))
{
System.Diagnostics.Debug.WriteLine("许可验证成功");
}
}
}
在窗口添加程序
<Grid>
<local:MyButton Content="License"/>
</Grid>
此时运行程序,当创建MyButton时验证许可提示错误,如下:
然后,添加许可文件到根目录
内容如下:
再运行程序,此时运行通过
自定义扩展LicFileLicenseProvider
/// <summary>
/// 自定义LicFileLicenseProvider
/// </summary>
public class MyLicFileLicenseProvider : LicFileLicenseProvider
{
/// <summary>
/// 检查密钥是否有效
/// </summary>
protected override bool IsKeyValid(string key, Type type)
{
return base.IsKeyValid(key, type);
}
protected override string GetKey(Type type)
{
return base.GetKey(type);
}
/// <summary>
/// 获取组件实例的许可证并确定其是否有效
/// </summary>
/// <returns></returns>
public override License GetLicense(LicenseContext context, Type type, object instance, bool allowExceptions)
{
return base.GetLicense(context, type, instance, allowExceptions);
}
}
通过自定义扩展LicFileLicenseProvider或LicenseProvider可以自定义许可文件密钥规则(Mac地址,网卡,许可截止日期等),和文件路径规则(保存在文档目录或服务器目录等其他目录,默认在程序集根目录)
注意事项
• 许可验证逻辑:在 IsValidLicense 方法中实现你的许可验证逻辑。你可以从文件、数据库或其他存储中读取许可信息,并进行验证。
• 异常处理:在 GetLicense 方法中,如果许可验证失败且 allowExceptions 为 true,应抛出 LicenseException 异常。
• 资源管理:确保在控件或组件的 Dispose 方法中正确释放许可资源。
通过上述步骤,你可以为自定义控件或组件添加许可验证机制,确保只有授权用户才能使用它们。
总结
1.在需要许可的类型上增加特性
[LicenseProvider(typeof(LicFileLicenseProvider))]
2.在应用程序根目录添加许可文件
H.Test.Demo5.MyButton.lic 内容以“H.Test.Demo5.MyButton is a licensed component.”开头
3.在需要验证许可的地方调用
using (License license = LicenseManager.Validate(typeof(MyButton), this))
{
System.Diagnostics.Debug.WriteLine("许可验证成功");
}
需要了解的知识点
LicenseProvider Class (System.ComponentModel) | Microsoft Learn
LicenseProviderAttribute Class (System.ComponentModel) | Microsoft Learn
LicFileLicenseProvider Class (System.ComponentModel) | Microsoft Learn
License Class (System.ComponentModel) | Microsoft Learn
LicenseManager Class (System.ComponentModel) | Microsoft Learn
LicenseContext Class (System.ComponentModel) | Microsoft Learn
System.Windows.Controls 命名空间 | Microsoft Learn
源码地址
GitHub - HeBianGu/WPF-ControlDemo: 示例
GitHub - HeBianGu/WPF-ControlBase: Wpf封装的自定义控件资源库
GitHub - HeBianGu/WPF-Control: WPF轻量控件和皮肤库