public void Can_only_get_license_per_allocated_licenses()
        {
            string fileName = WriteFloatingLicenseFile();

            GenerateLicenseFileInLicensesDirectory();

            LicensingService.SoftwarePublicKey       = public_only;
            LicensingService.LicenseServerPrivateKey = floating_private;

            var    host    = new ServiceHost(typeof(LicensingService));
            string address = "http://localhost:19292/" + Guid.NewGuid();

            host.AddServiceEndpoint(typeof(ILicensingService), new BasicHttpBinding(), address);

            host.Open();

            try
            {
                var validator = new LicenseValidator(public_only, fileName, address, Guid.NewGuid());
                validator.AssertValidLicense();

                var validator2 = new LicenseValidator(public_only, fileName, address, Guid.NewGuid());
                Assert.Throws <FloatingLicenseNotAvailableException>(() => validator2.AssertValidLicense());
            }
            finally
            {
                host.Close();
            }
        }
        public void Can_only_get_license_per_allocated_licenses()
        {
            string fileName = WriteFloatingLicenseFile();

            GenerateLicenseFileInLicensesDirectory();

            LicensingService.SoftwarePublicKey       = public_only;
            LicensingService.LicenseServerPrivateKey = floating_private;

            var host    = new ServiceHost(typeof(LicensingService));
            var address = "http://localhost:9292/license";

            host.AddServiceEndpoint(typeof(ILicensingService), new WSHttpBinding(), address);

            host.Open();

            var validator = new LicenseValidator(public_only, fileName, address, Guid.NewGuid());

            validator.AssertValidLicense();

            var validator2 = new LicenseValidator(public_only, fileName, address, Guid.NewGuid());

            Assert.Throws <LicenseNotFoundException>(validator2.AssertValidLicense);

            host.Abort();
        }
Beispiel #3
0
        private static void SelfVerification()
        {
            Thread.Sleep(TimeSpan.FromSeconds((double)new Random().Next(10, 25)));

            bool   result    = false;
            var    puk       = CommonHelper.MapPath("~/App_Data/publicKey.xml");
            string publicKey = "";

            if (File.Exists(puk))
            {
                publicKey = File.ReadAllText(puk);

                var licenseValidator = new LicenseValidator(publicKey, CommonHelper.MapPath("~/App_Data/license.lic"));
                try {
                    licenseValidator.AssertValidLicense();

                    //MessageBox.Show( $"License is valid to {licenseValidator.Name}, date: {licenseValidator.ExpirationDate}" );

                    result = true;
                }
                catch (Exception ex) {
                    Log.Error("sn:" + ex);
                    throw ex;
                }
            }

            if (!result)
            {
                Log.Error("sn");
                throw new InvalidOleVariantTypeException("sn");
            }
        }
        public void Can_validate_floating_license()
        {
            string fileName = WriteFloatingLicenseFile();

            GenerateLicenseFileInLicensesDirectory();

            LicensingService.SoftwarePublicKey = public_only;
            LicensingService.LicenseServerPrivateKey = floating_private;

            var host = new ServiceHost(typeof(LicensingService));
            const string address = "http://localhost:19292/license";
            host.AddServiceEndpoint(typeof(ILicensingService), new WSHttpBinding(), address);

            host.Open();
            try
            {

                var validator = new LicenseValidator(public_only, fileName, address, Guid.NewGuid());
                validator.AssertValidLicense();
            }
            finally
            {
                host.Abort();
            }
        }
Beispiel #5
0
        private void ValidateLicense()
        {
            var privateKeyPath = GetWorkDirFile("privateKey.xml");
            var publicKeyPath  = GetWorkDirFile("publicKey.xml");

            if (!File.Exists(publicKeyPath))
            {
                MessageBox.Show("Please create a license key first");
                return;
            }

            var publicKey = File.ReadAllText(publicKeyPath);

            var validator = new LicenseValidator(publicKey, @"license.lic");

            try
            {
                validator.AssertValidLicense();

                var dict = validator.LicenseAttributes;
                MessageBox.Show($"License to {dict["name"]}, key is {dict["key"]}");

                if (dict["key"] != txtComputerKey.Text)
                {
                    MessageBox.Show("invalid!");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        public void Gen_and_validate_with_attributes()
        {
            var guid       = Guid.NewGuid();
            var generator  = new LicenseGenerator(public_and_private);
            var expiration = DateTime.Now.AddDays(30);
            var key        = generator.Generate("Oren Eini", guid, expiration,
                                                new Dictionary <string, string>
            {
                { "prof", "llb" },
                { "reporting", "on" }
            }, LicenseType.Trial);

            var path = Path.GetTempFileName();

            File.WriteAllText(path, key);

            var validator = new LicenseValidator(public_only, path);

            validator.AssertValidLicense();

            Assert.Equal("llb", validator.LicenseAttributes["prof"]);
            Assert.Equal("on", validator.LicenseAttributes["reporting"]);
            Assert.Equal(guid, validator.UserId);
            Assert.Equal(expiration, validator.ExpirationDate);
            Assert.Equal("Oren Eini", validator.Name);
            Assert.Equal(LicenseType.Trial, validator.LicenseType);
        }
        public void Can_only_get_license_per_allocated_licenses()
        {
            string fileName = WriteFloatingLicenseFile();

            GenerateLicenseFileInLicensesDirectory();

            LicensingService.SoftwarePublicKey = public_only;
            LicensingService.LicenseServerPrivateKey = floating_private;

            var host = new ServiceHost(typeof(LicensingService));
            var address = "http://localhost:29292/license";
            host.AddServiceEndpoint(typeof(ILicensingService), new WSHttpBinding(), address);

            host.Open();

            try
            {
                var validator = new LicenseValidator(public_only, fileName, address, Guid.NewGuid());
                validator.AssertValidLicense();

                var validator2 = new LicenseValidator(public_only, fileName, address, Guid.NewGuid());
                Assert.Throws<FloatingLicenseNotAvialableException>(() => validator2.AssertValidLicense());
            }
            finally
            {
                host.Abort();
            }
        }
        public void Can_validate_floating_license()
        {
            string fileName = WriteFloatingLicenseFile();

            GenerateLicenseFileInLicensesDirectory();

            LicensingService.SoftwarePublicKey       = public_only;
            LicensingService.LicenseServerPrivateKey = floating_private;

            var          host    = new ServiceHost(typeof(LicensingService));
            const string address = "http://localhost:19292/license";

            host.AddServiceEndpoint(typeof(ILicensingService), new WSHttpBinding(), address);

            host.Open();
            try
            {
                var validator = new LicenseValidator(public_only, fileName, address, Guid.NewGuid());
                validator.AssertValidLicense();
            }
            finally
            {
                host.Abort();
            }
        }
Beispiel #9
0
        //private static CountManager countManager = new CountManager();

        //private void CountManager_ExceedLimitation(string obj)
        //{
        //    if (Validation() == false)
        //    {
        //        MessageBox.Show("No license provided");
        //    }
        //}

        private bool Validation()
        {
            var    keyFile   = "publicKey.xml";
            string publicKey = "";

            if (File.Exists(keyFile))
            {
                publicKey = File.ReadAllText(keyFile);
            }

            var licenseValidator = new LicenseValidator(publicKey, "license.lic");

            try
            {
                licenseValidator.AssertValidLicense();

                var log = $"{licenseValidator.Name} authorized License to {licenseValidator.LicenseAttributes["name"]}\n";
                this.Text = "SIAPM Attend Form authorized";
                LogHelper.Info(log);
                ResultText.AppendText(log);
                return(true);
            }
            catch (Exception ex)
            {
                LogHelper.Error("Validation", ex);
                ResultText.AppendText("No license provided or validation is failed.\n");
            }

            return(false);
        }
Beispiel #10
0
        private bool Validation()
        {
            var    keyFile   = "publicKey.xml";
            string publicKey = "";

            if (File.Exists(keyFile))
            {
                publicKey = File.ReadAllText(keyFile);
            }

            var licenseValidator = new LicenseValidator(publicKey, "license.lic");

            try
            {
                licenseValidator.AssertValidLicense();

                MessageBox.Show($"License is valid to {licenseValidator.Name}, date: {licenseValidator.ExpirationDate}");

                return(true);
            }
            catch (Exception ex)
            {
            }

            return(false);
        }
Beispiel #11
0
        public void Will_detect_duplicate_license()
        {
            var guid       = Guid.NewGuid();
            var generator  = new LicenseGenerator(public_and_private);
            var expiration = DateTime.Now.AddDays(30);
            var key        = generator.Generate("Oren Eini", guid, expiration, LicenseType.Trial);

            var path = Path.GetTempFileName();

            File.WriteAllText(path, key);

            var wait = new ManualResetEvent(false);

            var validator = new LicenseValidator(public_only, path)
            {
                LeaseTimeout = TimeSpan.FromSeconds(1)
            };
            InvalidationType?invalidation = null;

            validator.LicenseInvalidated             += type => invalidation = type;
            validator.MultipleLicensesWereDiscovered += (sender, args) => wait.Set();
            validator.AssertValidLicense();

            var validator2 = new LicenseValidator(public_only, path);

            validator2.AssertValidLicense();

            //todo: marked this out  for now
            //	Assert.True(wait.WaitOne(TimeSpan.FromSeconds(100)));
            //Assert.Equal(invalidation.Value, InvalidationType.TimeExpired);
        }
        public void Cannot_validate_hacked_license()
        {
            const string hackedLicense =
                @"<?xml version=""1.0"" encoding=""utf-16""?>
<license id=""2bc65446-0c78-453f-9da3-badb9f191163"" expiration=""2009-04-04T12:16:45.4328736"" type=""Trial"">
  <name>Oren Eini</name>
  <Signature xmlns=""http://www.w3.org/2000/09/xmldsig#"">
    <SignedInfo>
      <CanonicalizationMethod Algorithm=""http://www.w3.org/TR/2001/REC-xml-c14n-20010315"" />
      <SignatureMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#rsa-sha1"" />
      <Reference URI="""">
        <Transforms>
          <Transform Algorithm=""http://www.w3.org/2000/09/xmldsig#enveloped-signature"" />
        </Transforms>
        <DigestMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#sha1"" />
        <DigestValue>KxG48zaXJ0gEOpuCc4NPYTh7U7c=</DigestValue>
      </Reference>
    </SignedInfo>
    <SignatureValue>KfNKJRDwPeJ2Olw+sbe1RLLrzQzMAf/Kwcs34LkRMR/bRYTvm+RX1KMr0/+bNxtg0NCqMjMgPqrZfx3V416GMhlwMIFzFSRzF8Z/khKHXM2Hbur3ibeyMoj5GGTx5sUKJy0v5eVaLvE9pDc5pafVaUynk/5NDgCQR6wBbKtzLJamaX+zigS8uXGvDxcMAGSeY97wtATdXBawrWbfQgeJ72h0FHshaepqS5roNXgr/5oV4ma/KWTrwTZVBo76ThkgB4HzsZGqjAo9vZa5eUHQwrJfNEEwoHnu4Ld8PfKErwTbr6Q8GK8CSxldP5HJ0BALuj1bETlDum6/vcZZXGEtsQ==</SignatureValue>
  </Signature>
</license>";

            var path = Path.GetTempFileName();

            File.WriteAllText(path, hackedLicense);

            var validator = new LicenseValidator(public_only, path);

            Assert.Throws <LicenseNotFoundException>(() => validator.AssertValidLicense());
        }
        public void Gen_and_validate_with_attributes()
        {
            var guid = Guid.NewGuid();
            var generator = new LicenseGenerator(public_and_private);
            var expiration = DateTime.Now.AddDays(30);
            var key = generator.Generate("Oren Eini", guid, expiration,
                                         new Dictionary<string, string>
                                         {
                                            {"prof", "llb"},
                                            {"reporting", "on"}
                                         }, LicenseType.Trial);

            var path = Path.GetTempFileName();
            File.WriteAllText(path, key);

            var validator = new LicenseValidator(public_only, path);
            validator.AssertValidLicense();

            Assert.Equal("llb", validator.LicenseAttributes["prof"]);
            Assert.Equal("on", validator.LicenseAttributes["reporting"]);
            Assert.Equal(guid, validator.UserId);
            Assert.Equal(expiration, validator.ExpirationDate);
            Assert.Equal("Oren Eini", validator.Name);
            Assert.Equal(LicenseType.Trial, validator.LicenseType);
        }
		public void Will_detect_duplicate_license()
		{
			var guid = Guid.NewGuid();
			var generator = new LicenseGenerator(public_and_private);
			var expiration = DateTime.Now.AddDays(30);
			var key = generator.Generate("Oren Eini", guid, expiration, LicenseType.Trial);

			var path = Path.GetTempFileName();
			File.WriteAllText(path, key);

			var wait = new ManualResetEvent(false);

			var validator = new LicenseValidator(public_only, path)
			{
				LeaseTimeout = TimeSpan.FromSeconds(1)
			};
			InvalidationType? invalidation = null;
			validator.LicenseInvalidated += type => invalidation = type;
			validator.MultipleLicensesWereDiscovered += (sender, args) => wait.Set();
			validator.AssertValidLicense();

			var validator2 = new LicenseValidator(public_only, path);
			validator2.AssertValidLicense();

      //todo: marked this out  for now
		  //	Assert.True(wait.WaitOne(TimeSpan.FromSeconds(100)));
			//Assert.Equal(invalidation.Value, InvalidationType.TimeExpired);
		}
Beispiel #15
0
        public static ChocolateyLicense validate()
        {
            var chocolateyLicense = new ChocolateyLicense
            {
                LicenseType = ChocolateyLicenseType.Unknown
            };

            string licenseFile = ApplicationParameters.LicenseFileLocation;

            //no file system at this point
            if (File.Exists(licenseFile))
            {
                var license = new LicenseValidator(PUBLIC_KEY, licenseFile);

                try
                {
                    license.AssertValidLicense();
                    chocolateyLicense.IsValid = true;
                }
                catch (Exception e)
                {
                    //license may be invalid
                    chocolateyLicense.IsValid       = false;
                    chocolateyLicense.InvalidReason = e.Message;
                    "chocolatey".Log().Error("A license was found for a licensed version of Chocolatey, but is invalid:{0} {1}".format_with(Environment.NewLine, e.Message));
                }

                switch (license.LicenseType)
                {
                case LicenseType.Professional:
                    chocolateyLicense.LicenseType = ChocolateyLicenseType.Professional;
                    break;

                case LicenseType.Business:
                    chocolateyLicense.LicenseType = ChocolateyLicenseType.Business;
                    break;

                case LicenseType.Enterprise:
                    chocolateyLicense.LicenseType = ChocolateyLicenseType.Enterprise;
                    break;
                }

                chocolateyLicense.ExpirationDate = license.ExpirationDate;
                chocolateyLicense.Name           = license.Name;
                chocolateyLicense.Id             = license.UserId.to_string();

                //todo: if it is expired, provide a warning.
                // one month after it should stop working
            }
            else
            {
                //free version
                chocolateyLicense.LicenseType = ChocolateyLicenseType.Foss;
            }

            return(chocolateyLicense);
        }
Beispiel #16
0
        public void Execute(DocumentDatabase database)
        {
            string publicKey;

            using (var stream = typeof(ValidateLicense).Assembly.GetManifestResourceStream("Raven.Database.Commercial.RavenDB.public"))
            {
                if (stream == null)
                {
                    throw new InvalidOperationException("Could not find public key for the license");
                }
                publicKey = new StreamReader(stream).ReadToEnd();
            }
            var fullPath = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "license.xml"));

            licenseValidator = new LicenseValidator(publicKey, fullPath)
            {
                DisableFloatingLicenses = true,
            };
            licenseValidator.LicenseInvalidated             += LicenseValidatorOnLicenseInvalidated;
            licenseValidator.MultipleLicensesWereDiscovered += LicenseValidatorOnMultipleLicensesWereDiscovered;

            if (File.Exists(fullPath) == false)
            {
                CurrentLicense = new LicensingStatus
                {
                    Status  = "AGPL - Open Source",
                    Error   = false,
                    Message = "No license file was found at " + fullPath +
                              "\r\nThe AGPL license restrictions apply, only Open Source / Development work is permitted."
                };
                return;
            }

            try
            {
                licenseValidator.AssertValidLicense();

                CurrentLicense = new LicensingStatus
                {
                    Status  = "Commercial - " + licenseValidator.LicenseType,
                    Error   = false,
                    Message = "Valid license " + fullPath
                };
            }
            catch (Exception e)
            {
                logger.ErrorException("Could not validate license at " + fullPath, e);

                CurrentLicense = new LicensingStatus
                {
                    Status  = "AGPL - Open Source",
                    Error   = true,
                    Message = "Could not validate license file at " + fullPath + Environment.NewLine + e
                };
            }
        }
        public void Gen_and_validate()
        {
            var guid = Guid.NewGuid();
            var generator = new LicenseGenerator(public_and_private);
            var expiration = DateTime.Now.AddDays(30);
            var key = generator.Generate("Oren Eini", guid, expiration, LicenseType.Trial);

            var path = Path.GetTempFileName();
            File.WriteAllText(path, key);

            var validator = new LicenseValidator(public_only, path);
            validator.AssertValidLicense();

            Assert.Equal(guid, validator.UserId);
            Assert.Equal(expiration, validator.ExpirationDate);
            Assert.Equal("Oren Eini", validator.Name);
            Assert.Equal(LicenseType.Trial, validator.LicenseType);
        }
Beispiel #18
0
        public void Bug_for_year_over_8000_was_marked_as_expired()
        {
            var guid = Guid.NewGuid();
            var generator = new LicenseGenerator(public_and_private);
            var expiration = new DateTime(9999, 10, 10, 10, 10, 10);
            var key = generator.Generate("User name", guid, expiration, LicenseType.Standard);

            var path = Path.GetTempFileName();
            File.WriteAllText(path, key);

            var validator = new LicenseValidator(public_only, path);
            validator.AssertValidLicense();

            Assert.Equal(guid, validator.UserId);
            Assert.Equal(expiration, validator.ExpirationDate);
            Assert.Equal("User name", validator.Name);
            Assert.Equal(LicenseType.Standard, validator.LicenseType);
        }
        public void Throws_date_exception_when_license_is_expired()
        {
            var guid = Guid.NewGuid();
            var generator = new LicenseGenerator(public_and_private);
            var expiration = DateTime.Now.AddDays(-1);
            var key = generator.Generate("Oren Eini", guid, expiration,
                                         new Dictionary<string, string>
                                         {
                                            {"prof", "llb"},
                                            {"reporting", "on"}
                                         }, LicenseType.Trial);

            var path = Path.GetTempFileName();
            File.WriteAllText(path, key);

            var validator = new LicenseValidator(public_only, path);
            Assert.Throws<LicenseExpiredException>(() => validator.AssertValidLicense());
        }
Beispiel #20
0
        public void Bug_for_year_over_8000_was_marked_as_expired()
        {
            var guid       = Guid.NewGuid();
            var generator  = new LicenseGenerator(public_and_private);
            var expiration = new DateTime(9999, 10, 10, 10, 10, 10);
            var key        = generator.Generate("User name", guid, expiration, LicenseType.Standard);

            var path = Path.GetTempFileName();

            File.WriteAllText(path, key);

            var validator = new LicenseValidator(public_only, path);

            validator.AssertValidLicense();

            Assert.Equal(guid, validator.UserId);
            Assert.Equal(expiration, validator.ExpirationDate);
            Assert.Equal("User name", validator.Name);
            Assert.Equal(LicenseType.Standard, validator.LicenseType);
        }
        public void Gen_and_validate()
        {
            var guid       = Guid.NewGuid();
            var generator  = new LicenseGenerator(public_and_private);
            var expiration = DateTime.Now.AddDays(30);
            var key        = generator.Generate("Oren Eini", guid, expiration, LicenseType.Trial);

            var path = Path.GetTempFileName();

            File.WriteAllText(path, key);

            var validator = new LicenseValidator(public_only, path);

            validator.AssertValidLicense();

            Assert.Equal(guid, validator.UserId);
            Assert.Equal(expiration, validator.ExpirationDate);
            Assert.Equal("Oren Eini", validator.Name);
            Assert.Equal(LicenseType.Trial, validator.LicenseType);
        }
        public void Throws_date_exception_when_license_is_expired()
        {
            var guid       = Guid.NewGuid();
            var generator  = new LicenseGenerator(public_and_private);
            var expiration = DateTime.Now.AddDays(-1);
            var key        = generator.Generate("Oren Eini", guid, expiration,
                                                new Dictionary <string, string>
            {
                { "prof", "llb" },
                { "reporting", "on" }
            }, LicenseType.Trial);

            var path = Path.GetTempFileName();

            File.WriteAllText(path, key);

            var validator = new LicenseValidator(public_only, path);

            Assert.Throws <LicenseExpiredException>(() => validator.AssertValidLicense());
        }
Beispiel #23
0
        private static void ValidateLicense()
        {
            if (!File.Exists("publicKey.xml"))
            {
                MessageBox.Show("Please create a license key first");
                return;
            }

            var publicKey = File.ReadAllText(@"publicKey.xml");

            var validator = new LicenseValidator(publicKey, @"license.lic");

            try
            {
                validator.AssertValidLicense();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Beispiel #24
0
        /// <summary>
        /// 验证并且返回验证信息
        /// </summary>
        /// <returns>不成功返回空</returns>
        internal static LicenseValidator ValidationGetInfo()
        {
            if (!File.Exists(_path_license) || !File.Exists(_path_pub))
            {
                return(null); // 如果文件不全,则不验证
            }

            string publicKey = File.ReadAllText(_path_pub);

            try
            {
                var licenseValidator = new LicenseValidator(publicKey, _path_license);
                licenseValidator.AssertValidLicense();

                return(licenseValidator);
            }
            catch
            {
            }

            return(null);
        }
Beispiel #25
0
        public static bool IsValid(out DateTime expiration, string licFile, string publicKey)
        {
            expiration = DateTime.MinValue;

            var licVal = new LicenseValidator(publicKey, licFile);

            try
            {
                licVal.AssertValidLicense();
            }
            catch (Exception)
            {
                return(false);
            }

            expiration = licVal.ExpirationDate;

            var cpuInfo = string.Empty;
            var mc      = new ManagementClass("win32_processor");
            var moc     = mc.GetInstances();

            foreach (ManagementObject mo in moc)
            {
                cpuInfo = mo.Properties["processorID"].Value.ToString();
                break;
            }
            if (licVal.ExpirationDate <= DateTime.Now)
            {
                return(false);
            }

            if (licVal.Name != cpuInfo)
            {
                return(false);
            }


            return(true);
        }
        public void Cannot_validate_hacked_license()
        {
            const string hackedLicense =
                @"<?xml version=""1.0"" encoding=""utf-16""?>
<license id=""2bc65446-0c78-453f-9da3-badb9f191163"" expiration=""2009-04-04T12:16:45.4328736"" type=""Trial"">
  <name>Oren Eini</name>
  <Signature xmlns=""http://www.w3.org/2000/09/xmldsig#"">
    <SignedInfo>
      <CanonicalizationMethod Algorithm=""http://www.w3.org/TR/2001/REC-xml-c14n-20010315"" />
      <SignatureMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#rsa-sha1"" />
      <Reference URI="""">
        <Transforms>
          <Transform Algorithm=""http://www.w3.org/2000/09/xmldsig#enveloped-signature"" />
        </Transforms>
        <DigestMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#sha1"" />
        <DigestValue>KxG48zaXJ0gEOpuCc4NPYTh7U7c=</DigestValue>
      </Reference>
    </SignedInfo>
    <SignatureValue>KfNKJRDwPeJ2Olw+sbe1RLLrzQzMAf/Kwcs34LkRMR/bRYTvm+RX1KMr0/+bNxtg0NCqMjMgPqrZfx3V416GMhlwMIFzFSRzF8Z/khKHXM2Hbur3ibeyMoj5GGTx5sUKJy0v5eVaLvE9pDc5pafVaUynk/5NDgCQR6wBbKtzLJamaX+zigS8uXGvDxcMAGSeY97wtATdXBawrWbfQgeJ72h0FHshaepqS5roNXgr/5oV4ma/KWTrwTZVBo76ThkgB4HzsZGqjAo9vZa5eUHQwrJfNEEwoHnu4Ld8PfKErwTbr6Q8GK8CSxldP5HJ0BALuj1bETlDum6/vcZZXGEtsQ==</SignatureValue>
  </Signature>
</license>";

            var path = Path.GetTempFileName();
            File.WriteAllText(path, hackedLicense);

            var validator = new LicenseValidator(public_only, path);
            Assert.Throws<LicenseNotFoundException>(() => validator.AssertValidLicense());
        }
 public void Will_tell_that_we_are_in_invalid_state()
 {
     var validator = new LicenseValidator(public_only, Path.GetTempFileName());
     Assert.Throws<LicenseNotFoundException>(() => validator.AssertValidLicense());
 }
Beispiel #28
0
        public static ChocolateyLicense validate()
        {
            var chocolateyLicense = new ChocolateyLicense
            {
                LicenseType = ChocolateyLicenseType.Unknown
            };

            string licenseFile     = ApplicationParameters.LicenseFileLocation;
            var    userLicenseFile = ApplicationParameters.UserLicenseFileLocation;

            if (File.Exists(userLicenseFile))
            {
                licenseFile = userLicenseFile;
            }

            //no IFileSystem at this point
            if (File.Exists(licenseFile))
            {
                "chocolatey".Log().Debug("Evaluating license file found at '{0}'".format_with(licenseFile));
                var license = new LicenseValidator(PUBLIC_KEY, licenseFile);

                try
                {
                    license.AssertValidLicense();

                    // There is a lease expiration timer within Rhino.Licensing, which by
                    // default re-asserts the license every 5 minutes.  Since we assert a
                    // valid license on each attempt to execute an action with Chocolatey,
                    // re-checking of the license for the current session is not required.
                    license.DisableFutureChecks();

                    chocolateyLicense.IsValid = true;
                }
                catch (LicenseFileNotFoundException e)
                {
                    chocolateyLicense.IsValid       = false;
                    chocolateyLicense.InvalidReason = e.Message;
                    "chocolatey".Log().Error("A license was not found for a licensed version of Chocolatey:{0} {1}{0} {2}".format_with(Environment.NewLine, e.Message,
                                                                                                                                       "A license was also not found in the user profile: '{0}'.".format_with(ApplicationParameters.UserLicenseFileLocation)));
                }
                catch (Exception e)
                {
                    //license may be invalid
                    chocolateyLicense.IsValid       = false;
                    chocolateyLicense.InvalidReason = e.Message;
                    "chocolatey".Log().Error("A license was found for a licensed version of Chocolatey, but is invalid:{0} {1}".format_with(Environment.NewLine, e.Message));
                }

                var chocolateyLicenseType = ChocolateyLicenseType.Unknown;
                try
                {
                    Enum.TryParse(license.LicenseType.to_string(), true, out chocolateyLicenseType);
                }
                catch (Exception)
                {
                    chocolateyLicenseType = ChocolateyLicenseType.Unknown;
                }

                if (license.LicenseType == LicenseType.Trial)
                {
                    chocolateyLicenseType = ChocolateyLicenseType.BusinessTrial;
                }
                else if (license.LicenseType == LicenseType.Education)
                {
                    chocolateyLicenseType = ChocolateyLicenseType.Educational;
                }

                chocolateyLicense.LicenseType    = chocolateyLicenseType;
                chocolateyLicense.ExpirationDate = license.ExpirationDate;
                chocolateyLicense.Name           = license.Name;
                chocolateyLicense.Id             = license.UserId.to_string();

                //todo: if it is expired, provide a warning.
                // one month after it should stop working
            }
            else
            {
                //free version
                chocolateyLicense.LicenseType = ChocolateyLicenseType.Foss;
            }

            return(chocolateyLicense);
        }
        static void Main(string[] args)
        {
            //Dossier Application data
            var dossierName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                                           Application.ProductName);

            if (!Directory.Exists(dossierName))
            {
                Directory.CreateDirectory(dossierName);
            }

            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("fr-FR");
            // Add the event handler for handling UI thread exceptions to the event.
            Application.ThreadException += ThreadException;
            // Set the unhandled exception mode to force all Windows Forms errors to go through our handler.
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            // Add the event handler for handling non-UI thread exceptions to the event.
            AppDomain.CurrentDomain.UnhandledException += UnhandledException;

            BonusSkins.Register();
            SkinManager.EnableFormSkins();
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            string path = args.Length != 0 ? args[0] : string.Empty;


//#if DEBUG
//            IsMultiSociete = true;
//#else
            // determinition code hardware du pc actuel
            var codePc = GeneratorCode.Value();

            // verification de la license
            try
            {
                var publicKey = File.ReadAllText("publicKey.xml");
                var validator = new LicenseValidator(publicKey, "lic.tvs", false);
                validator.AssertValidLicense();
                if (validator.Name != codePc)
                {
                    throw new ApplicationException("Licence invalide!");
                }
                var attribute = validator.LicenseAttributes;
                IsMultiSociete = attribute["MultiSocite"] == "0";
                IsCnss         = attribute["Cnss"] == "0";
                IsDecBc        = attribute["BcSuspension"] == "0";
                IsDecFc        = attribute["FcSuspension"] == "0";
                IsEmp          = attribute["Employeur"] == "0";
                IsVirement     = attribute["Virement"] == "0";
                Societe        = attribute["Societe"];
                DateExpiration = validator.ExpirationDate;
                IsLiasse       = attribute["Liasse"] == "0";
                // IsCovis = attribute["Covis"] == "0";
            }
            catch (LicenseFileNotFoundException e)
            {
                XtraMessageBox.Show("Fichier de licence introuvable");
                new FrmLicenceInvalide().ShowDialog();
                return;
            }
            catch (LicenseExpiredException e)
            {
                XtraMessageBox.Show("Licence expirée");
                new FrmLicenceInvalide().ShowDialog();
                return;
            }
            catch (Exception e)
            {
                XtraMessageBox.Show(e.Message);
                new FrmLicenceInvalide().ShowDialog();
                return;
            }
            //#endif


            // init Ninject dependencies resolver
            Kernel = new StandardKernel();
            Kernel.Bind <IUserControlFactory>().ToFactory().InSingletonScope();
            Kernel.Bind <IFormFactory>().ToFactory().InSingletonScope();

            Kernel.Bind <AppConfiguration>()
            .ToSelf()
            .InSingletonScope();


            Kernel.Bind <IConfigurationRepository <GroupConfiguration> >()
            .To <GroupConfigurationRepository>()
            .InSingletonScope();

            // check configs (connection ...)
            // get configs / connection to `Groupe`
            // should return a valid connection
            var appConfig = Kernel.Get <AppConfiguration>();
            GroupConfiguration groupeConfig = appConfig.Load(path);

            if (!string.IsNullOrEmpty(path))
            {
                try
                {
                    appConfig.Load(path);
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }

            if (groupeConfig == null)
            {
                XtraMessageBox.Show("Configuration invalide!");
                // demarrer la fenetre principale
                //var frm = new FrmNouveauFichier(appConfig);
                //frm.ShowDialog();
                return;
            }
            // RebindGroupConnection(groupeConfig);


            Application.SetCompatibleTextRenderingDefault(false);
            var main                = Kernel.Get <FrmMain>();
            var service             = GetService();
            var frmAuthentification = new FrmOuverture(service);

            if (frmAuthentification.ShowDialog() != DialogResult.Yes)
            {
                return;
            }
            Context = new CommandContext
            {
                MainForm           = main,
                Container          = InitializeContainer(),
                Exercice           = service.Exercice,
                Societe            = service.Societe,
                User               = service.User,
                ConnectionProvider = Kernel.Get <IConnectionProvider>()
            };

            // demarrer la fenetre principale
            Application.Run(Context.MainForm);
            //   Application.Run(new XtraForm1());
        }
Beispiel #30
0
        public static ChocolateyLicense validate()
        {
            var chocolateyLicense = new ChocolateyLicense
            {
                LicenseType = ChocolateyLicenseType.Unknown
            };

            string licenseFile     = ApplicationParameters.LicenseFileLocation;
            var    userLicenseFile = ApplicationParameters.UserLicenseFileLocation;

            if (File.Exists(userLicenseFile))
            {
                licenseFile = userLicenseFile;
            }

            //no IFileSystem at this point
            if (File.Exists(licenseFile))
            {
                var license = new LicenseValidator(PUBLIC_KEY, licenseFile);

                try
                {
                    license.AssertValidLicense();
                    chocolateyLicense.IsValid = true;
                }
                catch (LicenseFileNotFoundException e)
                {
                    chocolateyLicense.IsValid       = false;
                    chocolateyLicense.InvalidReason = e.Message;
                    "chocolatey".Log().Error("A license was not found for a licensed version of Chocolatey:{0} {1}{0} {2}".format_with(Environment.NewLine, e.Message,
                                                                                                                                       "A license was also not found in the user profile: '{0}'.".format_with(ApplicationParameters.UserLicenseFileLocation)));
                }
                catch (Exception e)
                {
                    //license may be invalid
                    chocolateyLicense.IsValid       = false;
                    chocolateyLicense.InvalidReason = e.Message;
                    "chocolatey".Log().Error("A license was found for a licensed version of Chocolatey, but is invalid:{0} {1}".format_with(Environment.NewLine, e.Message));
                }

                var chocolateyLicenseType = ChocolateyLicenseType.Unknown;
                try
                {
                    Enum.TryParse(license.LicenseType.to_string(), true, out chocolateyLicenseType);
                }
                catch (Exception)
                {
                    chocolateyLicenseType = ChocolateyLicenseType.Unknown;
                }

                if (license.LicenseType == LicenseType.Trial)
                {
                    chocolateyLicenseType = ChocolateyLicenseType.BusinessTrial;
                }
                else if (license.LicenseType == LicenseType.Education)
                {
                    chocolateyLicenseType = ChocolateyLicenseType.Educational;
                }

                chocolateyLicense.LicenseType    = chocolateyLicenseType;
                chocolateyLicense.ExpirationDate = license.ExpirationDate;
                chocolateyLicense.Name           = license.Name;
                chocolateyLicense.Id             = license.UserId.to_string();

                //todo: if it is expired, provide a warning.
                // one month after it should stop working
            }
            else
            {
                //free version
                chocolateyLicense.LicenseType = ChocolateyLicenseType.Foss;
            }

            return(chocolateyLicense);
        }
 public void Will_fail_if_file_is_not_there()
 {
     var validator = new LicenseValidator(public_only, "not_there");
     Assert.Throws<LicenseFileNotFoundException>(() => validator.AssertValidLicense());
 }
        public void Will_fail_if_file_is_not_there()
        {
            var validator = new LicenseValidator(new DebugLogService(), public_only, "not_there");

            Assert.Throws <LicenseFileNotFoundException>(() => validator.AssertValidLicense());
        }
        public static ChocolateyLicense validate()
        {
            var chocolateyLicense = new ChocolateyLicense
            {
                LicenseType  = ChocolateyLicenseType.Unknown,
                IsCompatible = true
            };

            var regularLogOutput = determine_if_regular_output_for_logging();

            string licenseFile     = ApplicationParameters.LicenseFileLocation;
            var    userLicenseFile = ApplicationParameters.UserLicenseFileLocation;

            if (File.Exists(userLicenseFile))
            {
                licenseFile = userLicenseFile;
            }

            // no IFileSystem at this point
            if (!File.Exists(licenseFile))
            {
                var licenseFileName  = Path.GetFileName(ApplicationParameters.LicenseFileLocation);
                var licenseDirectory = Path.GetDirectoryName(ApplicationParameters.LicenseFileLocation);

                // look for misnamed files and locations
                // - look in the license directory for misnamed files
                if (Directory.Exists(licenseDirectory))
                {
                    if (Directory.GetFiles(licenseDirectory).Length != 0)
                    {
                        "chocolatey".Log().Error(regularLogOutput ? ChocolateyLoggers.Normal : ChocolateyLoggers.LogFileOnly, @"Files found in directory '{0}' but not a
 valid license file. License should be named '{1}'.".format_with(licenseDirectory, licenseFileName));
                        "chocolatey".Log().Warn(ChocolateyLoggers.Important, @" Rename license file to '{0}' to allow commercial features.".format_with(licenseFileName));
                    }
                }


                // - user put the license file in the top level location and/or forgot to rename it
                if (File.Exists(Path.Combine(ApplicationParameters.InstallLocation, licenseFileName)) || File.Exists(Path.Combine(ApplicationParameters.InstallLocation, licenseFileName + ".txt")))
                {
                    "chocolatey".Log().Error(regularLogOutput ? ChocolateyLoggers.Normal : ChocolateyLoggers.LogFileOnly, @"Chocolatey license found in the wrong location. File must be located at
 '{0}'.".format_with(ApplicationParameters.LicenseFileLocation));
                    "chocolatey".Log().Warn(regularLogOutput ? ChocolateyLoggers.Important : ChocolateyLoggers.LogFileOnly, @" Move license file to '{0}' to allow commercial features.".format_with(ApplicationParameters.LicenseFileLocation));
                }
            }

            // no IFileSystem at this point
            if (File.Exists(licenseFile))
            {
                "chocolatey".Log().Debug("Evaluating license file found at '{0}'".format_with(licenseFile));
                var license = new LicenseValidator(PUBLIC_KEY, licenseFile);

                try
                {
                    license.AssertValidLicense();

                    // There is a lease expiration timer within Rhino.Licensing, which by
                    // default re-asserts the license every 5 minutes.  Since we assert a
                    // valid license on each attempt to execute an action with Chocolatey,
                    // re-checking of the license for the current session is not required.
                    license.DisableFutureChecks();

                    chocolateyLicense.IsValid = true;
                }
                catch (LicenseFileNotFoundException e)
                {
                    chocolateyLicense.IsValid       = false;
                    chocolateyLicense.InvalidReason = e.Message;
                    "chocolatey".Log().Error(regularLogOutput ? ChocolateyLoggers.Normal : ChocolateyLoggers.LogFileOnly, "A license was not found for a licensed version of Chocolatey:{0} {1}{0} {2}".format_with(Environment.NewLine, e.Message,
                                                                                                                                                                                                                    "A license was also not found in the user profile: '{0}'.".format_with(ApplicationParameters.UserLicenseFileLocation)));
                }
                catch (Exception e)
                {
                    //license may be invalid
                    chocolateyLicense.IsValid       = false;
                    chocolateyLicense.InvalidReason = e.Message;
                    "chocolatey".Log().Error(regularLogOutput ? ChocolateyLoggers.Normal : ChocolateyLoggers.LogFileOnly, "A license was found for a licensed version of Chocolatey, but is invalid:{0} {1}".format_with(Environment.NewLine, e.Message));
                }

                var chocolateyLicenseType = ChocolateyLicenseType.Unknown;
                try
                {
                    Enum.TryParse(license.LicenseType.to_string(), true, out chocolateyLicenseType);
                }
                catch (Exception)
                {
                    chocolateyLicenseType = ChocolateyLicenseType.Unknown;
                }

                if (license.LicenseType == LicenseType.Trial)
                {
                    chocolateyLicenseType = ChocolateyLicenseType.BusinessTrial;
                }
                else if (license.LicenseType == LicenseType.Education)
                {
                    chocolateyLicenseType = ChocolateyLicenseType.Educational;
                }

                chocolateyLicense.LicenseType    = chocolateyLicenseType;
                chocolateyLicense.ExpirationDate = license.ExpirationDate;
                chocolateyLicense.Name           = license.Name;
                chocolateyLicense.Id             = license.UserId.to_string();

                //todo: #2584 if it is expired, provide a warning.
                // one month after it should stop working
            }
            else
            {
                //free version
                chocolateyLicense.LicenseType = ChocolateyLicenseType.Foss;
            }

            return(chocolateyLicense);
        }
        public void Will_tell_that_we_are_in_invalid_state()
        {
            var validator = new LicenseValidator(new DebugLogService(), public_only, Path.GetTempFileName());

            Assert.Throws <LicenseNotFoundException>(() => validator.AssertValidLicense());
        }