[Coding For Fun] 您有运行许可证吗?

本文中将为您提供给程序加上运行许可的方法

先看看效果(声明,这不是简单的输出一行字符串):

image

在本文中将会涉及到3个类 License, LicenseProvider, LicenseManager 和 注册表类

我们首先给程序创建一个自己的License

   1: public class SimpleRuntimeLicense : License
   2: {
   3:     private string TypeCode;
   4:     public override void Dispose() {}
   5:  
   6:     public SimpleRuntimeLicense(Type type)
   7:     {
   8:         TypeCode = type.GUID.ToString();
   9:     }
  10:  
  11:     public override string LicenseKey
  12:     {
  13:         get { return TypeCode; }
  14:     }
  15: }

而后,需要值得一提的是对于License的执行是利用.Net中常见的Provider模式

   1: public class SimpleLicenseProvider : LicenseProvider
   2: {
   3:  
   4:    public override License GetLicense(LicenseContext context, Type type, object instance, bool allowExceptions)
   5:    {
   6:        if (context.UsageMode == LicenseUsageMode.Runtime)
   7:        {
   8:            RegistryKey key = Registry.CurrentUser.OpenSubKey("Software\\MySimplceLicense");
   9:  
  10:            if (null != key)
  11:            {
  12:                string strlic = key.GetValue("SN").ToString();
  13:                if (strlic != null)
  14:                {
  15:                    if (string.Compare(strlic, type.GUID.ToString(), false) == 0)
  16:                        return new SimpleRuntimeLicense(type);
  17:                }
  18:            }
  19:            if (allowExceptions) throw new LicenseException(type, instance, "你没有运行许可证! :)");
  20:            
  21:        }
  22:  
  23:        return null;
  24:    }
  25: }

这样,我们就完成了License的基础结构,之后,再需要调用他的类上加上对应的标记即可, 我们拿MyClass开刀

   1: [GuidAttribute("7F46DB6D-98CD-4cb7-BA95-014F678B2375")]
   2: [LicenseProvider(typeof(SimpleLicenseProvider))]
   3: public class MyClass
   4: {
   5:     public void Validate()
   6:     {
   7:         LicenseManager.Validate(typeof(MyClass), this);
   8:     }
   9: }

这样,以后我们只要使用Validate的方法,都会先进行License的验证,如此,对于我们保护某些关键的方法和类就非常有用了

   1: try
   2: {
   3:     MyClass c = new MyClass();
   4:     c.Validate();
   5: }
   6: catch (Exception ex)
   7: {
   8:     Console.WriteLine(ex.Message);
   9: }

这样,就出现了开始出现的结果,于此,你是否产生了一些联想呢 :) have fun...

posted on   xwang  阅读(544)  评论(2编辑  收藏  举报

编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· [AI/GPT/综述] AI Agent的设计模式综述

导航

< 2008年12月 >
30 1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31 1 2 3
4 5 6 7 8 9 10

统计

点击右上角即可分享
微信分享提示