Inheritance: System.ComponentModel.LicenseContext
	// Serialize a license key to a stream.
	public static void Serialize(Stream o, String cryptoKey,
		     					 DesigntimeLicenseContext context)
			{
				BinaryFormatter formatter = new BinaryFormatter();
				formatter.Serialize
					(o, new Object [] {cryptoKey, context.keys});
			}
        private static void SerializeWithBinaryFormatter(Stream o, string cryptoKey, DesigntimeLicenseContext context)
        {
            IFormatter formatter = new BinaryFormatter();

#pragma warning disable SYSLIB0011
            formatter.Serialize(o, new object[] { cryptoKey, context._savedLicenseKeys });
#pragma warning restore SYSLIB0011
        }
        /// <summary>
        /// Serializes the licenses within the specified design-time license context
        /// using the specified key and output stream.
        /// </summary>
        public static void Serialize(Stream o, string cryptoKey, DesigntimeLicenseContext context)
        {
            IFormatter formatter = new BinaryFormatter();

#pragma warning disable SYSLIB0011 // Issue https://github.com/dotnet/runtime/issues/39293 tracks finding an alternative to BinaryFormatter
            formatter.Serialize(o, new object[] { cryptoKey, context._savedLicenseKeys });
#pragma warning restore SYSLIB0011
        }
Exemplo n.º 4
0
        // Serialize a license key to a stream.
        public static void Serialize(Stream o, String cryptoKey,
                                     DesigntimeLicenseContext context)
        {
            BinaryFormatter formatter = new BinaryFormatter();

            formatter.Serialize
                (o, new Object [] { cryptoKey, context.keys });
        }
Exemplo n.º 5
0
        private static void SerializeWithBinaryFormatter(Stream o, string cryptoKey, DesigntimeLicenseContext context)
        {
            IFormatter formatter = new BinaryFormatter();

#pragma warning disable SYSLIB0011
#pragma warning disable IL2026 // suppressed in ILLink.Suppressions.LibraryBuild.xml
            formatter.Serialize(o, new object[] { cryptoKey, context._savedLicenseKeys });
#pragma warning restore IL2026
#pragma warning restore SYSLIB0011
        }
		public static void Serialize (Stream o, string cryptoKey, DesigntimeLicenseContext context)
		{
			object [] lData = new object [2];
			lData [0] = cryptoKey;
			Hashtable lNewTable = new Hashtable ();
			foreach (DictionaryEntry et in context.keys) {
				lNewTable.Add (((Type) et.Key).AssemblyQualifiedName, et.Value);
			}
			lData[1] = lNewTable;

			BinaryFormatter lFormatter = new BinaryFormatter ();
			lFormatter.Serialize (o, lData);
		}
        public static void Serialize(Stream o, string cryptoKey, DesigntimeLicenseContext context)
        {
            object [] lData = new object [2];
            lData [0] = cryptoKey;
            Hashtable lNewTable = new Hashtable();

            foreach (DictionaryEntry et in context.keys)
            {
                lNewTable.Add(((Type)et.Key).AssemblyQualifiedName, et.Value);
            }
            lData[1] = lNewTable;

            BinaryFormatter lFormatter = new BinaryFormatter();

            lFormatter.Serialize(o, lData);
        }
 /// <summary>
 /// Serializes the licenses within the specified design-time license context
 /// using the specified key and output stream.
 /// </summary>
 public static void Serialize(Stream o, string cryptoKey, DesigntimeLicenseContext context)
 {
     if (EnableUnsafeBinaryFormatterInDesigntimeLicenseContextSerialization)
     {
         SerializeWithBinaryFormatter(o, cryptoKey, context);
     }
     else
     {
         using (BinaryWriter writer = new BinaryWriter(o, encoding: Text.Encoding.UTF8, leaveOpen: true))
         {
             writer.Write(BinaryWriterMagic); // flag to identify BinaryWriter
             writer.Write(cryptoKey);
             writer.Write(context._savedLicenseKeys.Count);
             foreach (DictionaryEntry keyAndValue in context._savedLicenseKeys)
             {
                 writer.Write(keyAndValue.Key.ToString() !);
                 writer.Write(keyAndValue.Value !.ToString() !);
             }
         }
     }
 }
            // The CLR invokes this whenever a COM client invokes
            // IClassFactory2::GetLicInfo on a managed class.
            //
            // COM normally doesn't expect this function to fail so this method
            // should only throw in the case of a catastrophic error (stack, memory, etc.)
            private void GetLicInfo(RuntimeTypeHandle rth, ref int pRuntimeKeyAvail, ref int pLicVerified) {
                pRuntimeKeyAvail = 0;
                pLicVerified = 0;

                Type type = Type.GetTypeFromHandle(rth);
                License license;
                string licenseKey;

                if (helperContext == null) {
                    helperContext = new DesigntimeLicenseContext();
                }
                else {
                    helperContext.savedLicenseKeys.Clear();
                }

                if (LicenseManager.ValidateInternalRecursive(helperContext, type, null, false, out license, out licenseKey)) {

                    if (helperContext.savedLicenseKeys.Contains(type.AssemblyQualifiedName)) {
                        pRuntimeKeyAvail = 1;
                    }

                    if (license != null) {
                        license.Dispose();
                        license = null;

                        pLicVerified = 1;
                    }
                }
            }
Exemplo n.º 10
0
            /// <summary>
            /// Creates the whole license file.
            /// </summary>
            /// <param name="licenseTask">The <see cref="LicenseTask" /> instance for which the license file should be created.</param>
            /// <param name="licensesFile">The .licenses file to create.</param>
            public void CreateLicenseFile(LicenseTask licenseTask, string licensesFile) {
                ArrayList assemblies = new ArrayList();

                // create assembly resolver
                AssemblyResolver assemblyResolver = new AssemblyResolver(licenseTask);

                // attach assembly resolver to the current domain
                assemblyResolver.Attach();

                licenseTask.Log(Level.Verbose, ResourceUtils.GetString("String_LoadingAssemblies"));

                try {
                    // first, load all the assemblies so that we can search for the 
                    // licensed component
                    foreach (string assemblyFileName in licenseTask.Assemblies.FileNames) {
                        Assembly assembly = Assembly.LoadFrom(assemblyFileName);
                        if (assembly != null) {
                            // output assembly filename to build log
                            licenseTask.Log(Level.Verbose, ResourceUtils.GetString("String_AssemblyLoaded"), 
                                assemblyFileName);
                            // add assembly to list of loaded assemblies
                            assemblies.Add(assembly);
                        }
                    }

                    DesigntimeLicenseContext dlc = new DesigntimeLicenseContext();
                    LicenseManager.CurrentContext = dlc;

                    // read the input file
                    using (StreamReader sr = new StreamReader(licenseTask.InputFile.FullName)) {
                        Hashtable licenseTypes = new Hashtable();

                        licenseTask.Log(Level.Verbose, ResourceUtils.GetString("String_CreatingLicenses"));

                        while (true) {
                            string line = sr.ReadLine();

                            if (line == null) {
                                break;
                            }

                            line = line.Trim();
                            // Skip comments, empty lines and already processed assemblies
                            if (line.StartsWith("#") || line.Length == 0 || licenseTypes.Contains(line)) {
                                continue;
                            }

                            licenseTask.Log(Level.Verbose, "{0}: ", line);

                            // Strip off the assembly name, if it exists
                            string typeName;

                            if (line.IndexOf(',') != -1) {
                                typeName = line.Split(',')[0];
                            } else {
                                typeName = line;
                            }

                            Type tp = null;

                            // try to locate the type in each assembly
                            foreach (Assembly assembly in assemblies) {
                                if (tp == null) {
                                    tp = assembly.GetType(typeName, false, true);
                                }

                                if (tp != null) {
                                    break;
                                }
                            }

                            if (tp == null) {
                                try {
                                    // final attempt, assuming line contains
                                    // assembly qualfied name
                                    tp = Type.GetType(line, false, false);
                                } catch {
                                    // ignore error, we'll report the load
                                    // failure later
                                }
                            }

                            if (tp == null) {
                                throw new BuildException(string.Format(CultureInfo.InvariantCulture,  
                                    ResourceUtils.GetString("NA2016"), typeName), licenseTask.Location);
                            } else {
                                // add license type to list of processed license types
                                licenseTypes[line] = tp;
                            }

                            // ensure that we've got a licensed component
                            if (tp.GetCustomAttributes(typeof(LicenseProviderAttribute), true).Length == 0) {
                                throw new BuildException(string.Format(CultureInfo.InvariantCulture,  
                                    ResourceUtils.GetString("NA2017"), tp.FullName), 
                                    licenseTask.Location);
                            }

                            try {
                                LicenseManager.CreateWithContext(tp, dlc);
                            } catch (Exception ex) {
                                if (IsSerializable(ex)) {
                                    throw new BuildException(string.Format(CultureInfo.InvariantCulture, 
                                        ResourceUtils.GetString("NA2018"), tp.FullName), 
                                        licenseTask.Location, ex);
                                }

                                // do not directly pass the exception as inner 
                                // exception to BuildException as the exception
                                // is not serializable, so construct a new 
                                // exception with message set to message of 
                                // original exception
                                throw new BuildException(string.Format(CultureInfo.InvariantCulture, 
                                    ResourceUtils.GetString("NA2018"), tp.FullName), 
                                    licenseTask.Location, new Exception(ex.Message));
                            }
                        }
                    }

                    // overwrite the existing file, if it exists - is there a better way?
                    if (File.Exists(licensesFile)) {
                        File.SetAttributes(licensesFile, FileAttributes.Normal);
                        File.Delete(licensesFile);
                    }

                    // write out the license file, keyed to the appropriate output 
                    // target filename
                    // this .license file will only be valid for this exe/dll
                    using (FileStream fs = new FileStream(licensesFile, FileMode.Create)) {
                        DesigntimeLicenseContextSerializer.Serialize(fs, licenseTask.Target, dlc);
                        licenseTask.Log(Level.Verbose, ResourceUtils.GetString("String_CreatedNewLicense"),
                            licensesFile);
                    }

                    dlc = null;
                } catch (BuildException) {
                    // re-throw exception
                    throw;
                } catch (Exception ex) {
                    if (IsSerializable(ex)) {
                        throw new BuildException(string.Format(CultureInfo.InvariantCulture, 
                            ResourceUtils.GetString("NA2019"), licenseTask.InputFile.FullName), 
                            licenseTask.Location, ex);
                    } else {
                        // do not directly pass the exception as inner exception to 
                        // BuildException as the exception might not be serializable, 
                        // so construct a
                        // new exception with message set to message of
                        // original exception
                        throw new BuildException(string.Format(CultureInfo.InvariantCulture, 
                            ResourceUtils.GetString("NA2019"), licenseTask.InputFile.FullName), 
                            licenseTask.Location, new Exception(ex.Message));
                    }
                } finally {
                    // detach assembly resolver from the current domain
                    assemblyResolver.Detach();
                }
            }
Exemplo n.º 11
0
        public void Test()
        {
            object lockObject = new object();
            //**DEFAULT CONTEXT & LicenseUsageMode**
            //Get CurrentContext, check default type
            Assert.Equal("System.ComponentModel.Design.RuntimeLicenseContext", LicenseManager.CurrentContext.GetType().ToString());
            //Read default LicenseUsageMode, check against CurrentContext (LicCont).UsageMode
            Assert.Equal(LicenseManager.CurrentContext.UsageMode, LicenseManager.UsageMode);

            //**CHANGING CONTEXT**
            //Change the context and check it changes
            LicenseContext oldcontext = LicenseManager.CurrentContext;
            LicenseContext newcontext = new DesigntimeLicenseContext();
            LicenseManager.CurrentContext = newcontext;
            Assert.Equal(newcontext, LicenseManager.CurrentContext);
            //Check the UsageMode changed too
            Assert.Equal(newcontext.UsageMode, LicenseManager.UsageMode);
            //Set Context back to original
            LicenseManager.CurrentContext = oldcontext;
            //Check it went back
            Assert.Equal(oldcontext, LicenseManager.CurrentContext);
            //Check the UsageMode changed too
            Assert.Equal(oldcontext.UsageMode, LicenseManager.UsageMode);

            //**CONTEXT LOCKING**
            //Lock the context
            LicenseManager.LockContext(lockObject);
            //Try and set new context again, should throw System.InvalidOperationException: The CurrentContext property of the LicenseManager is currently locked and cannot be changed.
            bool exceptionThrown = false;
            try
            {
                LicenseManager.CurrentContext = newcontext;
            }
            catch (Exception e)
            {
                Assert.Equal(typeof(InvalidOperationException), e.GetType());
                exceptionThrown = true;
            }
            //Check the exception was thrown
            Assert.Equal(true, exceptionThrown);
            //Check the context didn't change
            Assert.Equal(oldcontext, LicenseManager.CurrentContext);
            //Unlock it
            LicenseManager.UnlockContext(lockObject);
            //Now's unlocked, change it
            LicenseManager.CurrentContext = newcontext;
            Assert.Equal(newcontext, LicenseManager.CurrentContext);
            //Change it back
            LicenseManager.CurrentContext = oldcontext;


            //Lock the context
            LicenseManager.LockContext(lockObject);
            //Unlock with different "user" should throw System.ArgumentException: The CurrentContext property of the LicenseManager can only be unlocked with the same contextUser.
            object wrongLockObject = new object();
            exceptionThrown = false;
            try
            {
                LicenseManager.UnlockContext(wrongLockObject);
            }
            catch (Exception e)
            {
                Assert.Equal(typeof(ArgumentException), e.GetType());
                exceptionThrown = true;
            }
            Assert.Equal(true, exceptionThrown);
            //Unlock it
            LicenseManager.UnlockContext(lockObject);

            //** bool IsValid(Type);
            Assert.Equal(true, LicenseManager.IsLicensed(typeof(UnlicensedObject)));
            Assert.Equal(true, LicenseManager.IsLicensed(typeof(LicensedObject)));
            Assert.Equal(false, LicenseManager.IsLicensed(typeof(InvalidLicensedObject)));

            Assert.Equal(true, LicenseManager.IsValid(typeof(UnlicensedObject)));
            Assert.Equal(true, LicenseManager.IsValid(typeof(LicensedObject)));
            Assert.Equal(false, LicenseManager.IsValid(typeof(InvalidLicensedObject)));

            UnlicensedObject unlicensedObject = new UnlicensedObject();
            LicensedObject licensedObject = new LicensedObject();
            InvalidLicensedObject invalidLicensedObject = new InvalidLicensedObject();

            //** bool IsValid(Type, object, License);
            License license = null;
            Assert.Equal(true, LicenseManager.IsValid(unlicensedObject.GetType(), unlicensedObject, out license));
            Assert.Equal(null, license);

            license = null;
            Assert.Equal(true, LicenseManager.IsValid(licensedObject.GetType(), licensedObject, out license));
            Assert.Equal("TestLicense", license.GetType().Name);

            license = null;
            Assert.Equal(false, LicenseManager.IsValid(invalidLicensedObject.GetType(), invalidLicensedObject, out license));
            Assert.Equal(null, license);

            //** void Validate(Type);
            //Shouldn't throw exception
            LicenseManager.Validate(typeof(UnlicensedObject));
            //Shouldn't throw exception
            LicenseManager.Validate(typeof(LicensedObject));
            //Should throw exception
            exceptionThrown = false;
            try
            {
                LicenseManager.Validate(typeof(InvalidLicensedObject));
            }
            catch (Exception e)
            {
                Assert.Equal(typeof(LicenseException), e.GetType());
                exceptionThrown = true;
            }
            //Check the exception was thrown
            Assert.Equal(true, exceptionThrown);

            //** License Validate(Type, object);
            //Shouldn't throw exception, returns null license
            license = LicenseManager.Validate(typeof(UnlicensedObject), unlicensedObject);
            Assert.Equal(null, license);

            //Shouldn't throw exception, returns TestLicense license
            license = LicenseManager.Validate(typeof(LicensedObject), licensedObject);
            Assert.Equal("TestLicense", license.GetType().Name);

            //Should throw exception, returns null license
            exceptionThrown = false;
            try
            {
                license = null;
                license = LicenseManager.Validate(typeof(InvalidLicensedObject), invalidLicensedObject);
            }
            catch (Exception e)
            {
                Assert.Equal(typeof(LicenseException), e.GetType());
                exceptionThrown = true;
            }
            //Check the exception was thrown
            Assert.Equal(true, exceptionThrown);
            Assert.Equal(null, license);


            //** object CreateWithContext (Type, LicenseContext);
            object cwc = null;
            //Test we can create an unlicensed object with no context
            cwc = LicenseManager.CreateWithContext(typeof(UnlicensedObject), null);
            Assert.Equal("UnlicensedObject", cwc.GetType().Name);
            //Test we can create RunTime with CurrentContext (runtime)
            cwc = null;
            cwc = LicenseManager.CreateWithContext(typeof(RuntimeLicensedObject),
                LicenseManager.CurrentContext);
            Assert.Equal("RuntimeLicensedObject", cwc.GetType().Name);
            //Test we can't create DesignTime with CurrentContext (runtime)
            exceptionThrown = false;
            try
            {
                cwc = null;
                cwc = LicenseManager.CreateWithContext(typeof(DesigntimeLicensedObject), LicenseManager.CurrentContext);
            }
            catch (Exception e)
            {
                Assert.Equal(typeof(LicenseException), e.GetType());
                exceptionThrown = true;
            }
            //Check the exception was thrown
            Assert.Equal(true, exceptionThrown);
            //Test we can create DesignTime with A new DesignTimeContext 
            cwc = null;
            cwc = LicenseManager.CreateWithContext(typeof(DesigntimeLicensedObject),
                new DesigntimeLicenseContext());
            Assert.Equal("DesigntimeLicensedObject", cwc.GetType().Name);

            //** object CreateWithContext(Type, LicenseContext, object[]);
            //Test we can create RunTime with CurrentContext (runtime)
            cwc = null;
            cwc = LicenseManager.CreateWithContext(typeof(RuntimeLicensedObject),
                LicenseManager.CurrentContext, new object[] { 7 });
            Assert.Equal("RuntimeLicensedObject", cwc.GetType().Name);

        }
Exemplo n.º 12
0
 public static void Serialize(Stream o,
                              string cryptoKey,
                              DesigntimeLicenseContext context)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 13
0
Arquivo: lc.cs Projeto: nobled/mono
        private static void IntSerialize(Stream o,
                          string cryptoKey,
                          DesigntimeLicenseContext context)
        {
            Object[] lData = new Object[2];
            lData[0] = cryptoKey;
            Hashtable lNewTable = new Hashtable();
            FieldInfo fi =
                typeof(DesigntimeLicenseContext).GetField("savedLicenseKeys", BindingFlags.NonPublic | BindingFlags.Instance) ??
                typeof(DesigntimeLicenseContext).GetField("keys", BindingFlags.NonPublic | BindingFlags.Instance)
                ;
            Hashtable lOrgTable = (Hashtable)fi.GetValue(context);
            foreach (DictionaryEntry et in lOrgTable)
            {
                if (et.Key is string)
                    lNewTable.Add(et.Key, et.Value);
                else
                    lNewTable.Add(((Type)et.Key).AssemblyQualifiedName, et.Value);
            }
            lData[1] = lNewTable;

            BinaryFormatter lFormatter = new BinaryFormatter();
            lFormatter.Serialize(o, lData);

        }
 public static void Serialize(Stream o, string cryptoKey, DesigntimeLicenseContext context)
 {
     Contract.Requires(context != null);
 }
 public static void Serialize(Stream o, string cryptoKey, DesigntimeLicenseContext context)
 {
   Contract.Requires(context != null);
 }