Example #1
0
 public bool Load(string file) 
 {
     try
     {
         m_keys.Clear();
         TextReader tr = new StreamReader(file);
         while (true) 
         {
             string line = tr.ReadLine();
             if (line != null)
             {
                 line = line.Trim();
                 if (line.Length > 0)
                 {
                     LicenseKey lk = new LicenseKey();
                     lk.Init(line);
                     m_keys.Add(lk);
                 }
             }
             else 
             {
                 break;
             }
         }
         tr.Close();
         tr = null;
     }
     catch (Exception ex)
     {
         DebugLogger.Instance().LogError(ex);
         return false;
     }
     return true;
 }
Example #2
0
        static void Main()
        {
            LicenseKey lkd = new LicenseKey();
            lkd.LicensedEdition = LicenseKey.Edition.Professional;
            lkd.LicensedMajorVersion = 8;
            lkd.LicensedMinorVersion = 2;
            lkd.LicensedUsers = 50;
            lkd.ExpiryDate = DateTime.Now.AddMonths(1);
            String buildkey = LicenseHandler.ToProductCode(lkd, CryptHelper.LocalMachineID);
            buildkey = CryptHelper.InsertDashes(buildkey);

            LicenseKeyData rebuild = LicenseHandler.FromProductCode<LicenseKey>(buildkey, CryptHelper.LocalMachineID);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new frmKeyGen());
        }
        private void InsertServiceLicenseKey(ServiceLicenseKey serviceLicenseKey)
        {
            using (ScutexServiceEntities db1 = new ScutexServiceEntities())
            {
                LicenseKey licKey = new LicenseKey();
                licKey.Key               = serviceLicenseKey.Key;
                licKey.ActivationCount   = serviceLicenseKey.ActivationCount;
                licKey.Deactivated       = serviceLicenseKey.Deactivated;
                licKey.DeactivatedOn     = serviceLicenseKey.DeactivatedOn;
                licKey.DeactivatedReason = serviceLicenseKey.DeactivatedReason;
                licKey.LicenseSetId      = serviceLicenseKey.LicenseSetId;
                licKey.CreatedOn         = serviceLicenseKey.CreatedOn;

                db1.AddToLicenseKeys(licKey);
                db1.SaveChanges();
            }
        }
Example #4
0
        /// <summary>
        /// The main method of this example.
        /// </summary>
        /// <param name="args">no arguments are needed to run this example.</param>
        public static void Main(String[] args)
        {
            LicenseKey.LoadLicenseFile(Environment.GetEnvironmentVariable("ITEXT7_LICENSEKEY") +
                                       "/itextkey-html2pdf_typography.xml");
            FileInfo file = new FileInfo(DEST);

            file.Directory.Create();

            C05E03_Invitations app = new C05E03_Invitations();

            String[] names   = { "Bruno Lowagie", "Ingeborg Willaert", "John Doe" };
            int      counter = 1;

            foreach (String name in names)
            {
                app.CreatePdf(name, SRC, String.Format(DEST, counter++));
            }
        }
        public StandardLicenseValidatorTests()
        {
            var licenseKey = new LicenseKey <SimpleTestLicense>
            {
                LicenseType    = Type,
                ExpirationDate = _expirationDate,
                ActivationDate = _activationDate,
                LicenseName    = LicenseName,
                KeyData        = new SimpleTestLicense
                {
                    ValidThrough = _validThrough,
                    IssuedTo     = IssuedTo,
                    MaxUsers     = MaxUsers
                }
            };

            _licenseValidator = new StandardLicenseValidator <SimpleTestLicense>(licenseKey);
        }
Example #6
0
        public void HasFeatureTest()
        {
            var ki = new LicenseKey()
            {
                Expires = DateTime.Today.AddDays(3),
                F1      = true,
                F2      = false,
                F5      = true
            };

            bool result = ki.HasFeature(1)
                          .HasNotFeature(2)
                          .HasFeature(5)
                          .HasNotExpired()
                          .IsValid();

            Assert.IsTrue(result);
        }
        public bool Validate()
        {
            try
            {
                var key = LicenseKey.Decrypt(Shared.ENCRYPTION_KEY);
                IssueDate       = ExtractDate(key, 0);
                ExpirationDate  = ExtractDate(key, 8);
                RegisteredEmail = key.Substring(16, key.Length - 16);
                IsTrial         = IsExpired(this);
                return(true);
            }
            catch
            {
                Rest();
            }

            return(false);
        }
Example #8
0
        public async Task <(bool success, string message)> ValidateKeyAsync(LicenseKey licenseKey)
        {
            var find = await FindKeyAsync(licenseKey);

            if (find.success)
            {
                bool success = find.data.Contains(new KeyInfo()
                {
                    Key = licenseKey.Key
                });
                string message = (success) ? "Key is valid" : "Key is not valid";
                return(success, message);
            }
            else
            {
                return(false, $"Key not found: {GetBlobName(licenseKey)}");
            }
        }
Example #9
0
        public void IsOnRightMachineTest()
        {
            var ki = new LicenseKey {
                ActivatedMachines = new List <ActivationData>()
                {
                    new ActivationData {
                        Mid = "test"
                    }
                }
            };

            var result = ki.IsOnRightMachine().IsValid();

            Assert.IsFalse(ki.IsOnRightMachine().IsValid());

            ki.ActivatedMachines[0].Mid = SKGL.SKM.getMachineCode(SKGL.SKM.getSHA1);

            Assert.IsTrue(ki.IsOnRightMachine().IsValid());
        }
Example #10
0
        public void InsertLicenseKey(Model.LicenseKey key)
        {
            long newId;

            //using (ScutexEntities db1 = new ScutexEntities())
            //{
            LicenseKey lk = new LicenseKey();

            Mapper.CreateMap <Model.LicenseKey, LicenseKey>();
            lk                  = Mapper.Map <Model.LicenseKey, LicenseKey>(key);
            lk.LicenseKey1      = key.Key;
            lk.HashedLicenseKey = key.HashedLicenseKey;

            db.AddToLicenseKeys(lk);
            db.SaveChanges();

            newId = lk.LicenseKeyId;
            //}
        }
Example #11
0
        private void FillLicenseGrid(int ID)
        {
            LicenseKey Licensekeyobject = new LicenseKey();
            LicenseKey ReturnObject     = new LicenseKey();

            Licensekeyobject.ID = ID;
            int id = Convert.ToInt32(Session["UserID"].ToString());

            ReturnObject             = BL.UsersBL.Ins.GetData(Licensekeyobject, id);
            CompanyNameComboBox.Text = ReturnObject.CompanyName;
            //InstallTypeList1.SelectedItem.Text = ReturnObject.InstallType;
            if (ReturnObject.InstallType == "HA")
            {
                InstallTypeList1.SelectedIndex = 0;
            }
            else
            {
                InstallTypeList1.SelectedIndex = 1;
            }

            if (ReturnObject.LicenseType == "Evaluation")
            {
                LicenseType.SelectedIndex = 0;
            }
            else if (ReturnObject.LicenseType == "Subscription")
            {
                LicenseType.SelectedIndex = 1;
            }

            else
            {
                LicenseType.SelectedIndex = 2;
            }



            //LicenseType.SelectedItem.Text = ReturnObject.LicenseType;
            //string abc = (ReturnObject.ExpirationDate)

            ExpirationDate.Date = Convert.ToDateTime(ReturnObject.ExpirationDate);

            UnitsTextBox.Text = ReturnObject.Units.ToString();
        }
Example #12
0
        private bool SetProductLicense(LicenseKey licenseKey, string userName, string company, string email, string designTimeLicenseCategory, string runtimeLicenseCategory)
        {
            Debug.Assert(!string.IsNullOrEmpty(runtimeLicenseCategory));

            License designTimeLicense = null;
            License runtimeLicense;

            LicenseClient client = new LicenseClient(_publicKeyXml);

            try
            {
                LicensePublisherResponse response;
                if (!string.IsNullOrEmpty(designTimeLicenseCategory))
                {
                    response = client.GetLicense(CultureInfo.CurrentCulture, Product, Version, licenseKey, designTimeLicenseCategory, userName, company, email, MachineLicense.LocalMachineData);
                    if (!CheckLicense(response))
                    {
                        client.Close();
                        return(false);
                    }
                    designTimeLicense = response.License;
                }
                response = client.GetLicense(CultureInfo.CurrentCulture, Product, Version, licenseKey, runtimeLicenseCategory, userName, company, email, MachineLicense.LocalMachineData);
                client.Close();
                if (!CheckLicense(response))
                {
                    return(false);
                }
                runtimeLicense = response.License;
            }
            catch (CommunicationException exception)
            {
                LastErrorMessage = exception.Message;
                client.Abort();
                return(false);
            }

            string designTimeLicenseString = designTimeLicense == null ? string.Empty : designTimeLicense.SignedString;
            string runtimeLicenseString    = runtimeLicense == null ? string.Empty : runtimeLicense.SignedString;

            SaveProductLicense(licenseKey, userName, company, email, designTimeLicenseString, runtimeLicenseString);
            return(true);
        }
Example #13
0
        public static void Patch()
        {
            var  licenseUtils         = typeof(LicenseUtils);
            var  members              = licenseUtils.FindMembers(MemberTypes.All, BindingFlags.NonPublic | BindingFlags.Static, null, null);
            Type activatedLicenseType = null;

            foreach (var memberInfo in members)
            {
                if (memberInfo.Name.Equals("__activatedLicense", StringComparison.OrdinalIgnoreCase) && memberInfo is FieldInfo fieldInfo)
                {
                    activatedLicenseType = fieldInfo.FieldType;
                }
            }

            if (activatedLicenseType == null)
            {
                return;
            }

            var licenseKey = new LicenseKey
            {
                Expiry = DateTime.Now.AddYears(100),
                Ref    = "ServiceStack",
                Name   = "Enterprise",
                Type   = LicenseType.Enterprise
            };
            var constructor = activatedLicenseType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(LicenseKey) }, null);

            if (constructor == null)
            {
                return;
            }

            var activatedLicense      = constructor.Invoke(new object[] { licenseKey });
            var activatedLicenseField = licenseUtils.GetField("__activatedLicense", BindingFlags.NonPublic | BindingFlags.Static);

            if (activatedLicenseField != null)
            {
                activatedLicenseField.SetValue(null, activatedLicense);
            }
            // LicenseUtils.HasLicensedFeature(LicenseFeature.All) is now true
        }
Example #14
0
        /// <summary>
        /// If the Order Item has one of the marked Attributes, create a License string and return it
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public LicenseKey CreateLicense(OrderItem item)
        {
            LicenseKey license = new LicenseKey();

            license.ProductName = item.Product.GetLocalized(x => x.Name);

            var productKey = item.Product.GetAttribute <string>(Constants.LicenseKeyAttribute);

            if (productKey == null)
            {
                return(license);
            }

            if (_licenseSettings.DomainAttributeId != 0)
            {
                //let's see if this product has our Domain attribute
                var pva = _productAttributeParser.ParseProductAttributeMappings(item.AttributesXml).Where(a => a.ProductAttributeId == _licenseSettings.DomainAttributeId).FirstOrDefault();
                if (pva != null)
                {
                    var url = _productAttributeParser.ParseValues(item.AttributesXml, pva.Id).First();
                    license.Url         = url;
                    license.LicenseType = LicenseType.Domain.ToString();
                    license.License     = CreateLicense(LicenseType.Domain, url, productKey);
                    return(license);
                }
            }

            if (_licenseSettings.UrlAttributeId != 0)
            {
                var pva = _productAttributeParser.ParseProductAttributeMappings(item.AttributesXml).Where(a => a.ProductAttributeId == _licenseSettings.UrlAttributeId).FirstOrDefault();
                if (pva != null)
                {
                    var url = _productAttributeParser.ParseValues(item.AttributesXml, pva.Id).First();
                    license.Url         = url;
                    license.LicenseType = LicenseType.Url.ToString();
                    license.License     = CreateLicense(LicenseType.Url, url, productKey);
                    return(license);
                }
            }

            return(license);
        }
Example #15
0
        public DataTable GetExpirysData(int ExpiryValue)
        {
            DataTable  LicenseDataTable = new DataTable();
            LicenseKey ReturnObject     = new LicenseKey();

            try
            {
                string SqlQuery = "select DATEDIFF(DAY, GETDATE(),ExpirationDate),GETDATE(),ExpirationDate, li.*,lc.CompanyName,u.LoginName from  License li inner join Users u on li.CreateBy=u.ID inner join LicenseCompanys  lc on li.CompanyID=lc.ID  where  DATEDIFF(DAY, GETDATE(),ExpirationDate) <= '" + ExpiryValue + "' and ExpirationDate>=GETDATE()";

                LicenseDataTable = objAdaptor.FetchData(SqlQuery);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
            }
            return(LicenseDataTable);
        }
Example #16
0
        private void cmdLicense_Click(object sender, EventArgs e)
        {
            // get the text string from
            string license = txtLicense.Text;

            license = license.Trim();
            if (license.Length != 32)
            {
                MessageBox.Show("Invalid license, please re-check");
                return;
            }
            LicenseKey lk = new LicenseKey();

            try
            {
                lk.Init(license);
                if (lk.valid)
                {
                    txtLicense.Text = "";
                    //should really check, vendor id against plugin vendor id
                    KeyRing.Instance().m_keys.Add(lk);
                    string licensefile = UVDLPApp.Instance().m_apppath + UVDLPApp.m_pathsep + "licenses.key";
                    if (KeyRing.Instance().Save(licensefile))
                    {
                        MessageBox.Show("License Added to Keyring, Restart to take effect");
                    }
                    else
                    {
                        MessageBox.Show("Error Saving Keyring");
                    }
                }
                else
                {
                    MessageBox.Show("Invalid license, please re-check");
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Error validating license, please re-check");
            }
        }
        private void cmdLicense_Click(object sender, EventArgs e)
        {
            // get the text string from
            string license = txtLicense.Text;

            license = license.Trim();
            if (license.Length != 32)
            {
                MessageBox.Show(((DesignMode) ? "InvalidLicensePleaseReCheck" :UVDLPApp.Instance().resman.GetString("InvalidLicensePleaseReCheck", UVDLPApp.Instance().cul)));
                return;
            }
            LicenseKey lk = new LicenseKey();

            try
            {
                lk.Init(license);
                if (lk.valid)
                {
                    txtLicense.Text = "";
                    //should really check, vendor id against plugin vendor id
                    KeyRing.Instance().m_keys.Add(lk);
                    string licensefile = UVDLPApp.Instance().m_apppath + UVDLPApp.m_pathsep + "licenses.key";
                    if (KeyRing.Instance().Save(licensefile))
                    {
                        MessageBox.Show(((DesignMode) ? "LicenseAddedToKeyringRestartToTakeEffect" :UVDLPApp.Instance().resman.GetString("LicenseAddedToKeyringRestartToTakeEffect", UVDLPApp.Instance().cul)));
                    }
                    else
                    {
                        MessageBox.Show(((DesignMode) ? "ErrorSavingKeyring" :UVDLPApp.Instance().resman.GetString("ErrorSavingKeyring", UVDLPApp.Instance().cul)));
                    }
                }
                else
                {
                    MessageBox.Show(((DesignMode) ? "InvalidLicensePleaseReCheck" :UVDLPApp.Instance().resman.GetString("InvalidLicensePleaseReCheck", UVDLPApp.Instance().cul)));
                }
            }
            catch (Exception)
            {
                MessageBox.Show(((DesignMode) ? "ErrorValidatingLicensePleaseReCheck" :UVDLPApp.Instance().resman.GetString("ErrorValidatingLicensePleaseReCheck", UVDLPApp.Instance().cul)));
            }
        }
Example #18
0
        public DataTable GetEstimateLicensesData()
        {
            DataTable  EstimateLicensesDataTable = new DataTable();
            LicenseKey ReturnObject = new LicenseKey();

            try
            {
                //	string SqlQuery = "select * from ServerTypes";

                string SqlQuery = "select ServerType,UnitCost,'' as noofservers,'' as totalunits from ServerTypes";
                EstimateLicensesDataTable = objAdaptor.FetchData(SqlQuery);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
            }
            return(EstimateLicensesDataTable);
        }
 private void CheckLicensing()
 {
     foreach (PluginEntry pe in m_plugins)
     {
         try
         {
             // iterate through all loaded plugins
             // get the vendor id
             int        vid = pe.m_plugin.GetInt("VendorID");
             LicenseKey lk  = KeyRing.Instance().Find(vid);
             if (lk != null)
             {
                 pe.m_licensed = true;
             }
         }
         catch (Exception ex)
         {
             DebugLogger.Instance().LogError(ex);
         }
     }
 }
Example #20
0
        public void LicenseStatusTest()
        {
            var test = new LicenseKey();

            var res = Newtonsoft.Json.JsonConvert.SerializeObject(test);

            var activateToken = activateDeactivate;
            var featureToken  = "WyI2Iiwib3lFQjFGYk5pTHYrelhIK2pveWdReDdEMXd4ZDlQUFB3aGpCdTRxZiJd";

            var result = Key.Activate(token: activateToken, parameters: new ActivateModel()
            {
                Key = "GEBNC-WZZJD-VJIHG-GCMVD", ProductId = 3349, Sign = true, MachineCode = "foo", Metadata = true
            });

            var license = result.LicenseKey;

            Assert.IsTrue(license.IsValid());
            Assert.IsTrue(result.Metadata.LicenseStatus.IsValid);

            Assert.IsTrue(result.Metadata.VerifySignature("<RSAKeyValue><Modulus>sGbvxwdlDbqFXOMlVUnAF5ew0t0WpPW7rFpI5jHQOFkht/326dvh7t74RYeMpjy357NljouhpTLA3a6idnn4j6c3jmPWBkjZndGsPL4Bqm+fwE48nKpGPjkj4q/yzT4tHXBTyvaBjA8bVoCTnu+LiC4XEaLZRThGzIn5KQXKCigg6tQRy0GXE13XYFVz/x1mjFbT9/7dS8p85n8BuwlY5JvuBIQkKhuCNFfrUxBWyu87CFnXWjIupCD2VO/GbxaCvzrRjLZjAngLCMtZbYBALksqGPgTUN7ZM24XbPWyLtKPaXF2i4XRR9u6eTj5BfnLbKAU5PIVfjIS+vNYYogteQ==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"));
        }
        public IActionResult GenerateKey(int course_id, int number)
        {
            try
            {
                if (number == 0)
                {
                    throw new Exception("Zero requested");
                }

                //Generate licenses
                string[] new_licenses = new string[number];
                for (int i = 0; i < number; i++)
                {
                    //Get current date
                    var current_date = DateTime.Now;
                    var plain_text   = current_date + course_id.ToString() + i;
                    using (MD5 md5Hash = MD5.Create())
                    {
                        string hash           = GetMd5Hash(md5Hash, plain_text);
                        string formatted_hash = FormatLicenseKey(hash);
                        new_licenses[i] = formatted_hash;
                        //Add in the database
                        var db_object = new LicenseKey
                        {
                            Value     = formatted_hash,
                            Course_id = course_id,
                            Used      = false,
                            Active    = true
                        };
                        _context.LicenseKey.Add(db_object);
                        _context.SaveChanges();
                    }
                }
                return(RedirectToAction("Success", "LicenseKeys", new { keys = new_licenses }));
            }
            catch
            {
                return(RedirectToAction("Error", "LicenseKeys"));
            }
        }
Example #22
0
        public void UsageCounter()
        {
            var token     = getKeys;
            var tokenDObj = "WyIxMSIsInRFLzRQSzJkT2V0Y1pyN3Y3a1I2Rm9YdmczNUw0SzJTRHJwUERhRFMiXQ==";

            // this is a simple hack to retrieve license info (auto complete it).
            var license = new LicenseKey {
                ProductId = 3349, Key = "GEBNC-WZZJD-VJIHG-GCMVD"
            };

            license.Refresh(token);

            if (license.DataObjects.Contains("usagecount"))
            {
                var dataObj = license.DataObjects.Get("usagecount");

                // attempt to increment. true means we succeed.
                if (dataObj.IncrementIntValue(token: tokenDObj,
                                              incrementValue: 1,
                                              enableBound: true,
                                              upperBound: 4,
                                              licenseKey: license))
                {
                    // success, we can keep using this feature
                }
                else
                {
                    dataObj.SetIntValue(tokenDObj, 0);
                    Assert.Fail();
                    // fail, the the user has already used it 10 times.
                }
            }
            else
            {
                // if it does not exist, add a new one.
                license.AddDataObject(tokenDObj, new DataObject {
                    Name = "usagecount", IntValue = 0
                });
            }
        }
 private void cmdLicense_Click(object sender, EventArgs e)
 {
     // get the text string from
     string license = txtLicense.Text;
     license = license.Trim();
     if (license.Length != 32)
     {
         MessageBox.Show("Invalid license, please re-check");
         return;
     }
     LicenseKey lk = new LicenseKey();
     try
     {
         lk.Init(license);
         if (lk.valid)
         {
             txtLicense.Text = "";
             //should really check, vendor id against plugin vendor id
             KeyRing.Instance().m_keys.Add(lk);
             string licensefile = UVDLPApp.Instance().m_apppath + UVDLPApp.m_pathsep + "licenses.key";
             if (KeyRing.Instance().Save(licensefile))
             {
                 MessageBox.Show("License Added to Keyring, Restart to take effect");
             }
             else
             {
                 MessageBox.Show("Error Saving Keyring");
             }
         }
         else
         {
             MessageBox.Show("Invalid license, please re-check");
         }
     }
     catch (Exception)
     {
         MessageBox.Show("Error validating license, please re-check");
     }
 }
Example #24
0
        public DataTable GetThirtydaysExpiry(string ID)
        {
            DataTable  LicenseDataTable = new DataTable();
            LicenseKey ReturnObject     = new LicenseKey();

            try
            {
                string sqlQuery = "select li.*,lc.CompanyName,u.LoginName from  License li inner join Users u on li.CreateBy=u.ID inner join LicenseCompanys  lc on li.CompanyID=lc.ID where ExpirationDate  BETWEEN CONVERT(date, getdate())  and (select dateadd(m, 1, getdate())) and " +
                                  "li.CreatedOn in (select max (Createdon) from License group by companyid)  order by ExpirationDate Asc ";


                LicenseDataTable = objAdaptor.FetchData(sqlQuery);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
            }
            return(LicenseDataTable);
        }
Example #25
0
        public void Does_deserialize_LicenseKey()
        {
            var key = new LicenseKey {
                Name   = "The Name",
                Ref    = "1000",
                Type   = LicenseType.Business,
                Expiry = new DateTime(2001, 01, 01),
                Meta   = (long)(LicenseMeta.Subscription | LicenseMeta.Cores),
            };

            var jsv = key.ToJsv();

            Assert.That(jsv, Does.Contain($"eta:" + (int)key.Meta));
            jsv.Print();

            var fromKey = jsv.FromJsv <LicenseKey>();

            Assert.That(fromKey.Name, Is.EqualTo(key.Name));
            Assert.That(fromKey.Ref, Is.EqualTo(key.Ref));
            Assert.That(fromKey.Type, Is.EqualTo(key.Type));
            Assert.That(fromKey.Expiry, Is.EqualTo(key.Expiry));
            Assert.That(fromKey.Meta, Is.EqualTo(key.Meta));

            var oldKey = jsv.FromJsv <OldLicenseKey>();

            Assert.That(oldKey.Name, Is.EqualTo(key.Name));
            Assert.That(oldKey.Ref, Is.EqualTo(key.Ref));
            Assert.That(oldKey.Type, Is.EqualTo(key.Type));
            Assert.That(oldKey.Expiry, Is.EqualTo(key.Expiry));

            var oldJsv = oldKey.ToJsv();

            fromKey = oldJsv.FromJsv <LicenseKey>();
            Assert.That(fromKey.Name, Is.EqualTo(key.Name));
            Assert.That(fromKey.Ref, Is.EqualTo(key.Ref));
            Assert.That(fromKey.Type, Is.EqualTo(key.Type));
            Assert.That(fromKey.Expiry, Is.EqualTo(key.Expiry));
            Assert.That(fromKey.Meta, Is.EqualTo(0));
        }
        public void Test1()
        {
            var software = new LicensedSoftware("Microsoft", "Visual Studio 2019", SoftwareType.User);

            software.AddLicense(LicenseKey.Parse("test key"), DateTime.Now, DateTime.Now.AddDays(365),
                                OrganizationId.Create(), 10, 1000, "Test description");


            var @event = software.Events.FirstOrDefault();

            Assert.IsAssignableFrom <LicenseCreatedEvent>(@event);

            var eventCreatedLicense = @event as LicenseCreatedEvent;

            software.AddLicense(eventCreatedLicense.Key, eventCreatedLicense.DateStart, eventCreatedLicense.DateEnd,
                                eventCreatedLicense.OrganizationId, eventCreatedLicense.Activations, eventCreatedLicense.Price,
                                eventCreatedLicense.Description);

//            software.Licenses.First((x, i) => i == 0)
//
//            Assert.AreEqual(originalLicense.Key, copyLicense.Key);
//            Assert.AreEqual(originalLicense.ActivationsCount, copyLicense.ActivationsCount);
        }
Example #27
0
        public string InsertLicense(LicenseKey LK)
        {
            if (DoesLicenseExist(LK.Key, LK.SoftwareId))
            {
                return("License Key for specified software already exists");
            }

            var License = SQLTables.TableColumns.LicenseKeys;

            License["SoftwareID"]           = LK.SoftwareId.ToString();
            License["LicenseKey"]           = LK.Key;
            License["DateModified"]         = LK.DateUpdated.ToString("s");
            License["ExpirationDate"]       = LK.DateExpiring.ToString("s");
            License["KeyHolder"]            = LK.Holder;
            License["KeyManager"]           = LK.Manager;
            License["HolderLoginID"]        = LK.HolderID;
            License["LicenseCost"]          = String.Format("{0:0.00}", LK.LicenseCost);
            License["RequisitionNumber"]    = LK.RequisitionNumber;
            License["ChargebackComplete"]   = Convert.ToInt32(LK.ChargebackComplete).ToString();
            License["ProviderID"]           = LK.Provider.ToString();
            License["AssignmentStatus"]     = LK.Assignment.ToString();
            License["SpeedChart"]           = LK.Speedchart;
            License["DateAssigned"]         = LK.DateAssigned.ToString("s");
            License["DateRemoved"]          = LK.DateRemoved.ToString("s");
            License["LicenseHolderCompany"] = LK.LicenseHolderCompany.ToString();
            License["Description"]          = LK.Description;
            License["Comments"]             = LK.Comments;
            License["Comments"]             = LK.Comments;
            License["FileSubpath"]          = LK.fileSubpath == Guid.Empty ? "" : LK.fileSubpath.ToString();
            License["LastModifiedBy"]       = LK.LastModifiedBy;

            string error = "";

            return(SQLiteDataHelper.Insert("LicenseKeys", License, ref error)
                ? "License \"" + LK.Key + "\" Inserted Successfully"
                : error);
        }
        private void AssertKey(string licenseKeyText, LicenseKey expectedKey)
        {
            var licenseKey = licenseKeyText.ToLicenseKey();

            Assert.That(licenseKey.Ref, Is.EqualTo(expectedKey.Ref));
            Assert.That(licenseKey.Name, Is.EqualTo(expectedKey.Name));
            Assert.That(licenseKey.Type, Is.EqualTo(expectedKey.Type));
            //Assert.That(licenseKey.Hash, Is.EqualTo(expectedKey.Hash));
            Assert.That(licenseKey.Expiry, Is.EqualTo(expectedKey.Expiry));
        }
Example #29
0
        //licenses can be in a few states:
        // licensed and enabled - load the plugin and use it
        // licensed and disabled - do not use the plugin, do not initialize
        // un-licensed and enabled - prompt the user for license key, do not initialize it
        // un-licensed and disabled - ignore this plugin, keep entry for it, do not initialize
        public void ScanForPlugins()
        {
            // load the list of plugin states
            string picn = m_apppath + m_pathsep + "pluginconfig.cfg"; // plugin configuration name

            m_pluginstates.Load(picn);

            // get a list of dll's in this current directory
            // try to register them as a plug-in
            string[] filePaths = Directory.GetFiles(m_apppath, "*.dll");
            foreach (String pluginname in filePaths)
            {
                string args = Path.GetFileNameWithoutExtension(pluginname);
                if (args.ToLower().StartsWith("pl"))
                {
                    // located a dll that is a potential plugin
                    Type ObjType = null;
                    try
                    {
                        // load it
                        Assembly ass = null;
                        //string args = Path.GetFileNameWithoutExtension(pluginname);
                        ass = Assembly.Load(args);
                        if (ass != null)
                        {
                            ObjType = ass.GetType(args + ".PlugIn"); // look for the plugin interface
                            // OK Lets create the object as we have the Report Type
                            if (ObjType != null)
                            {
                                // create an instance of the plugin
                                IPlugin plug = (IPlugin)Activator.CreateInstance(ObjType);
                                // create an entry for the plugin
                                PluginEntry pe = new PluginEntry(plug, args);
                                //add the entry to the list of plugins
                                m_plugins.Add(pe);
                                //mark the plugin as enabled by default
                                pe.m_enabled = true;
                                if (m_pluginstates.InList(args))
                                {
                                    // this plugin is listed in the disabled list.
                                    DebugLogger.Instance().LogInfo("Plugin " + args + " marked disabled");
                                    pe.m_enabled = false;
                                }

                                //get the vendor id of the newly loaded plugin
                                int vid = plug.GetInt("VendorID");
                                //look for the license key for this plugin
                                LicenseKey lk = KeyRing.Instance().Find(vid);
                                // if we found it, mark it as licensed
                                if (lk != null)
                                {
                                    //initialize the plugin by setting the host.
                                    if (pe.m_enabled)
                                    {
                                        plug.Host = this; // this will initialize the plugin - the plugin's init function will be called
                                        DebugLogger.Instance().LogInfo("Loaded licensed plugin " + args);
                                    }
                                }

                                /*
                                 * if (pe.m_enabled && pe.m_licensed)
                                 * {
                                 *  DebugLogger.Instance().LogInfo("Loaded licensed plugin " + args);
                                 * }else if (pe.m_enabled && )
                                 * */
                                DebugLogger.Instance().LogInfo("Loaded plugin " + args);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        DebugLogger.Instance().LogError(ex.Message);
                    }
                }
            }
        }
		private void InsertServiceLicenseKey(ServiceLicenseKey serviceLicenseKey)
		{
			using (ScutexServiceEntities db1 = new ScutexServiceEntities())
			{
				LicenseKey licKey = new LicenseKey();
				licKey.Key = serviceLicenseKey.Key;
				licKey.ActivationCount = serviceLicenseKey.ActivationCount;
				licKey.Deactivated = serviceLicenseKey.Deactivated;
				licKey.DeactivatedOn = serviceLicenseKey.DeactivatedOn;
				licKey.DeactivatedReason = serviceLicenseKey.DeactivatedReason;
				licKey.LicenseSetId = serviceLicenseKey.LicenseSetId;
				licKey.CreatedOn = serviceLicenseKey.CreatedOn;

				db1.AddToLicenseKeys(licKey);
				db1.SaveChanges();
			}
		}
 public void AddLicense(LicenseKey key, DateTime dateStart, DateTime dateEnd, OrganizationId organizationId, int activations,
                        int price, string description)
 {
     Apply(new LicenseCreatedEvent(key, dateStart, dateEnd, organizationId, activations, price, description));
 }
Example #32
0
 /// <summary>
 /// Checks if the current license key is on the correct device.
 /// </summary>
 /// <param name="licenseKey">The license key object.</param>
 /// <returns></returns>
 public static bool IsOnRightMachine(LicenseKey licenseKey)
 {
     return(licenseKey.IsOnRightMachine(SKGL.SKM.getSHA256).IsValid());
 }
        public void AddInstance(DateTime installDate, ServerId serverId, OrganizationId organizationId, LicenseKey key)
        {
            var license = Licenses.First(x => x.Key.Equals(key));

            if (license is null)
            {
                //  todo: use domain exception
                throw new Exception("This key not exist");
            }

            if (license.ActivationsInstances.Count() >= license.ActivationsCount)
            {
                //  todo: use domain exception
                throw new Exception("This license has a maximum number of copies");
            }

            if (!license.OrganizationId.Equals(organizationId))
            {
                //  todo: use domain exception
                throw new Exception("You cannot apply the license of someone else's organization");
            }

            Apply(new LicensedSoftwareInstanceCreatedEvent(SoftwareInstanceId.Create(), installDate, serverId,
                                                           organizationId, key));
        }
 public LicensedSoftwareInstanceCreatedEvent(SoftwareInstanceId id, DateTime installDate, ServerId serverId,
                                             OrganizationId organizationId, LicenseKey key) : base(id, installDate, serverId, organizationId)
 {
     Key = key;
 }
Example #35
0
 public CreateLicensedSoftwareInstanceCommand(Guid softwareId, DateTime installDate, ServerId serverId,
                                              OrganizationId organizationId, LicenseKey key) : base(softwareId, installDate, serverId, organizationId)
 {
     Key = key;
 }