[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 2008-12-25 17:57  xwang  阅读(535)  评论(2编辑  收藏  举报

导航