public override License GetLicense (LicenseContext context,
			Type type,
			object instance,
			bool allowExceptions)
		{
			if (type.Name.Equals ("RuntimeLicensedObject")) {
				if (context.UsageMode != LicenseUsageMode.Runtime)
					if (allowExceptions)
						throw new LicenseException (type, instance, "License fails because this is a Runtime only license");
					else
						return null;
				return new TestLicense ();
			}

			if (type.Name.Equals ("DesigntimeLicensedObject")) 
			{
				if (context.UsageMode != LicenseUsageMode.Designtime)
					if (allowExceptions)
						throw new LicenseException (type, instance, "License fails because this is a Designtime only license");
					else
						return null;
				return new TestLicense ();
			}

			if (type.Name.Equals ("LicensedObject"))
				return new TestLicense ();

			if (allowExceptions)
				throw new LicenseException (type, instance, "License fails because of class name.");
			else
				return null;
		}
Example #2
0
        /// <summary>
        /// Creates an instance of the specified type with the
        /// specified arguments, using creationContext as the context in which the licensed
        /// instance can be used.
        /// </summary>
        public static object CreateWithContext(Type type, LicenseContext creationContext, object[] args)
        {
            object created = null;

            lock (s_internalSyncObject)
            {
                LicenseContext normal = CurrentContext;
                try
                {
                    CurrentContext = creationContext;
                    LockContext(s_selfLock);
                    try
                    {
                        created = Activator.CreateInstance(type, args);
                    }
                    catch (TargetInvocationException e)
                    {
                        throw e.InnerException;
                    }
                }
                finally
                {
                    UnlockContext(s_selfLock);
                    CurrentContext = normal;
                }
            }

            return(created);
        }
 public static object CreateWithContext(Type type, LicenseContext creationContext, object[] args)
 {
     object obj2 = null;
     lock (internalSyncObject)
     {
         LicenseContext currentContext = CurrentContext;
         try
         {
             CurrentContext = creationContext;
             LockContext(selfLock);
             try
             {
                 obj2 = SecurityUtils.SecureCreateInstance(type, args);
             }
             catch (TargetInvocationException exception)
             {
                 throw exception.InnerException;
             }
             return obj2;
         }
         finally
         {
             UnlockContext(selfLock);
             CurrentContext = currentContext;
         }
     }
     return obj2;
 }
Example #4
0
		public override License GetLicense (LicenseContext context,
						    Type type,
						    object instance,
						    bool allowExceptions)
		{
			try
			{
				if (context == null || context.UsageMode != LicenseUsageMode.Designtime)
					return null;
			
				string path = Path.GetDirectoryName (type.Assembly.Location);
				path = Path.Combine (path, type.FullName + ".LIC");
			
				if (!File.Exists (path)) return null;
			
				StreamReader sr = new StreamReader (path);
				string key = sr.ReadLine ();
				sr.Close ();
				
				if (IsKeyValid (key, type))
					return new LicFileLicense (key);
			}
			catch
			{
				if (allowExceptions) throw;
			}
			return null;
		}
Example #5
0
        /// <include file='doc\LicenseManager.uex' path='docs/doc[@for="LicenseManager.CreateWithContext1"]/*' />
        /// <devdoc>
        ///    <para>Creates an instance of the specified type with the
        ///       specified arguments, using creationContext as the context in which the licensed
        ///       instance can be used.</para>
        /// </devdoc>
        public static object CreateWithContext(Type type, LicenseContext creationContext, object[] args)
        {
            if ((!(type.IsPublic || type.IsNestedPublic)) && (type.Assembly == typeof(LicenseManager).Assembly))
            {
                IntSecurity.FullReflection.Demand();
            }

            object created = null;

            lock (typeof(LicenseManager)) {
                LicenseContext normal = CurrentContext;
                try {
                    CurrentContext = creationContext;
                    LockContext(selfLock);
                    try {
                        created = Activator.CreateInstance(type, BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance, null, args, null);
                    }
                    catch (TargetInvocationException e) {
                        throw e.InnerException;
                    }
                }
                finally {
                    UnlockContext(selfLock);
                    CurrentContext = normal;
                }
            }

            return(created);
        }
		public override License GetLicense(LicenseContext context, Type type, object instance, bool allowExceptions)
		{
			ScutexLicense license = null;

			try
			{
				if (context.UsageMode == LicenseUsageMode.Designtime)
				{
					if (_licensingManager != null)
						license = _licensingManager.Validate(InteractionModes.Silent);

					if (license != null)
					{
						if (!license.IsLicenseValid())
						{
							//throw new LicenseException(type, instance, "Invalid license or trial expired");
							return null;
						}
						else
						{
							return new ScutexComponentLicense(license);
						}
					}
				}

				return null;
			}
			catch (Exception ex)
			{
				return null;
			}
		}
Example #7
0
        public static object?CreateWithContext(
            [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type,
            LicenseContext creationContext,
            object[] args)
        {
            object?created = null;

            lock (s_internalSyncObject)
            {
                LicenseContext normal = CurrentContext;
                try
                {
                    CurrentContext = creationContext;
                    LockContext(s_selfLock);
                    try
                    {
                        created = Activator.CreateInstance(type, args);
                    }
                    catch (TargetInvocationException e)
                    {
                        throw e.InnerException !;
                    }
                }
                finally
                {
                    UnlockContext(s_selfLock);
                    CurrentContext = normal;
                }
            }

            return(created);
        }
        public static object CreateWithContext(Type type, LicenseContext creationContext, object[] args)
        {
            object obj2 = null;

            lock (internalSyncObject)
            {
                LicenseContext currentContext = CurrentContext;
                try
                {
                    CurrentContext = creationContext;
                    LockContext(selfLock);
                    try
                    {
                        obj2 = SecurityUtils.SecureCreateInstance(type, args);
                    }
                    catch (TargetInvocationException exception)
                    {
                        throw exception.InnerException;
                    }
                    return(obj2);
                }
                finally
                {
                    UnlockContext(selfLock);
                    CurrentContext = currentContext;
                }
            }
            return(obj2);
        }
Example #9
0
        /// <summary>Creates an instance of the specified type with the specified arguments, given a context in which you can use the licensed instance.</summary>
        /// <returns>An instance of the specified type with the given array of arguments.</returns>
        /// <param name="type">A <see cref="T:System.Type" /> that represents the type to create. </param>
        /// <param name="creationContext">A <see cref="T:System.ComponentModel.LicenseContext" /> that specifies when you can use the licensed instance. </param>
        /// <param name="args">An array of type <see cref="T:System.Object" /> that represents the arguments for the type. </param>
        public static object CreateWithContext(Type type, LicenseContext creationContext, object[] args)
        {
            object result = null;
            object obj    = LicenseManager.lockObject;

            lock (obj)
            {
                object         contextUser    = new object();
                LicenseContext currentContext = LicenseManager.CurrentContext;
                LicenseManager.CurrentContext = creationContext;
                LicenseManager.LockContext(contextUser);
                try
                {
                    result = Activator.CreateInstance(type, args);
                }
                catch (TargetInvocationException ex)
                {
                    throw ex.InnerException;
                }
                finally
                {
                    LicenseManager.UnlockContext(contextUser);
                    LicenseManager.CurrentContext = currentContext;
                }
            }
            return(result);
        }
 /// <summary>Returns a license for the instance of the component, if one is available.</summary>
 /// <returns>A valid <see cref="T:System.ComponentModel.License" />. If this method cannot find a valid <see cref="T:System.ComponentModel.License" /> or a valid <paramref name="context" /> parameter, it returns null.</returns>
 /// <param name="context">A <see cref="T:System.ComponentModel.LicenseContext" /> that specifies where you can use the licensed object. </param>
 /// <param name="type">A <see cref="T:System.Type" /> that represents the component requesting the <see cref="T:System.ComponentModel.License" />. </param>
 /// <param name="instance">An object that requests the <see cref="T:System.ComponentModel.License" />. </param>
 /// <param name="allowExceptions">true if a <see cref="T:System.ComponentModel.LicenseException" /> should be thrown when a component cannot be granted a license; otherwise, false. </param>
 /// <PermissionSet>
 ///   <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
 /// </PermissionSet>
 public override License GetLicense(LicenseContext context, Type type, object instance, bool allowExceptions)
 {
     try
     {
         if (context == null || context.UsageMode != LicenseUsageMode.Designtime)
         {
             return(null);
         }
         string directoryName = Path.GetDirectoryName(type.Assembly.Location);
         directoryName = Path.Combine(directoryName, type.FullName + ".LIC");
         if (!File.Exists(directoryName))
         {
             return(null);
         }
         StreamReader streamReader = new StreamReader(directoryName);
         string       key          = streamReader.ReadLine();
         streamReader.Close();
         if (IsKeyValid(key, type))
         {
             return(new LicFileLicense(key));
         }
     }
     catch
     {
         if (allowExceptions)
         {
             throw;
         }
     }
     return(null);
 }
Example #11
0
        /// <summary>
        ///    <para>Gets a license for the instance of the component and determines if it is valid.</para>
        /// </summary>
        public override License GetLicense(LicenseContext context, Type type, object instance, bool allowExceptions)
        {
            LicFileLicense lic = null;

            Debug.Assert(context != null, "No context provided!");
            if (context != null)
            {
                if (context.UsageMode == LicenseUsageMode.Runtime)
                {
                    string key = context.GetSavedLicenseKey(type, null);
                    if (key != null && IsKeyValid(key, type))
                    {
                        lic = new LicFileLicense(this, key);
                    }
                }

                if (lic == null)
                {
                    string modulePath = null;

                    if (context != null)
                    {
                        ITypeResolutionService resolver = (ITypeResolutionService)context.GetService(typeof(ITypeResolutionService));
                        if (resolver != null)
                        {
                            modulePath = resolver.GetPathOfAssembly(type.Assembly.GetName());
                        }
                    }

                    if (modulePath == null)
                    {
                        modulePath = type.Module.FullyQualifiedName;
                    }

                    string moduleDir   = Path.GetDirectoryName(modulePath);
                    string licenseFile = moduleDir + "\\" + type.FullName + ".lic";

                    Debug.WriteLine($"Looking for license in: {licenseFile}");
                    if (File.Exists(licenseFile))
                    {
                        Stream       licStream = new FileStream(licenseFile, FileMode.Open, FileAccess.Read, FileShare.Read);
                        StreamReader sr        = new StreamReader(licStream);
                        string       s         = sr.ReadLine();
                        sr.Close();
                        if (IsKeyValid(s, type))
                        {
                            lic = new LicFileLicense(this, GetKey(type));
                        }
                    }

                    if (lic != null)
                    {
                        context.SetSavedLicenseKey(type, lic.LicenseKey);
                    }
                }
            }
            return(lic);
        }
Example #12
0
        /// <summary>
        ///    <para>Gets a license for the instance of the component and determines if it is valid.</para>
        /// </summary>
        public override License GetLicense(LicenseContext context, Type type, object instance, bool allowExceptions)
        {
            LicFileLicense lic = null;

            Debug.Assert(context != null, "No context provided!");
            if (context != null)
            {
                if (context.UsageMode == LicenseUsageMode.Runtime)
                {
                    string key = context.GetSavedLicenseKey(type, null);
                    if (key != null && IsKeyValid(key, type))
                    {
                        lic = new LicFileLicense(this, key);
                    }
                }

                if (lic == null)
                {
                    string modulePath = null;

                    if (context != null)
                    {
                        ITypeResolutionService resolver = (ITypeResolutionService)context.GetService(typeof(ITypeResolutionService));
                        if (resolver != null)
                        {
                            modulePath = resolver.GetPathOfAssembly(type.Assembly.GetName());
                        }
                    }

                    if (modulePath == null)
                    {
                        modulePath = type.Module.FullyQualifiedName;
                    }

                    string moduleDir = Path.GetDirectoryName(modulePath);
                    string licenseFile = moduleDir + "\\" + type.FullName + ".lic";

                    Debug.WriteLine($"Looking for license in: {licenseFile}");
                    if (File.Exists(licenseFile))
                    {
                        Stream licStream = new FileStream(licenseFile, FileMode.Open, FileAccess.Read, FileShare.Read);
                        StreamReader sr = new StreamReader(licStream);
                        string s = sr.ReadLine();
                        sr.Close();
                        if (IsKeyValid(s, type))
                        {
                            lic = new LicFileLicense(this, GetKey(type));
                        }
                    }

                    if (lic != null)
                    {
                        context.SetSavedLicenseKey(type, lic.LicenseKey);
                    }
                }
            }
            return lic;
        }
        private static bool ValidateInternalRecursive(LicenseContext context, Type type, object instance, bool allowExceptions, out License license, out string licenseKey)
        {
            LicenseProvider cachedProvider = GetCachedProvider(type);

            if ((cachedProvider == null) && !GetCachedNoLicenseProvider(type))
            {
                LicenseProviderAttribute attribute = (LicenseProviderAttribute)Attribute.GetCustomAttribute(type, typeof(LicenseProviderAttribute), false);
                if (attribute != null)
                {
                    Type licenseProvider = attribute.LicenseProvider;
                    cachedProvider = GetCachedProviderInstance(licenseProvider);
                    if (cachedProvider == null)
                    {
                        cachedProvider = (LicenseProvider)SecurityUtils.SecureCreateInstance(licenseProvider);
                    }
                }
                CacheProvider(type, cachedProvider);
            }
            license = null;
            bool flag = true;

            licenseKey = null;
            if (cachedProvider != null)
            {
                license = cachedProvider.GetLicense(context, type, instance, allowExceptions);
                if (license == null)
                {
                    flag = false;
                }
                else
                {
                    licenseKey = license.LicenseKey;
                }
            }
            if (flag && (instance == null))
            {
                string str;
                Type   baseType = type.BaseType;
                if (!(baseType != typeof(object)) || (baseType == null))
                {
                    return(flag);
                }
                if (license != null)
                {
                    license.Dispose();
                    license = null;
                }
                flag = ValidateInternalRecursive(context, baseType, null, allowExceptions, out license, out str);
                if (license != null)
                {
                    license.Dispose();
                    license = null;
                }
            }
            return(flag);
        }
        public override License GetLicense(LicenseContext context, Type type, object instance, bool allowExceptions)
        {
            FileLicense license = null;
            StringBuilder listMsg = new StringBuilder();
            if (context != null)
            {
                if (context.UsageMode == LicenseUsageMode.Designtime)
                {
                    license = new FileLicense(this, "");
                }
                if (license != null)
                {
                    return license;
                }
                //licenses
                string licenseFile = GetlicFilePath();
                if (!string.IsNullOrWhiteSpace(licenseFile) && File.Exists(licenseFile))
                {
                    try
                    {

                        StreamReader sr = new StreamReader(licenseFile, Encoding.Default);
                        String xmlStr = DESEncrypt.Decrypt(sr.ReadToEnd());
                        var entity = XmlFormatterSerializer.DeserializeFromXml<LicenseEntity>(xmlStr, typeof(LicenseEntity));
                        if (entity != null)
                        {
                            var pastDate = DateTime.Parse(entity.PastDate);
                            if (DateTime.Now > pastDate)
                            {
                                listMsg.AppendLine(" 许可证已过期");
                            }
                        }

                        if (listMsg.Length > 5)
                        {
                            listMsg.Insert(0, " 许可证编号:" + entity.ID);
                            listMsg.Insert(1, " 许可证名称:" + entity.Name);
                            listMsg.Insert(2, " 程序集版本号:" + entity.AssemblyName);
                            license = new FileLicense(this, listMsg.ToString());
                        }
                        else
                            license = new FileLicense(this, "");
                    }
                    catch (IOException e)
                    {
                        license = new FileLicense(this, "检查许可证失败" + e.Message);
                    }
                }
                else
                {
                    license = new FileLicense(this, "lic文件不存在,请联系供应商");
                }
            }
            return license;
        }
 public override System.ComponentModel.License GetLicense(	LicenseContext context,
     Type type,
     object instance,
     bool allowExceptions)
 {
     /* the context passed in can be used to determine runtime or designtime usage, however it does not handle
      * saved license keys and therfore we have our own to handle that.
      * There is a resource drain if the requesting controls do not release the License generated and returned
      * to them.
      */
     XEditNetLicenseContext lcTemp = new XEditNetLicenseContext();
     return new XEditNetLicence(lcTemp.GetSavedLicenseKey(typeof(XEditNetLicenseProvider),System.Reflection.Assembly.GetExecutingAssembly()));
 }
Example #16
0
            // The CLR invokes this when instantiating an unmanaged COM
            // object. The purpose is to decide which IClassFactory method to
            // use.
            public static LicenseContext GetCurrentContextInfo(Type type, out bool isDesignTime, out string key)
            {
                LicenseContext licContext = LicenseManager.CurrentContext;

                isDesignTime = licContext.UsageMode == LicenseUsageMode.Designtime;
                key          = null;
                if (!isDesignTime)
                {
                    key = licContext.GetSavedLicenseKey(type, resourceAssembly: null);
                }

                return(licContext);
            }
        public override License GetLicense(LicenseContext context, Type type, object instance, bool allowExceptions)
        {
            LicFileLicense license = null;

            if (context != null)
            {
                if (context.UsageMode == LicenseUsageMode.Runtime)
                {
                    string savedLicenseKey = context.GetSavedLicenseKey(type, null);
                    if ((savedLicenseKey != null) && this.IsKeyValid(savedLicenseKey, type))
                    {
                        license = new LicFileLicense(this, savedLicenseKey);
                    }
                }
                if (license != null)
                {
                    return(license);
                }
                string path = null;
                if (context != null)
                {
                    ITypeResolutionService service = (ITypeResolutionService)context.GetService(typeof(ITypeResolutionService));
                    if (service != null)
                    {
                        path = service.GetPathOfAssembly(type.Assembly.GetName());
                    }
                }
                if (path == null)
                {
                    path = type.Module.FullyQualifiedName;
                }
                string str4 = Path.GetDirectoryName(path) + @"\" + type.FullName + ".lic";
                if (File.Exists(str4))
                {
                    Stream       stream = new FileStream(str4, FileMode.Open, FileAccess.Read, FileShare.Read);
                    StreamReader reader = new StreamReader(stream);
                    string       key    = reader.ReadLine();
                    reader.Close();
                    if (this.IsKeyValid(key, type))
                    {
                        license = new LicFileLicense(this, this.GetKey(type));
                    }
                }
                if (license != null)
                {
                    context.SetSavedLicenseKey(type, license.LicenseKey);
                }
            }
            return(license);
        }
        public override License GetLicense( LicenseContext context,
        Type type,
        object instance,
         bool allowExceptions )
        {
            // We'll test for the usage mode...run time v. design time.
            // Note we only check if run time...
            if (context.UsageMode == LicenseUsageMode.Runtime)
            {
                // The Registry key we'll check
                RegistryKey licenseKey =
              Registry.CurrentUser.OpenSubKey("Software\\Acme\\HostKeys");

                if (licenseKey != null)
                {
                    // Passed the first test, which is the existence of the
                    // Registry key itself. Now obtain the stored value
                    // associated with our app's GUID.
                    string strLic =
               (string)licenseKey.GetValue(type.GUID.ToString()); // reflected!
                    if (strLic != null)
                    {
                        // Passed the second test, which is some value
                        // exists that's associated with our app's GUID.
                        if (String.Compare("Installed", strLic, false) == 0)
                        {
                            // Got it...valid license...
                            return new RuntimeRegistryLicense(type);
                        } // if
                    } // if
                } // if

                // if we got this far, we failed the license test. We then
                // check to see if exceptions are allowed, and if so, throw
                // a new license exception...
                if (allowExceptions == true)
                {
                    throw new LicenseException(type,
                                               instance,
                                               "Your license is invalid");
                } // if

                // Exceptions are not desired, so we'll simply return null.
                return null;
            } // if
            else
            {
                return new DesigntimeRegistryLicense(type);
            } // else
        }
    public override License GetLicense(LicenseContext context,
        Type type, object instance, bool allowExceptions)
    {
//      return new RegLicense(this, type);
//      if (context.UsageMode == LicenseUsageMode.Designtime)
//      {
//        RegistryKey licenseKey = Registry.LocalMachine.
//          OpenSubKey("Software\\MindFusion Limited\\ComponentLicenses");

//        if (licenseKey == null)
//        {
//          // the conrol might be installed on a 64-bit system
//          licenseKey = Registry.LocalMachine.
//            OpenSubKey("Software\\Wow6432Node\\MindFusion Limited\\ComponentLicenses");
//        }

//        if (licenseKey != null)
//        {
//          object keyVal = licenseKey.GetValue(type.FullName);
//          if (keyVal != null)
//          {
//#if DEMO_VERSION
//            return new RegLicense(this, type);
//#else

//#if FCNET_STD
//            if (keyVal.ToString() == "fcxstd_lic_sG9VJ4sL")
//              return new RegLicense(this, type);
//#else
//            if (keyVal.ToString() == "fcxpro_lic_FO7cGAk")
//              return new RegLicense(this, type);
//#endif
//#endif
//          }
//        }

//        if (allowExceptions)
//        {
//          throw new LicenseException(type, instance,
//              "Couldn''t get design-time license for ''" + type.FullName + "''");
//        }

//        return null;
//      }
//      else
      {
        return new RuntimeRegLicense(this, type);
      }
    }
Example #20
0
 // The CLR invokes this when instantiating an unmanaged COM
 // object. The purpose is to decide which classfactory method to
 // use.
 //
 // If the current context is design time, the CLR will
 // use ICF::CreateInstance().
 //
 // If the current context is runtime and the current context
 // exposes a non-null license key and the COM object supports
 // IClassFactory2, the CLR will use ICF2::CreateInstanceLic().
 // Otherwise, the CLR will use ICF::CreateInstance.
 //
 // Arguments:
 //    ref int fDesignTime:   on exit, this will be set to indicate
 //                           the nature of the current license context.
 //    ref int bstrKey:       on exit, this will point to the
 //                           licensekey saved inside the license context.
 //                           (only if the license context is runtime)
 //    RuntimeTypeHandle rth: the managed type of the wrapper
 private void GetCurrentContextInfo(ref int fDesignTime, ref IntPtr bstrKey, RuntimeTypeHandle rth)
 {
     this.savedLicenseContext = LicenseManager.CurrentContext;
     this.savedType           = Type.GetTypeFromHandle(rth);
     if (this.savedLicenseContext.UsageMode == LicenseUsageMode.Designtime)
     {
         fDesignTime = 1;
         bstrKey     = (IntPtr)0;
     }
     else
     {
         fDesignTime = 0;
         String key = this.savedLicenseContext.GetSavedLicenseKey(this.savedType, null);
         bstrKey = Marshal.StringToBSTR(key);
     }
 }
Example #21
0
            // Used to validate a type and retrieve license details
            // when activating a managed COM server from an IClassFactory2 instance.
            public static bool ValidateAndRetrieveLicenseDetails(
                LicenseContext context,
                Type type,
                out License?license,
                out string?licenseKey)
            {
                context ??= LicenseManager.CurrentContext;

                return(LicenseManager.ValidateInternalRecursive(
                           context,
                           type,
                           instance: null,
                           allowExceptions: false,
                           out license,
                           out licenseKey));
            }
Example #22
0
 public static Object CreateWithContext
     (Type type, LicenseContext creationContext, Object[] args)
 {
     lock (typeof(LicenseManager))
     {
         // Temporarily switch to the new context during creation.
         LicenseContext savedContext = currentContext;
         currentContext = creationContext;
         try
         {
             // Make sure that we are the only context user.
             if (ourLock == null)
             {
                 ourLock = new Object();
             }
             LockContext(ourLock);
             try
             {
                 try
                 {
                     return(Activator.CreateInstance(type, args));
                 }
                 catch (TargetInvocationException e)
                 {
                     // Re-throw the inner exception, if present.
                     if (e.InnerException != null)
                     {
                         throw e.InnerException;
                     }
                     else
                     {
                         throw;
                     }
                 }
             }
             finally
             {
                 UnlockContext(ourLock);
             }
         }
         finally
         {
             currentContext = savedContext;
         }
     }
 }
Example #23
0
        /// <summary>
        /// Get license from registry. If not expired and is valid then use it
        /// </summary>
        /// <param name="context"></param>
        /// <param name="type"></param>
        /// <param name="instance"></param>
        /// <param name="allowExceptions"></param>
        /// <returns></returns>
        public override License GetLicense(LicenseContext context, Type type, object instance, bool allowExceptions)
        {
            // Get license only in design mode
            if (context.UsageMode == LicenseUsageMode.Designtime)
            {
                // check and create license
                AxiomLicense lic = new AxiomLicense();

                // Trial license
                System.Windows.Forms.MessageBox.Show("Please register ME!");
                return lic;
            }
            else
            {
                return new AxiomLicense();
            }
        }
Example #24
0
        public override License GetLicense(LicenseContext context,
			Type type, object instance, bool allowExceptions)
        {
            #if (DEMO)
            if (context.UsageMode == LicenseUsageMode.Designtime || Debugger.IsAttached) {
                return new DemoLicense(true);
            }
            else {
                bool runSpecial = false;
                try {
                    LocalDataStoreSlot slot = Thread.GetNamedDataSlot("Wilson.ORMapper.AllowDemo");
                    string allowDemoKey = Thread.GetData(slot) as string;
                    if (allowDemoKey != null) {
                        if (allowDemoKey.Equals("WilsonWebPortal")) runSpecial = true;
                        else if (allowDemoKey.Equals("WilsonORHelper")) runSpecial = true;
                    }
                }
                catch {} // Do Nothing

                bool runMatrix = false;
                if (!runSpecial) {
                    try {
                        if (Process.GetProcessesByName("WebMatrix").Length > 0) runMatrix = true;
                        else if (Process.GetProcessesByName("WebServer").Length > 0) runMatrix = true;
                    }
                    catch {} // Do Nothing
                }
                if (runSpecial || runMatrix) {
                    return new DemoLicense(true);
                }
                else {
                    return null;
                }
            }
            #else
            return new DemoLicense(false);
            #endif
        }
            // The CLR invokes this when instantiating an unmanaged COM
            // object. The purpose is to decide which classfactory method to
            // use.
            //
            // If the current context is design time, the CLR will
            // use ICF::CreateInstance().
            //
            // If the current context is runtime and the current context
            // exposes a non-null license key and the COM object supports
            // IClassFactory2, the CLR will use ICF2::CreateInstanceLic().
            // Otherwise, the CLR will use ICF::CreateInstance.
            //
            // Arguments:
            //    ref int fDesignTime:   on exit, this will be set to indicate
            //                           the nature of the current license context.
            //    ref int bstrKey:       on exit, this will point to the
            //                           licensekey saved inside the license context.
            //                           (only if the license context is runtime)
            //    RuntimeTypeHandle rth: the managed type of the wrapper
            private void GetCurrentContextInfo(ref int fDesignTime, ref IntPtr bstrKey, RuntimeTypeHandle rth) {
                this.savedLicenseContext = LicenseManager.CurrentContext;
                this.savedType = Type.GetTypeFromHandle(rth);
                if (this.savedLicenseContext.UsageMode == LicenseUsageMode.Designtime) {
                    fDesignTime = 1;
                    bstrKey = (IntPtr)0;
                }
                else {
                    fDesignTime = 0;
                    String key = this.savedLicenseContext.GetSavedLicenseKey(this.savedType, null);
                    bstrKey = Marshal.StringToBSTR(key);

                }
            }
 /// <include file='doc\LicenseManager.uex' path='docs/doc[@for="LicenseManager.CreateWithContext"]/*' />
 /// <devdoc>
 ///    <para>Creates an instance of the specified type, using 
 ///       creationContext
 ///       as the context in which the licensed instance can be used.</para>
 /// </devdoc>
 public static object CreateWithContext(Type type, LicenseContext creationContext) {
     return CreateWithContext(type, creationContext, new object[0]);
 }
Example #27
0
        /// <include file='doc\LicenseManager.uex' path='docs/doc[@for="LicenseManager.ValidateInternalRecursive"]/*' />
        /// <devdoc>
        ///     Since we want to walk up the entire inheritance change, when not
        ///     give an instance, we need another helper method to walk up
        ///     the chain...
        /// </devdoc>
        private static bool ValidateInternalRecursive(LicenseContext context, Type type, object instance, bool allowExceptions, out License license, out string licenseKey)
        {
            LicenseProvider provider = GetCachedProvider(type);

            if (provider == null && !GetCachedNoLicenseProvider(type))
            {
                // NOTE : Must look directly at the class, we want no inheritance.
                //
                LicenseProviderAttribute attr = (LicenseProviderAttribute)Attribute.GetCustomAttribute(type, typeof(LicenseProviderAttribute), false);
                if (attr != null)
                {
                    Type providerType = attr.LicenseProvider;
                    provider = GetCachedProviderInstance(providerType);

                    if (provider == null)
                    {
                        provider = (LicenseProvider)SecurityUtils.SecureCreateInstance(providerType);
                    }
                }

                CacheProvider(type, provider);
            }

            license = null;
            bool isValid = true;

            licenseKey = null;
            if (provider != null)
            {
                license = provider.GetLicense(context, type, instance, allowExceptions);
                if (license == null)
                {
                    isValid = false;
                }
                else
                {
                    // For the case where a COM client is calling "RequestLicKey",
                    // we try to squirrel away the first found license key
                    //
                    licenseKey = license.LicenseKey;
                }
            }

            // When looking only at a type, we need to recurse up the inheritence
            // chain, however, we can't give out the license, since this may be
            // from more than one provider.
            //
            if (isValid && instance == null)
            {
                Type baseType = type.BaseType;
                if (baseType != typeof(object) && baseType != null)
                {
                    if (license != null)
                    {
                        license.Dispose();
                        license = null;
                    }
                    string temp;
                    isValid = ValidateInternalRecursive(context, baseType, null, allowExceptions, out license, out temp);
                    if (license != null)
                    {
                        license.Dispose();
                        license = null;
                    }
                }
            }

            return(isValid);
        }
 public override License GetLicense(LicenseContext context, Type type, Object instance, bool allowExceptions)
 {
     return(default(License));
 }
	// Get the license for a type.
	public override License GetLicense
				(LicenseContext context, Type type, object instance,
				 bool allowExceptions)
			{
				String key, path;
				StreamReader reader;

				// Bail out if we don't have a license context.
				if(context == null)
				{
					return null;
				}

				// Use the saved key if we saw this type previously.
				if(context.UsageMode == LicenseUsageMode.Runtime)
				{
					key = context.GetSavedLicenseKey(type, null);
					if(key != null && IsKeyValid(key, type))
					{
						return new FileLicense(key);
					}
				}

				// Find the pathname of the assembly containing the type.
			#if CONFIG_COMPONENT_MODEL_DESIGN
				ITypeResolutionService trs;
				trs = (ITypeResolutionService)
					context.GetService(typeof(ITypeResolutionService));
				if(trs != null)
				{
					path = trs.GetPathOfAssembly(type.Assembly.GetName());
					if(path == null)
					{
						path = type.Assembly.Location;
					}
				}
				else
			#endif
				{
					path = type.Assembly.Location;
				}

				// Look for a "*.lic" file for the type.
				path = Path.Combine(Path.GetDirectoryName(path),
									type.FullName + ".lic");
				try
				{
					reader = new StreamReader(path);
				}
				catch(Exception)
				{
					// Could not open the file, so assume unlicensed.
					return null;
				}

				// Read the key from the first line of the license file.
				key = reader.ReadLine();
				reader.Close();

				// Bail out if the key is invalid.
				if(key == null || !IsKeyValid(key, type))
				{
					return null;
				}

				// Cache the key within the context.
				context.SetSavedLicenseKey(type, key);

				// Return a new file license to the caller.
				return new FileLicense(key);
			}
Example #30
0
 /// <summary>
 /// Creates an instance of the specified type, using
 /// creationContext
 /// as the context in which the licensed instance can be used.
 /// </summary>
 public static object CreateWithContext(Type type, LicenseContext creationContext)
 {
     return(CreateWithContext(type, creationContext, Array.Empty <object>()));
 }
Example #31
0
 public override License GetLicense(LicenseContext context, Type type, object instance, bool allowExceptions)
 {
     return new EncryptedLicense();
 }
        /// <summary>
        /// Return the license key for the given context and type
        /// </summary>
        /// <remarks>
        /// This can be overridden to change where the license key is stored by the provider.   For
        /// instance a derived class could override this method to store the key in the Registry.
        /// </remarks>
        /// <param name="context">The license context</param>
        /// <param name="type">The type to get the key for</param>
        /// <returns>The license key</returns>
        protected virtual string GetLicenseKey(LicenseContext context, Type type)
        {
            string key = null;
            if (context.UsageMode == LicenseUsageMode.Runtime)
            {
                try
                {
                    key = context.GetSavedLicenseKey(type, null);
                }
                catch
                {
                    // if something goes wrong retrieving the saved license key then just ignore it
                    // and try reading from file
                }
            }

            // if we're in design mode or a suitable license key wasn't found in
            // the runtime context look for a .LIC file
            //
            if (key == null)
            {
                key = ReadKeyFromFile(GetLicenseFilePath(context, type));
            }
            return key;
        }
Example #33
0
        // Get the license for a type.
        public override License GetLicense
            (LicenseContext context, Type type, object instance,
            bool allowExceptions)
        {
            String       key, path;
            StreamReader reader;

            // Bail out if we don't have a license context.
            if (context == null)
            {
                return(null);
            }

            // Use the saved key if we saw this type previously.
            if (context.UsageMode == LicenseUsageMode.Runtime)
            {
                key = context.GetSavedLicenseKey(type, null);
                if (key != null && IsKeyValid(key, type))
                {
                    return(new FileLicense(key));
                }
            }

            // Find the pathname of the assembly containing the type.
                        #if CONFIG_COMPONENT_MODEL_DESIGN
            ITypeResolutionService trs;
            trs = (ITypeResolutionService)
                  context.GetService(typeof(ITypeResolutionService));
            if (trs != null)
            {
                path = trs.GetPathOfAssembly(type.Assembly.GetName());
                if (path == null)
                {
                    path = type.Assembly.Location;
                }
            }
            else
                        #endif
            {
                path = type.Assembly.Location;
            }

            // Look for a "*.lic" file for the type.
            path = Path.Combine(Path.GetDirectoryName(path),
                                type.FullName + ".lic");
            try
            {
                reader = new StreamReader(path);
            }
            catch (Exception)
            {
                // Could not open the file, so assume unlicensed.
                return(null);
            }

            // Read the key from the first line of the license file.
            key = reader.ReadLine();
            reader.Close();

            // Bail out if the key is invalid.
            if (key == null || !IsKeyValid(key, type))
            {
                return(null);
            }

            // Cache the key within the context.
            context.SetSavedLicenseKey(type, key);

            // Return a new file license to the caller.
            return(new FileLicense(key));
        }
 public override License GetLicense(LicenseContext context, Type type, object instance, bool allowExceptions)
 {
     int num2;
     string[] textArray1;
     string text1 = "\nEnvironment info:\n";
     text1 = text1 + "version: " + DiagramView.VersionName + "\n";
     if (Assembly.GetEntryAssembly() != null)
     {
         text1 = text1 + "entry: ";
         try
         {
             text1 = text1 + Assembly.GetEntryAssembly().FullName;
         }
         catch (SecurityException)
         {
             text1 = text1 + "?fn?";
         }
         object obj1 = null;
         try
         {
             obj1 = Assembly.GetEntryAssembly().EntryPoint;
         }
         catch (SecurityException)
         {
             text1 = text1 + "?ep?";
         }
         if (obj1 != null)
         {
             text1 = text1 + ", has entry point\n";
         }
         else
         {
             text1 = text1 + ", no entry point\n";
         }
     }
     else
     {
         text1 = text1 + "null entry\n";
     }
     int num1 = 0;
     string text2 = "";
     try
     {
         try
         {
             text2 = context.GetSavedLicenseKey(type, null);
         }
         catch (SecurityException exception1)
         {
             text2 = null;
             text1 = text1 + "\n" + exception1.ToString();
         }
         if (text2 != null)
         {
             text1 = text1 + "key: " + text2 + "\n";
         }
         else
         {
             text1 = text1 + "null key\n";
         }
         if ((text2 != null) && (text2.Length != 0))
         {
             goto Label_01AF;
         }
         try
         {
             Assembly[] assemblyArray1 = AppDomain.CurrentDomain.GetAssemblies();
             Assembly[] assemblyArray2 = assemblyArray1;
             for (num2 = 0; num2 < assemblyArray2.Length; num2++)
             {
                 Assembly assembly1 = assemblyArray2[num2];
                 text1 = text1 + assembly1.FullName + "\n";
                 try
                 {
                     text2 = context.GetSavedLicenseKey(type, assembly1);
                 }
                 catch (SecurityException)
                 {
                     text2 = null;
                 }
                 if ((text2 != null) && (text2.Length > 0))
                 {
                     goto Label_015A;
                 }
             }
         }
         catch (SecurityException)
         {
         }
     Label_015A:
         text1 = text1 + DiagramView.myVersionName + "\n";
         if (DiagramView.myVersionAssembly != null)
         {
             text1 = text1 + DiagramView.myVersionAssembly.GetName().Name + "\n";
         }
         else
         {
             text1 = text1 + "null licensed assembly\n";
         }
         if (DiagramView.myVersionName.Length > 0x18)
         {
             text2 = DiagramView.myVersionName;
         }
     Label_01AF:
         if ((text2 != null) && (text2.Length > 0))
         {
             num1 = this.Dispose(text2, true);
             if (num1 == 4)
             {
                 return new DiagramViewLicense(text2, num1);
             }
         }
         else
         {
             text2 = "";
             RegistryKey key1 = null;
             try
             {
                 key1 = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Northwoods Software\Go.NET");
             }
             catch (SecurityException exception2)
             {
                 text1 = text1 + "\n" + exception2.ToString();
             }
             if (key1 == null)
             {
                 try
                 {
                     key1 = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Northwoods Software\GoDiagram");
                 }
                 catch (SecurityException)
                 {
                 }
             }
             if (key1 != null)
             {
                 string text3 = type.Assembly.GetName().Name;
                 object obj2 = null;
                 try
                 {
                     obj2 = key1.GetValue(text3);
                 }
                 catch (SecurityException)
                 {
                 }
                 if ((obj2 != null) && (obj2 is byte[]))
                 {
                     text2 = Convert.ToBase64String((byte[])obj2);
                 }
             }
             num1 = this.Dispose(text2, false);
             if ((num1 == 0) && (key1 != null))
             {
                 text2 = "";
                 string text4 = type.Assembly.GetName().Name + " eval";
                 object obj3 = null;
                 try
                 {
                     obj3 = key1.GetValue(text4);
                 }
                 catch (SecurityException)
                 {
                 }
                 if ((obj3 != null) && (obj3 is byte[]))
                 {
                     text2 = Convert.ToBase64String((byte[])obj3);
                 }
                 num1 = this.Dispose(text2, false);
             }
             if ((num1 >= 4) && (context.UsageMode == LicenseUsageMode.Designtime))
             {
                 context.SetSavedLicenseKey(type, text2);
             }
             if ((num1 == 4) || (context.UsageMode == LicenseUsageMode.Designtime))
             {
                 return new DiagramViewLicense(text2, num1);
             }
         }
     }
     catch (Exception exception3)
     {
         text1 = text1 + "\n" + exception3.ToString();
     }
     num2 = num1 & 3;
     switch (num2)
     {
         case 1:
             {
                 string text7 = (num1 > 4) ? "beta" : "evaluation";
                 textArray1 = new string[0x10] { "Built using ", DiagramViewLicenseProvider.GONAME, " for .NET Windows Forms ", this.StringFloat(DiagramView.Version), Environment.NewLine, "Copyright \x00a9 Northwoods Software, 1998-2004.  All Rights Reserved.", Environment.NewLine, "This ", text7, " copy of ", DiagramViewLicenseProvider.GONAME, " is about to expire.", Environment.NewLine, Environment.NewLine, "DO NOT DISTRIBUTE OR DEPLOY THIS SOFTWARE.", Environment.NewLine };
                 string text8 = string.Concat(textArray1);
                 if (num1 < 4)
                 {
                     text8 = text8 + Environment.NewLine + "Please purchase a license at www.nwoods.com" + Environment.NewLine;
                 }
                 if (SystemInformation.UserInteractive)
                 {
                     MessageBox.Show(text8, type.Name + " License Check", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                 }
                 else
                 {
                     Console.WriteLine(type.Name + " License Check");
                     Console.WriteLine(text8);
                 }
                 return new DiagramViewLicense(text8, num1);
             }
         case 2:
             {
                 string text5 = (num1 > 4) ? "beta" : "evaluation";
                 textArray1 = new string[14] { "Built using ", DiagramViewLicenseProvider.GONAME, " for .NET Windows Forms ", this.StringFloat(DiagramView.Version), Environment.NewLine, "Copyright \x00a9 Northwoods Software, 1998-2004.  All Rights Reserved.", Environment.NewLine, "This software is licensed for a limited ", text5, " period.", Environment.NewLine, Environment.NewLine, "DO NOT DISTRIBUTE OR DEPLOY THIS SOFTWARE.", Environment.NewLine };
                 string text6 = string.Concat(textArray1);
                 if (num1 < 4)
                 {
                     text6 = text6 + Environment.NewLine + "Please purchase a license at www.nwoods.com" + Environment.NewLine;
                 }
                 if (SystemInformation.UserInteractive)
                 {
                     if (!DiagramViewLicenseProvider.err)
                     {
                         DiagramViewLicenseProvider.err = true;
                         MessageBox.Show(text6, type.Name + " License Check", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                     }
                 }
                 else
                 {
                     Console.WriteLine(type.Name + " License Check");
                     Console.WriteLine(text6);
                 }
                 return new DiagramViewLicense(text6, num1);
             }
     }
     textArray1 = new string[0x1c] { 
         "Built using ", DiagramViewLicenseProvider.GONAME, " for .NET Windows Forms ", this.StringFloat(DiagramView.Version), Environment.NewLine, "Copyright \x00a9 Northwoods Software, 1998-2004.  All Rights Reserved.", Environment.NewLine, "The license for this copy of ", DiagramViewLicenseProvider.GONAME, " is invalid or has expired.", Environment.NewLine, Environment.NewLine, "Please purchase a license at www.nwoods.com", Environment.NewLine, "If you have already purchased a ", DiagramViewLicenseProvider.GONAME, 
         " development license,", Environment.NewLine, "  have you requested an Unlock Code for your development machine by running the GoDiagram LicenseManager?", Environment.NewLine, "If you have already entered an Unlock Code in the LicenseManager,", Environment.NewLine, "  did you link license objects into your application via the Microsoft license compiler?", Environment.NewLine, "  (Make sure the needed components and correct VERSION are listed in the LICENSES.LICX file,", Environment.NewLine, "   and that the LICENSES.LICX file is part of your EXECUTABLE's project, not in a DLL.)", Environment.NewLine
      };
     string text9 = string.Concat(textArray1);
     text9 = text9 + text1;
     if (SystemInformation.UserInteractive)
     {
         MessageBox.Show(text9, type.Name + " License Check", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
     }
     else
     {
         Console.WriteLine(type.Name + " License Check");
         Console.WriteLine(text9);
     }
     if (allowExceptions)
     {
         throw new LicenseException(type, instance, text9);
     }
     return null;
 }
        /// <include file='doc\LicFileLicenseProvider.uex' path='docs/doc[@for="LicFileLicenseProvider.GetLicense"]/*' />
        /// <devdoc>
        ///    <para>Gets a license for the instance of the component and determines if it is valid.</para>
        /// </devdoc>
        public override License GetLicense(LicenseContext context, Type type, object instance, bool allowExceptions)
        {
            ProcCountLicense lic = null;

            Debug.Assert(context != null, "No context provided!");
            //if no context is provided, do nothing
            if (context != null)
            {
                //if this control is in runtime mode
                if (context.UsageMode == LicenseUsageMode.Runtime)
                {
                    //retreive the stored license key
                    string key = context.GetSavedLicenseKey(type, null);

                    //check if the stored license key is null
                    // and call IsKeyValid to make sure its valid
                    if (key != null && IsKeyValid(key, type))
                    {
                        //if the key is valid create a new license
                        lic = new ProcCountLicense(this, key);
                    }
                }

                //if we're in design mode or
                //a suitable license key wasn't found in
                //the runtime context.
                //attempt to look for a .LIC file
                if (lic == null)
                {
                    //build up the path where the .LIC file
                    //should be
                    string modulePath = null;

                    // try and locate the file for the assembly
                    if (context != null)
                    {
                        ITypeResolutionService resolver = (ITypeResolutionService)context.GetService(typeof(ITypeResolutionService));
                        if (resolver != null)
                            modulePath = resolver.GetPathOfAssembly(type.Assembly.GetName());
                    }

                    if (modulePath == null)
                        modulePath = type.Module.FullyQualifiedName;

                    //get the path from the file location
                    string moduleDir = Path.GetDirectoryName(modulePath);

                    //build the path of the .LIC file
                    string licenseFile = moduleDir + "\\" + type.FullName + ".lic";

                    Debug.WriteLine("Path of license file: " + licenseFile);

                    //if the .LIC file exists, dig into it
                    if (File.Exists(licenseFile))
                    {
                        //crack the file and get the first line
                        Stream licStream = new FileStream(licenseFile, FileMode.Open, FileAccess.Read, FileShare.Read);
                        StreamReader sr = new StreamReader(licStream);
                        string s = sr.ReadLine();
                        sr.Close();

                        Debug.WriteLine("Contents of license file: " + s);

                        //check if the key is valid
                        if (IsKeyValid(s, type))
                        {
                            //valid key so create a new License
                            lic = new ProcCountLicense(this, s);
                        }
                    }

                    //if we managed to create a license, stuff it into the context
                    if (lic != null)
                    {
                        context.SetSavedLicenseKey(type, lic.LicenseKey);
                    }
                }

            }
            return lic;
        }
        /// <summary>
        /// Extract the license for the given type from the given licenseKey
        /// </summary>
        /// <param name="context">The current licensing context</param>
        /// <param name="type">The type to be licensed</param>
        /// <param name="licenseKey">The encrypted hexadecimal license key</param>
        /// <returns>A license for the given type or NULL if the licenseKey was invalid</returns>
        protected virtual EncryptedLicense LoadLicense(LicenseContext context, Type type, string licenseKey)
        {
            // check that validation parameters have been set by the client
            //
            if (_designSignature == null || _runtimeSignature == null)
                throw new InvalidOperationException("EncryptedLicenseProvider.SetParameters must be called prior to using the EncryptedLicenseProvider");
            if (licenseKey == null) return null;

            try
            {
                byte[] encData = FromHex(licenseKey);

                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                des.Key = _desKey;
                des.IV = _desIV;

                byte[] data = des.CreateDecryptor().TransformFinalBlock(encData, 0, encData.Length);

                // extract the password data and encrypted product data
                //
                byte[] passwordData = new byte[ArraySize(_keyStrength)];
                byte[] encPayload = new byte[ArraySize(data.Length - _keyStrength)];

                // for key strengths greater than 8 the order of payload and key is swapped
                //
                if (_keyStrength < 8)
                {
                    Array.Copy(data, 0, passwordData, 0, _keyStrength);
                    Array.Copy(data, _keyStrength, encPayload, 0, encPayload.Length);
                }
                else
                {
                    Array.Copy(data, 0, encPayload, 0, encPayload.Length);
                    Array.Copy(data, encPayload.Length, passwordData, 0, _keyStrength);
                }

                // the key used to encrypt payload is just the first 7 bytes of the password data
                //
                byte[] encryptionKey = new byte[ArraySize(8)];
                Array.Copy(passwordData, 0, encryptionKey, 0, 7);

                // validate that the password matches what the client is expecting
                //
                CspParameters cspParams = new CspParameters();

                // if we are running in a server or ASP then ensure that we use the machine CSP
                // store to avoid problems.
                //
                if (!Environment.UserInteractive || UseMachineKeyStore)
                {
                    cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
                }
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cspParams);
                rsa.ImportParameters(_rsaParameters);

                byte[] paddedPasswordData = PadPassword(passwordData);
                if (context.UsageMode == LicenseUsageMode.Designtime)
                {

                    // if design time license requested then the license MUST be a design license
                    //
                    if (!rsa.VerifyData(paddedPasswordData, new SHA1CryptoServiceProvider(), _designSignature)) return null;
                }
                else
                {
                    // if runtime license requested then first check if the license is a runtime license
                    // also allow design licenses to work at runtime
                    //
                    if (!rsa.VerifyData(paddedPasswordData, new SHA1CryptoServiceProvider(), _runtimeSignature))
                    {
                        if (!rsa.VerifyData(paddedPasswordData, new SHA1CryptoServiceProvider(), _designSignature)) return null;
                    }
                }

                // decrypt the payload using the encryption key
                //
                des.IV = encryptionKey;
                byte[] payload = des.CreateDecryptor().TransformFinalBlock(encPayload, 0, encPayload.Length);

                int checksumLength = (_checksumProductInfo) ? 2 : 0;
                byte[] productData = new byte[ArraySize(payload.Length - 2 - checksumLength)];
                Array.Copy(payload, 2, productData, 0, productData.Length);

                UInt16 serialNo = BitConverter.ToUInt16(payload, 0);
                string product = System.Text.ASCIIEncoding.UTF8.GetString(productData);

                // validate the product data checksum
                //
                if (_checksumProductInfo)
                {
                    UInt16 requiredChecksum = BitConverter.ToUInt16(payload, payload.Length - checksumLength);
                    UInt16 actualChecksum = Checksum(productData);
                    if (requiredChecksum != actualChecksum)
                        return null;
                }

                // if in design time then create a runtime license and save it
                //
                if (context.UsageMode == LicenseUsageMode.Designtime && type != null)
                {

                    // create the runtime password by encrypting the design password
                    //
                    byte[] encPassword = des.CreateEncryptor().TransformFinalBlock(paddedPasswordData, 0, paddedPasswordData.Length);
                    byte[] runtimePasswordData = new byte[ArraySize(_keyStrength)];
                    Array.Copy(encPassword, 0, runtimePasswordData, 0, _keyStrength);

                    string runtimeLicenseKey = GenerateKey(_keyStrength, runtimePasswordData, productData,_checksumProductInfo, serialNo);

                    // save the runtime key into the context
                    //
                    context.SetSavedLicenseKey(type, runtimeLicenseKey);
                }
                return new EncryptedLicense(licenseKey, serialNo, product);
            }
            catch
            {
                return null;
            }
        }
Example #37
0
        /// <summary>
        ///    <para>Creates an instance of the specified type with the 
        ///       specified arguments, using creationContext as the context in which the licensed
        ///       instance can be used.</para>
        /// </summary>
        public static object CreateWithContext(Type type, LicenseContext creationContext, object[] args)
        {
            object created = null;

            lock (s_internalSyncObject)
            {
                LicenseContext normal = CurrentContext;
                try
                {
                    CurrentContext = creationContext;
                    LockContext(s_selfLock);
                    try
                    {
                        created = SecurityUtils.SecureCreateInstance(type, args);
                    }
                    catch (TargetInvocationException e)
                    {
                        throw e.InnerException;
                    }
                }
                finally
                {
                    UnlockContext(s_selfLock);
                    CurrentContext = normal;
                }
            }

            return created;
        }
Example #38
0
        /// <summary>
        /// Since we want to walk up the entire inheritance change, when not
        /// give an instance, we need another helper method to walk up
        /// the chain...
        /// </summary>
        private static bool ValidateInternalRecursive(LicenseContext context, Type type, object?instance, bool allowExceptions, out License?license, out string?licenseKey)
        {
            LicenseProvider?provider = GetCachedProvider(type);

            if (provider == null && !GetCachedNoLicenseProvider(type))
            {
                // NOTE : Must look directly at the class, we want no inheritance.
                LicenseProviderAttribute?attr = (LicenseProviderAttribute?)Attribute.GetCustomAttribute(type, typeof(LicenseProviderAttribute), false);

                if (attr != null)
                {
                    Type providerType = attr.LicenseProvider !;
                    provider = GetCachedProviderInstance(providerType) ?? (LicenseProvider)Activator.CreateInstance(providerType) !;
                }

                CacheProvider(type, provider);
            }

            license = null;
            bool isValid = true;

            licenseKey = null;
            if (provider != null)
            {
                license = provider.GetLicense(context, type, instance, allowExceptions);
                if (license == null)
                {
                    isValid = false;
                }
                else
                {
                    // For the case where a COM client is calling "RequestLicKey",
                    // we try to squirrel away the first found license key
                    licenseKey = license.LicenseKey;
                }
            }

            // When looking only at a type, we need to recurse up the inheritance
            // chain, however, we can't give out the license, since this may be
            // from more than one provider.
            if (isValid && instance == null)
            {
                Type?baseType = type.BaseType;
                if (baseType != typeof(object) && baseType != null)
                {
                    if (license != null)
                    {
                        license.Dispose();
#pragma warning disable IDE0059 // ValidateInternalRecursive does not null licence all the time (https://github.com/dotnet/roslyn/issues/42761)
                        license = null;
#pragma warning restore IDE0059
                    }
                    isValid = ValidateInternalRecursive(context, baseType, null, allowExceptions, out license, out _);
                    if (license != null)
                    {
                        license.Dispose();
                        license = null;
                    }
                }
            }

            return(isValid);
        }
Example #39
0
 public override License GetLicense(LicenseContext context, Type type, object instance, bool allowExceptions)
 {
     throw new NotImplementedException();
 }
 /// <summary>
 /// Return the license for the given type from a given DLL assembly resources
 /// </summary>
 /// <param name="context">The license context to validate the license in</param>
 /// <param name="assembly">The assembly containing the license</param>
 /// <param name="type">The type to get the license for</param>
 /// <returns>The license key if any</returns>
 /// <remarks>
 /// This method can be used to check the given DLL assembly for a license.  By default the .NET licensing
 /// framework only checks the entry assembly (ie typically executables) for licenses.  This means
 /// that if a licensed control is wrapped in another control, the customer of the wrapped control will
 /// still required a design time license key for the original control.  This is generally the behaviour
 /// that control authors would like.  If however you want to provide a license that enables a customer
 /// to create new component/controls using your control/component then you can achieve this by using 
 /// this method to check for a license in the CallingAssembly that created the control/component.
 /// </remarks>
 public virtual EncryptedLicense GetLicense(LicenseContext context, Assembly assembly, Type type)
 {
     if (assembly == null) return null;
     EncryptedLicense license = null;
     string licenseKey = GetSavedLicenseKey(assembly, type);
     if (licenseKey != null)
     {
         license = LoadLicense(context, null, licenseKey);
     }
     return license;
 }
 public abstract License GetLicense(LicenseContext context, Type type, object instance, bool allowExceptions);
Example #42
0
 public static object CreateWithContext(
     [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type,
     LicenseContext creationContext)
 {
     return(CreateWithContext(type, creationContext, Array.Empty <object>()));
 }
	// Get the license for a type.
	public abstract License GetLicense
			(LicenseContext context, Type type, Object instance,
			 bool allowExceptions);
Example #44
0
 // Get the license for a type.
 public override License GetLicense
     (LicenseContext context, Type type, Object instance,
     bool allowExceptions)
 {
     return(new DefaultLicense(type.FullName));
 }
        /// <summary>
        /// Return the directory used to store license files
        /// </summary>
        /// <param name="context">The licence context</param>
        /// <param name="type">The type being licensed</param>
        /// <returns>The directory to look for license files</returns>
        protected virtual string GetLicenseDirectory(LicenseContext context, Type type)
        {
            string result = null;

            // try to use the type resolver service if available
            //
            if (context != null && type != null)
            {
                ITypeResolutionService resolver = (ITypeResolutionService)context.GetService(typeof(ITypeResolutionService));
                if (resolver != null)
                    result = resolver.GetPathOfAssembly(type.Assembly.GetName());
            }

            if (result == null)
            {
                if (type == null)
                {
                    result = AppDomain.CurrentDomain.BaseDirectory;
                }
                else
                {
                    Assembly assembly = type.Assembly;

                    // use the code base if possible
                    //
                    result = assembly.CodeBase;
                    if (result.StartsWith(@"file:///"))
                    {
                        result = result.Replace(@"file:///", "");
                    }
                    else
                    {
                        result = type.Module.FullyQualifiedName;
                    }
                }
            }
            return Path.GetDirectoryName(result);
        }
 public static Object CreateWithContext(Type type, LicenseContext creationContext)
 {
     return(default(Object));
 }
 /// <summary>
 /// Get a license (if installed) for the given context, type and instance
 /// </summary>
 /// <param name="context">The context (design or runtime)</param>
 /// <param name="type">The type to get the license for</param>
 /// <param name="instance"></param>
 /// <param name="allowExceptions">If true LicenseException is thrown if a valid license cannot be loaded</param>
 /// <returns>An encrypted license</returns>
 public override License GetLicense(LicenseContext context, Type type, object instance, bool allowExceptions)
 {
     string licenseKey = GetLicenseKey(context, type);
     License license = LoadLicense(context, type, licenseKey);
     if (license == null && allowExceptions)
     {
         if (instance == null)
             throw new LicenseException(type);
         else
             throw new LicenseException(type, instance);
     }
     return license;
 }
Example #48
0
 /// <include file='doc\LicenseManager.uex' path='docs/doc[@for="LicenseManager.CreateWithContext"]/*' />
 /// <devdoc>
 ///    <para>Creates an instance of the specified type, using
 ///       creationContext
 ///       as the context in which the licensed instance can be used.</para>
 /// </devdoc>
 public static object CreateWithContext(Type type, LicenseContext creationContext)
 {
     return(CreateWithContext(type, creationContext, new object[0]));
 }
        /// <summary>
        /// Return the directory used to store license files
        /// </summary>
        /// <param name="context">The licence context</param>
        /// <param name="type">The type being licensed</param>
        /// <returns>The directory to look for license files</returns>
        protected virtual string GetLicenseDirectory(LicenseContext context, Type type)
        {
            string result = null;

            // try to use the type resolver service if available
            //
            if (context != null)
            {
                ITypeResolutionService resolver = (ITypeResolutionService)context.GetService(typeof(ITypeResolutionService));
                if (resolver != null)
                    result = resolver.GetPathOfAssembly(type.Assembly.GetName());
            }

            if (result == null)
            {
                // use the code base if possible - because this works properly under ASP.NET
                // where as the Module.FullyQualifiedName points to a temporary file
                //
                result = type.Assembly.CodeBase;
                if (result.StartsWith(@"file:///"))
                {
                    result = result.Replace(@"file:///", "");
                }
                else
                {
                    result = type.Module.FullyQualifiedName;
                }
            }
            return Path.GetDirectoryName(result);
        }
Example #50
0
 public static object CreateWithContext(Type type, LicenseContext creationContext, object[] args)
 {
     throw new NotImplementedException();
 }
 /// <summary>
 /// Called by GetLicenseKey to get the file path to obtain the license from (if there is no runtime license saved in the context)
 /// </summary>
 /// <remarks>
 /// This can be overridden to change the file used to store the design time license for the provider.   By default the
 /// the license file is stored in the same directory as the component executable with the name based on the fully
 /// qualified type name eg MyNamespace.MyControl.lic
 /// </remarks>
 /// <seealso cref="GetLicenseKey"/>
 /// <param name="context">The licence context</param>
 /// <param name="type">The type to get the license for</param>
 /// <returns>The path of the license file</returns>
 protected virtual string GetLicenseFilePath(LicenseContext context, Type type)
 {
     string dir = GetLicenseDirectory(context, type);
     return String.Format(@"{0}\{1}.lic", dir, type.FullName);
 }
        /// <include file='doc\LicenseManager.uex' path='docs/doc[@for="LicenseManager.ValidateInternalRecursive"]/*' />
        /// <devdoc>
        ///     Since we want to walk up the entire inheritance change, when not 
        ///     give an instance, we need another helper method to walk up
        ///     the chain...
        /// </devdoc>
        private static bool ValidateInternalRecursive(LicenseContext context, Type type, object instance, bool allowExceptions, out License license, out string licenseKey) {
            LicenseProvider provider = GetCachedProvider(type);
            if (provider == null && !GetCachedNoLicenseProvider(type)) {
                // NOTE : Must look directly at the class, we want no inheritance.
                //
                LicenseProviderAttribute attr = (LicenseProviderAttribute)Attribute.GetCustomAttribute(type, typeof(LicenseProviderAttribute), false);
                if (attr != null) {
                    Type providerType = attr.LicenseProvider;
                    provider = GetCachedProviderInstance(providerType);

                    if (provider == null) {
                        provider = (LicenseProvider)SecurityUtils.SecureCreateInstance(providerType);
                    }
                }

                CacheProvider(type, provider);
            }

            license = null;
            bool isValid = true;

            licenseKey = null;
            if (provider != null) {
                license = provider.GetLicense(context, type, instance, allowExceptions);
                if (license == null) {
                    isValid = false;
                }
                else {
                    // For the case where a COM client is calling "RequestLicKey", 
                    // we try to squirrel away the first found license key
                    //
                    licenseKey = license.LicenseKey;
                }
            }

            // When looking only at a type, we need to recurse up the inheritence
            // chain, however, we can't give out the license, since this may be
            // from more than one provider.
            //
            if (isValid && instance == null) {
                Type baseType = type.BaseType;
                if (baseType != typeof(object) && baseType != null) {
                    if (license != null) {
                        license.Dispose();
                        license = null;
                    }
                    string temp;
                    isValid = ValidateInternalRecursive(context, baseType, null, allowExceptions, out license, out temp);
                    if (license != null) {
                        license.Dispose();
                        license = null;
                    }
                }
            }

            return isValid;
        }
        /// <summary>
        /// Return the license key for the given context and type
        /// </summary>
        /// <remarks>
        /// This can be overridden to change where the license key is stored by the provider.   For
        /// instance a derived class could override this method to store the key in the Registry.
        /// </remarks>
        /// <param name="context">The license context</param>
        /// <param name="type">The type to get the key for</param>
        /// <returns>The license key</returns>
        protected virtual string GetLicenseKey(LicenseContext context, Type type)
        {
            string key = null;
            if (context.UsageMode == LicenseUsageMode.Runtime)
            {
                key = context.GetSavedLicenseKey(type, null);
            }

            // Try and loaded license from registry
            if (key == null)
            {
                key = ReadKeyFromRegistry();
            }

            // if we're in design mode or a suitable license key wasn't found in
            // the runtime context look for a .LIC file
            //
            if (key == null)
            {
                key = ReadKeyFromFile(GetLicenseFilePath(context, type));
            }
            return key;
        }
        /// <summary>
        /// Extract the license for the given type from the given licenseKey
        /// </summary>
        /// <param name="context">The current licensing context</param>
        /// <param name="type">The type to be licensed</param>
        /// <param name="licenseKey">The encrypted hexadecimal license key</param>
        /// <returns>A license for the given type or NULL if the licenseKey was invalid</returns>
        private EncryptedLicense LoadLicense(LicenseContext context, Type type, string licenseKey)
        {
            // check that validation parameters have been set by the client
            //
            if (_rsaParameters == null || _designSignature == null || _runtimeSignature == null)
                throw new InvalidOperationException("EncryptedLicenseProvider.SetParameters must be called prior to using the EncryptedLicenseProvider");
            if (licenseKey == null) return null;

            try
            {
                byte[] encData = FromHex(licenseKey);

                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                des.Key = _desKey;
                des.IV = _desIV;

                byte[] data = des.CreateDecryptor().TransformFinalBlock(encData, 0, encData.Length);

                // extract the encryption key and encrypted product data - note that the encryption
                // key has only 7 significant bytes
                //
                byte[] encryptionKey = new byte[ArraySize(8)];
                byte[] encPayload = new byte[ArraySize(data.Length - keyLength)];

                Array.Copy(data, 0, encryptionKey, 0, keyLength);
                Array.Copy(data, keyLength, encPayload, 0, encPayload.Length);

                // validate that the password matches what the client is expecting
                //
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                rsa.FromXmlString(_rsaParameters);

                if (context.UsageMode == LicenseUsageMode.Designtime)
                {
                    // if design time license requested then the license MUST be a design license
                    //
                    if (!rsa.VerifyData(encryptionKey, new SHA1CryptoServiceProvider(), _designSignature)) return null;
                }
                else
                {
                    // if runtime license requested then first check if the license is a runtime license
                    // also allow design licenses to work at runtime
                    //
                    if (!rsa.VerifyData(encryptionKey, new SHA1CryptoServiceProvider(), _runtimeSignature))
                    {
                        if (!rsa.VerifyData(encryptionKey, new SHA1CryptoServiceProvider(), _designSignature)) return null;
                    }
                }

                // decrypt the payload using the encryption key
                //
                des.IV = encryptionKey;
                byte[] payload = des.CreateDecryptor().TransformFinalBlock(encPayload, 0, encPayload.Length);
                byte[] productData = new byte[ArraySize(payload.Length - 2)];
                Array.Copy(payload, 2, productData, 0, productData.Length);

                UInt16 serialNo = BitConverter.ToUInt16(payload, 0);
                string product = System.Text.ASCIIEncoding.UTF8.GetString(productData);

                // if in design time then create a runtime license and save it
                //
                if (context.UsageMode == LicenseUsageMode.Designtime && type != null)
                {
                    // create the runtime password by encrypting the design time license
                    //
                    byte[] encKey = des.CreateEncryptor().TransformFinalBlock(encryptionKey, 0, encryptionKey.Length);
                    byte[] runtimeKey = new byte[ArraySize(8)];
                    Array.Copy(encKey, 0, runtimeKey, 0, keyLength);

                    // encrypt the payload using the runtime key
                    //
                    des.IV = runtimeKey;
                    encPayload = des.CreateEncryptor().TransformFinalBlock(payload, 0, payload.Length);

                    // Combine the runtime key and encrypted payload
                    // Note that only the first 7 bytes of the key contain information so we
                    // only pack this much information - this enables us to reduce the size of
                    // the final key by 8 bytes.
                    //
                    data = new byte[ArraySize(keyLength + encPayload.Length)];
                    runtimeKey.CopyTo(data, 0);
                    encPayload.CopyTo(data, keyLength);

                    // encrypt again to obscure the password - this time using preset encryption key
                    //
                    des.IV = _desIV;
                    encData = des.CreateEncryptor().TransformFinalBlock(data, 0, data.Length);

                    string runtimeLicenseKey = ToHex(encData);

                    // save the runtime key into the context
                    //
                    context.SetSavedLicenseKey(type, runtimeLicenseKey);
                }
                return new EncryptedLicense(licenseKey, serialNo, product);
            }
            catch
            {
                return null;
            }
        }
 public static Object CreateWithContext(Type type, LicenseContext creationContext)
 {
   return default(Object);
 }