Class with information about license.
Esempio n. 1
0
 public static void ValidateCurrentLicense()
 {
     lock (_validationLock)
     {
         CurrentLicense = ValidateLicense(LicenseFilePath);
     }
 }
        public IHttpActionResult PutLicense(int id, License license)
        {
            license.ModificationDate = DateTime.Now;

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != license.LicenseId)
            {
                return BadRequest();
            }
            
            _db.MarkAsModified(license);

            try
            {
                _db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!LicenseExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }
Esempio n. 3
0
		public Splash() : base() {
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
            _license = LicenseManager.Validate(typeof(Splash), this);
			
			//	Size to the image so as to display it fully and position the form in the center screen with no border.
			this.Size = this.BackgroundImage.Size;
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
			this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;

			//	Force the splash to stay on top while the mainform renders but don't show it in the taskbar.
			this.TopMost = true;
			this.ShowInTaskbar = false;
			
			//	Make the backcolour Fuchia and set that to be transparent
			//	so that the image can be shown with funny shapes, round corners etc.
			this.BackColor = System.Drawing.Color.Fuchsia;
			this.TransparencyKey = System.Drawing.Color.Fuchsia;

			//	Initialise a timer to do the fade out
			if (this.components == null) {
				this.components = new System.ComponentModel.Container();
			}
			this.fadeTimer = new System.Windows.Forms.Timer(this.components);
            //	Size to the image so as to display it fully and position the form in the center screen with no border.
            this.Size = this.BackgroundImage.Size;

		}
Esempio n. 4
0
        protected void btnAddLicense_Click(object sender, EventArgs e)
        {
            License license = new License();
            license.Software = txtBoxSoftware.Text;
            license.OS = txtBoxOperatingSystem.Text;
            license.Key = txtBoxKey.Text;
            license.NumOfCopies = Convert.ToInt32(txtBoxNumOfCopies.Text);
            license.ExpirationDate = txtBoxNumOfCopies.Text;
            license.ExpirationDate = txtBoxExpirationDate.Text;
            license.Notes = txtBoxNotes.Text;
            license.Type = ddlType.SelectedValue;

            lblMessage.Text = License.saveLicense(license);
            lblMessage.Visible = true;

            if (lblMessage.Text == "License created successfully!<bR>")
            {
                GridView1.DataBind();
                GridView2.DataBind();

                panelCreateLicense.Visible = false;
                btnCreateLicense.Visible = true;

                txtBoxSoftware.Text = "";
                txtBoxOperatingSystem.Text = "";
                txtBoxKey.Text = "";
                txtBoxNumOfCopies.Text = "";
                txtBoxExpirationDate.Text = "";
                txtBoxNotes.Text = "";
            }
        }
        public frmMain()
        {
            InitializeComponent();

            dbConnect = new DBConnect();
            License = new License();
        }
Esempio n. 6
0
        public void AddLicenseWithValidData()
        {
            var license = new License("GiantLicense", "TestUrl", "TestLink");

            this.facade.CreateLicense(license);
            LicensesPageAsserter.AssertLicenseExist(LicensesPage.Instance, license);
        }
        public void Exports_With_User_Defined_KeyValues_When_Available()
        {
            var service = new ExportService() as IExportService;
            var product = new Product { Id = Guid.NewGuid(), Name = "My Product", };
            var license = new License
            {
                LicenseType = LicenseType.Standard, 
                OwnerName = "License Owner", 
                ExpirationDate = null,
            };
            
            license.Data.Add(new UserData { Key = "KeyOne", Value = "ValueOne"});
            license.Data.Add(new UserData { Key = "KeyTwo", Value = "ValueTwo"});

            var path = Path.GetTempFileName();
            var file = new FileInfo(path);

            service.Export(product, license, file);

            var reader = file.OpenText();
            var content = reader.ReadToEnd();

            Assert.NotNull(content);
            Assert.Contains("KeyOne=\"ValueOne\"", content);
            Assert.Contains("KeyTwo=\"ValueTwo\"", content);
        }
        public static License PromptUserForLicense(License currentLicense)
        {
            SynchronizationContext synchronizationContext = null;
            try
            {
                synchronizationContext = SynchronizationContext.Current;
                using (var form = new LicenseExpiredForm())
                {
                    form.CurrentLicense = currentLicense;
                    form.ShowDialog();
                    if (form.ResultingLicenseText == null)
                    {
                        return null;
                    }

                    new RegistryLicenseStore()
                        .StoreLicense(form.ResultingLicenseText);

                    return LicenseDeserializer.Deserialize(form.ResultingLicenseText);
                }

            }
            finally
            {
                SynchronizationContext.SetSynchronizationContext(synchronizationContext);
            }
        }
Esempio n. 9
0
        public void CancelAddLicense()
        {
            var license = new License("TestLicense", "TestUrl", "TestLink");

            this.facade.CancelCreateLicense(license);
            LicensesPageAsserter.AssertLicenseNotExist(LicensesPage.Instance, license);
        }
Esempio n. 10
0
        public frmMain ()
        {
            InitializeComponent();

            //Obtain the license
            license = LicenseManager.Validate(typeof(frmMain), this);
        }
        private static LicenseState GetLicenseState(Database db, License license, DateTime? buildDate, DateTime now, Dictionary<int, LicenseState> cache, Dictionary<int, string> errors)
        {
            LicenseState licenseState;

            if (cache.TryGetValue(license.LicenseId, out licenseState))
                return licenseState;

            ParsedLicense parsedLicense = ParsedLicenseManager.GetParsedLicense(license.LicenseKey);
            if (parsedLicense == null)
            {
                errors[license.LicenseId] = string.Format("The license key #{0} is invalid.", license.LicenseId);
                return null;
            }

            if (!parsedLicense.IsLicenseServerElligible())
            {
                errors[license.LicenseId] = string.Format("The license #{0}, of type {1}, cannot be used in the license server.",
                    license.LicenseId, parsedLicense.LicenseType);
                return null;
            }


            if ( !(buildDate == null || parsedLicense.SubscriptionEndDate == null || buildDate <= parsedLicense.SubscriptionEndDate ) )
            {
                errors[license.LicenseId] = string.Format("The maintenance subscription of license #{0} ends on {1:d} but the requested version has been built on {2:d}.",
                    license.LicenseId, parsedLicense.SubscriptionEndDate, buildDate);
                return null;
            }

           
            licenseState = new LicenseState(now, db, license, parsedLicense);
            cache.Add(license.LicenseId, licenseState);
            return licenseState;
           
        }
        protected override bool IsNormalLicenseExpired(License license, DateTime expirationDateTime, DateTime validationDateTime)
        {
            var entryAssembly = AssemblyHelper.GetEntryAssembly();
            var linkerTimestamp = entryAssembly.GetBuildDateTime();

            return (linkerTimestamp > expirationDateTime);
        }
        protected void Application_Start()
        {
            //Register areas
            AreaRegistration.RegisterAllAreas();

            //Set license
            License license = new License();
            license.SetLicense(@".\..\..\licenses\GroupDocs.Comparison.lic");

            //Register filters
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

            //Create comparison settings
            var comparisonSettings = new ComparisonWidgetSettings
            {
                //Set root storage path
                RootStoragePath = Server.MapPath("~/App_Data/"),
                //Set comparison behavior
                ComparisonBehavior =
                {
                    StyleChangeDetection = true,
                    GenerateSummaryPage = true
                },
                //Set license for Viewer
                LicensePath = @".\..\..\licenses\GroupDocs.Viewer.lic"
            };

            //Initiate comparison widget
            ComparisonWidget.Init(comparisonSettings);
            //Register routes
            RouteConfig.RegisterRoutes(RouteTable.Routes, comparisonSettings);
            //Bundle scripts
            BundleConfigurator.Configure(comparisonSettings);
        }
Esempio n. 14
0
 public void NonExpiredLicense()
 {
     Instant expiry = Instant.FromUtc(2000, 1, 1, 0, 0, 0);
     StubClock clock = new StubClock(expiry - Duration.OneMillisecond);
     License license = new License(expiry, clock);
     Assert.IsFalse(license.HasExpired);
 }
		public override void Execute()
		{
			var orderMessage = documentSession.Load<OrderMessage>(OrderId);

			var license = new License
			{
				Key = Guid.NewGuid(),
				OrderId = orderMessage.Id
			};
			documentSession.Store(license);

			TaskExecuter.ExecuteLater(new SendEmailTask
			{
				From = "*****@*****.**",
				To = orderMessage.Email,
				Subject = "Congrats on your new tekpub thingie",
				Template = "NewOrder",
				ViewContext = new
				{
					orderMessage.OrderId,
					orderMessage.Name,
					orderMessage.Amount,
					LiceseKey = license.Key
				}
			});

			orderMessage.Handled = true;
		}
        //functions

        //Update the vie with the selected license
        public void SelectedLicenseChanged(string license, string count)
        {
            selectedlicense = null;
            int c = 0;
            try
            {
                c = int.Parse(count);
            }
            catch (Exception e)
            {
                Log.WriteLog("Error parsing int");
            }
            foreach (License l in list_allAvailableLicenses)
            {
                if (l.Name.Equals(license))
                {
                    selectedlicense = l;
                }
            }
            if (selectedlicense != null)
            {
                view.UpdateLicense(selectedlicense, c);
            }



        }
Esempio n. 17
0
 public void ExpiryAtExactInstance()
 {
     Instant expiry = Instant.FromUtc(2000, 1, 1, 0, 0, 0);
     StubClock clock = new StubClock(expiry);
     License license = new License(expiry, clock);
     Assert.IsTrue(license.HasExpired);
 }
Esempio n. 18
0
        public static bool ShowWindow()
        {
            string keySW = "Software";
              string keyESRI = "ESRI";
              string keyDF = "DeedDrafter";
              string keyExecute = "Execute";

              string acceptValue = "{61F78689-7E9A-47CC-B8F0-DC4428AD4937}";

              RegistryKey regKeySW = Registry.CurrentUser.OpenSubKey(keySW);
              if (regKeySW != null)
              {
            RegistryKey regKeyESRI = regKeySW.OpenSubKey(keyESRI);
            if (regKeyESRI != null)
            {
              RegistryKey regKeyDF = regKeyESRI.OpenSubKey(keyDF);
              if (regKeyDF != null)
              {
            object value = regKeyDF.GetValue(keyExecute, "");
            if (value.ToString() == acceptValue)
              return true;
              }
            }
              }

              var license = new License();
              license.ShowDialog();

              if (license.Agreed)
              {
            // If we have any errors, allow the app to start, but
            // the user will have to accept the agreement again :(
            if (regKeySW == null)
              return true;

            try
            {
              regKeySW = Registry.CurrentUser.OpenSubKey(keySW, RegistryKeyPermissionCheck.ReadWriteSubTree);
              if (regKeySW == null)
            return true;

              RegistryKey regKeyESRI = regKeySW.OpenSubKey(keyESRI, RegistryKeyPermissionCheck.ReadWriteSubTree);
              if (regKeyESRI == null)
            regKeyESRI = regKeySW.CreateSubKey(keyESRI, RegistryKeyPermissionCheck.ReadWriteSubTree);
              if (regKeyESRI == null)
            return true;

              RegistryKey regKeyDF = regKeyESRI.OpenSubKey(keyDF, RegistryKeyPermissionCheck.ReadWriteSubTree);
              if (regKeyDF == null)
            regKeyDF = regKeyESRI.CreateSubKey(keyDF, RegistryKeyPermissionCheck.ReadWriteSubTree);
              if (regKeyDF == null)
            return true;

              regKeyDF.SetValue(keyExecute, acceptValue);
            }
            catch { }
              }

              return license.Agreed;
        }
Esempio n. 19
0
 public LicensedColorComboBox()
 {
     license = LicenseManager.Validate(typeof(LicensedColorComboBox), this);
     FillItems();
     base.SelectedItem = base.Items[7]; // Black
     base.DrawItem += new DrawItemEventHandler(this.combo_DrawItem);
 }
Esempio n. 20
0
		public ValidationResult IsLicenseValidForSaving(License license)
		{
			ValidationResult result = new ValidationResult();
			result.IsValid = true;

			if (String.IsNullOrEmpty(license.Name))
			{
				result.IsValid = false;
				result.ValidationErrors.Add("Project Name cannot be null.");
			}

			if (license.Product == null)
			{
				result.IsValid = false;
				result.ValidationErrors.Add("License project must contain a Product.");
			}

			if (license.KeyGeneratorType == KeyGeneratorTypes.None)
			{
				result.IsValid = false;
				result.ValidationErrors.Add("You must select a valid License Key Generator type.");
			}

			if (license.TrialSettings == null ||
				license.TrialSettings.ExpirationOptions == TrialExpirationOptions.None ||
				String.IsNullOrEmpty(license.TrialSettings.ExpirationData))
			{
				result.IsValid = false;
				result.ValidationErrors.Add("You must select a Trial Expiration type.");
			}

			return result;
		}
Esempio n. 21
0
        public void Export(Product product, License license, FileInfo path)
        {
            var generator = new LicenseGenerator(product.PrivateKey);
            var expiration = license.ExpirationDate.GetValueOrDefault(DateTime.MaxValue);
            var key = generator.Generate(license.OwnerName, license.ID, expiration, license.Data.ToDictionary(userData => userData.Key, userData => userData.Value), license.LicenseType);

            File.WriteAllText(path.FullName, key);
        }
Esempio n. 22
0
 /// <summary>
 /// Creates new license object with given properties. See lmBoxAPI JavaDoc for details:
 /// http://lmbox.labs64.com/javadoc/index.html?com/labs64/lmbox/core/service/LicenseService.html
 /// </summary>
 public static License create(Context context, String licenseeNumber, String licenseTemplateNumber, String transactionNumber, License newLicense)
 {
     newLicense.licenseeNumber = licenseeNumber;
     newLicense.licenseTemplateNumber = licenseTemplateNumber;
     newLicense.licenseProperties.Add(Constants.Transaction.TRANSACTION_NUMBER, transactionNumber);
     lmbox output = LmBoxAPI.request(context, LmBoxAPI.Method.POST, Constants.License.endPoint, newLicense.ToDictionary());
     return new License(output.items[0]);
 }
 public IssueLicenseViewModel()
 {
     CurrentLicense = new License
     {
         LicenseType = LicenseType.Trial,
         ExpirationDate = DateTime.Now.AddDays(Settings.Default.DefaultTrialDays).Date
     };
 }
Esempio n. 24
0
 private void button1_Click(object sender, EventArgs e)
 {
     License l = new License();
     int y = Convert.ToInt32(numericUpDown1.Value);
     int m = Convert.ToInt32(numericUpDown2.Value);
     int d = Convert.ToInt32(numericUpDown3.Value);
     textBox1.Text = l.encode(l.confuse(y, m, d));
 }
        /// <summary>
        /// Sets the license.
        /// </summary>
        public override void SetLicense()
        {
            License license = new License();
            license.SetLicense(AttachmentResources.LicenseFileName);

            Aspose.Pdf.License pdfLicense = new Aspose.Pdf.License();
            pdfLicense.SetLicense(AttachmentResources.LicenseFileName);
        }
  /// <summary>
 /// Constroi um objeto recuperando e definindo a licença de uso
 /// </summary>
 public PDF2TextAsposePDFConverter()
 {
     var assembly = Assembly.GetExecutingAssembly();
     License license = new License();
     using (Stream stream = assembly.GetManifestResourceStream("Carubbi.PDF.Assets.Aspose.Total.lic"))
     {
         license.SetLicense(stream);
     }
 }
        public JsonResult Update([DataSourceRequest] DataSourceRequest request, License license)
        {
            if (license != null && ModelState.IsValid)
            {
                LicenseRepository.Repository.Update(license);
            }

            return Json(ModelState.ToDataSourceResult());
        }
 /// <summary>
 /// Constroi um leitor com a licença já configurada
 /// </summary>
 public LeitorAsposeCells()
 {
     var assembly = Assembly.GetExecutingAssembly();
     License license = new License();
     using (Stream stream = assembly.GetManifestResourceStream("Carubbi.Excel.Assets.Aspose.Total.lic"))
     {
         license.SetLicense(stream);           
     }
 }
        // GET: ManageLicenses/Create
        public ActionResult Create(int? id)
        {
            ViewBag.FullName = getUserName();
            var volunteerID = id;
            License license = new License();
            license.volID = db.Volunteers.Where(s => s.volID == volunteerID).Select(v => v.volID).Single();

            return View(license);
        }
Esempio n. 30
0
 public static DomainLicense Create(string domainName, License license)
 {
     return new DomainLicense
     {
         DomainName = domainName,
         License = license,
         LicenseId = license.ObjectId
     };
 }
Esempio n. 31
0
 public override string ToString()
 {
     return($"{License.ToString()} WITH {Exception.ToString()}");
 }
Esempio n. 32
0
        public async Task GoDig(Report report)
        {
            var initX = report.Area.PosX.Value;
            var sizeX = report.Area.SizeX;

            var initY = report.Area.PosY.Value;
            var sizeY = report.Area.SizeY;

            var list = new List <Task <Report> >();

            for (int x = initX; x < (initX + sizeX); x++)
            {
                list.Add(this.Explore(new Area(x, initY, 1, sizeY)));
            }

            Task.WaitAll(list.ToArray());

            foreach (var result in list)
            {
                if (result.Result.Amount > 0)
                {
                    var left = result.Result.Amount;

                    for (int y = initY; y < (initY + sizeY) && left > 0; y++)
                    {
                        var explore = await this.Explore(new Area(result.Result.Area.PosX, y, 1, 1));

                        var depth = 1;

                        if (explore.Amount > 0)
                        {
                            var license = new License(0, 0, 0);
                            try
                            {
                                await _digSignal.WaitAsync();

                                license = await UpdateLicense();

                                while (depth <= 10 && left > 0 && explore.Amount > 0)
                                {
                                    if (license.DigUsed >= license.DigAllowed)
                                    {
                                        license = await UpdateLicense();
                                    }

                                    var result1 = await Dig(new Dig(license.Id.Value, result.Result.Area.PosX, y, depth));

                                    license.DigUsed += 1;

                                    if (result1 != null)
                                    {
                                        explore.Amount -= result1.Count;
                                        left           -= result1.Count;
                                        foreach (var treasure in result1)
                                        {
                                            treasureQueue.Add(new Gold()
                                            {
                                                Money = treasure, Depth = depth
                                            });
                                        }
                                    }
                                    depth += 1;
                                }
                            }
                            finally
                            {
                                if (license.DigUsed < license.DigAllowed)
                                {
                                    licenses.Add(license);
                                }
                                _digSignal.Release();
                            }
                        }
                    }
                }
            }
        }
Esempio n. 33
0
 public MyHttpServer(int port)
     : base(port)
 {
     license = new License();
 }
Esempio n. 34
0
        public byte[] GetProcessedTemplate(DocsPaVO.utente.InfoUtente infoUtente, DocsPaVO.documento.SchedaDocumento sd)
        {
            byte[] content = null;
            System.IO.MemoryStream stream = new System.IO.MemoryStream();

            // Percorso modello
            string pathModel = sd.template.PATH_MODELLO_1;

            try
            {
                //System.IO.FileStream licenseStream = new System.IO.FileStream("C:\\Temp\\Aspose.total.xml", System.IO.FileMode.Open, System.IO.FileAccess.Read);

                // Caricamento licenza
                DocsPaDB.Query_DocsPAWS.ClientSideModelProcessor csmp = new DocsPaDB.Query_DocsPAWS.ClientSideModelProcessor();

                Aspose.Slides.License lic = new License();
                byte[] licenseContent     = csmp.GetLicense("ASPOSE");
                if (licenseContent != null)
                {
                    System.IO.MemoryStream licenseStream = new System.IO.MemoryStream(licenseContent, 0, licenseContent.Length);
                    lic.SetLicense(licenseStream);
                    licenseStream.Close();
                }

                DocsPaVO.Modelli.ModelKeyValuePair[] commonFields = this.GetModelKeyValuePairs(infoUtente, sd);

                // Lettura modello con Aspose
                using (Presentation ppt = new Presentation(pathModel))
                {
                    // 1 - Analisi master
                    foreach (LayoutSlide layoutSlide in ppt.LayoutSlides)
                    {
                        foreach (IShape shape in layoutSlide.Shapes)
                        {
                            if (shape is Aspose.Slides.AutoShape)
                            {
                                if (((IAutoShape)shape).TextFrame != null)
                                {
                                    string text = ((IAutoShape)shape).TextFrame.Text;
                                    if (!string.IsNullOrEmpty(text))
                                    {
                                        this.SearchAndReplaceFields(ref text, commonFields);
                                        ((IAutoShape)shape).TextFrame.Text = text;
                                    }
                                }
                            }
                        }
                    }

                    // Lettura caselle di testo
                    ITextFrame[] textFrames = Aspose.Slides.Util.SlideUtil.GetAllTextFrames(ppt, true);

                    foreach (ITextFrame tf in textFrames)
                    {
                        foreach (Paragraph par in tf.Paragraphs)
                        {
                            string text = par.Text;
                            if (!string.IsNullOrEmpty(text) && text.Contains("#"))
                            {
                                this.SearchAndReplaceFields(ref text, commonFields);
                                par.Text = text;
                            }
                            #region OLD CODE
                            //foreach (Portion port in par.Portions)
                            //{
                            //    string text = port.Text;
                            //    if (!string.IsNullOrEmpty(text) && text.Contains("#"))
                            //    {
                            //        this.SearchAndReplaceFields(ref text, commonFields);
                            //        port.Text = text;
                            //    }
                            //}
                            #endregion
                        }
                    }

                    #region OLD CODE
                    //Lettura slide
                    //foreach (ISlide slide in ppt.Slides)
                    //{
                    //    // Ciclo sulle forme della slide
                    //    foreach (IShape shape in slide.Shapes)
                    //    {
                    //        // Analisi testo
                    //        if (((IAutoShape)shape).TextFrame != null)
                    //        {
                    //            string text = ((IAutoShape)shape).TextFrame.Text;
                    //            if (!string.IsNullOrEmpty(text))
                    //            {
                    //                this.SearchAndReplaceFields(ref text, commonFields);
                    //                ((IAutoShape)shape).TextFrame.Text = text;
                    //            }
                    //        }
                    //    }
                    //}
                    #endregion

                    // Salvataggio del documento
                    Aspose.Slides.Export.SaveFormat frm = new Aspose.Slides.Export.SaveFormat();
                    switch (sd.template.PATH_MODELLO_1_EXT.ToUpper())
                    {
                    case "PPT":
                    default:
                        frm = Aspose.Slides.Export.SaveFormat.Ppt;
                        break;

                    case "PPTX":
                        frm = Aspose.Slides.Export.SaveFormat.Pptx;
                        break;

                    case "PPSX":
                        frm = Aspose.Slides.Export.SaveFormat.Ppsx;
                        break;

                    case "ODP":
                        frm = Aspose.Slides.Export.SaveFormat.Odp;
                        break;
                    }

                    ppt.Save(stream, Aspose.Slides.Export.SaveFormat.Pptx);
                }

                content = stream.ToArray();
            }
            catch (Exception ex)
            {
                logger.DebugFormat("{0}\r\n{1}", ex.Message, ex.StackTrace);
                content = null;
            }
            return(content);
        }
Esempio n. 35
0
 public BuildCodeActivity()
 {
     this.license = LicenseManager.Validate(typeof(BuildCodeActivity), this);
 }
        /// <summary>
        /// Validates the license.
        /// </summary>
        /// <param name="license">The license key the user has given to be validated.</param>
        /// <returns>The validation context containing all the validation results.</returns>
        public IValidationContext ValidateLicense(string license)
        {
            Argument.IsNotNullOrWhitespace(() => license);

            var validationContext = new ValidationContext();

            Log.Info("Validating license");

            try
            {
                var licenseObject = License.Load(license);
                var failureList   = licenseObject.Validate()
                                    .Signature(_applicationIdService.ApplicationId)
                                    .AssertValidLicense().ToList();

                if (failureList.Count > 0)
                {
                    foreach (var failure in failureList)
                    {
                        var businessRuleValidationResult = BusinessRuleValidationResult.CreateErrorWithTag(failure.Message, failure.HowToResolve);
                        validationContext.Add(businessRuleValidationResult);
                    }
                }

                var licenseAttributes = licenseObject.AdditionalAttributes;
                if (licenseAttributes != null)
                {
                    foreach (var licenseAttribute in licenseAttributes.GetAll())
                    {
                        if (string.Equals(licenseAttribute.Key, LicenseElements.MachineId))
                        {
                            Log.Debug("Validating license using machine ID");

                            var machineLicenseValidationContext = _machineLicenseValidationService.Validate(licenseAttribute.Value);
                            validationContext.SynchronizeWithContext(machineLicenseValidationContext, true);

                            if (machineLicenseValidationContext.HasErrors)
                            {
                                Log.Error("The license can only run on machine with ID '{0}'", licenseAttribute.Value);
                            }
                        }

                        // TODO: add additional attribute checks here
                    }
                }

                // Also validate the xml, very important for expiration date and version
                var xmlValidationContext = ValidateXml(license);
                validationContext.SynchronizeWithContext(xmlValidationContext, true);
            }
            catch (Exception ex)
            {
                Log.Error(ex, "An error occurred while loading the license");

                validationContext.Add(BusinessRuleValidationResult.CreateError("An unknown error occurred while loading the license, please contact support"));
            }
            finally
            {
                if (validationContext.GetErrors().Count > 0)
                {
                    Log.Warning("License is not valid:");
                    Log.Indent();

                    foreach (var error in validationContext.GetErrors())
                    {
                        Log.Warning("- {0}\n{1}", error.Message, error.Tag as string);
                    }

                    Log.Unindent();
                }
                else
                {
                    Log.Info("License is valid");
                }
            }

            return(validationContext);
        }
Esempio n. 37
0
        internal static void ExportLicense(string macAddress)
        {
label_1:
            int num1 = 1923356461;

            while (true)
            {
                int     num2 = 2050214009;
                uint    num3;
                License license;
                string  licenseRoot;
                string  str;
                switch ((num3 = (uint)(num1 ^ num2)) % 14U)
                {
                case 0:
                    license.Licensee = CoreProtector.\u200F‮‌‍‬‎‍‮‬‌‮‪‭‮‌‫‭​​‌‮‎‪‪‮();
                    num1             = (int)num3 * -1537389269 ^ 930953215;
                    continue;

                case 1:
                    licenseRoot = Resources.LicenseRoot;
                    CoreProtector.\u200D‪‭‍‫‬‭‭‫‭‮‪‌​‭​‌‌‭‭‮‫‮(licenseRoot, str);
                    int num4 = !CoreProtector.\u202C‎‎‫‭‍‌‪​‭‪‬‬‎​‭‌‌‌‪‮‮‍‫‫‏‪‭‎‪‌‭‮(licenseRoot) ? 412641103 : (num4 = 1218056561);
                    int num5 = (int)num3 * -745668599;
                    num1 = num4 ^ num5;
                    continue;

                case 2:
                    license.DateRequested = DateTime.Now;
                    num1 = (int)num3 * -863090512 ^ 153358108;
                    continue;

                case 3:
                    license = new License();
                    num1    = 313527243;
                    continue;

                case 4:
                    license.Node = macAddress;
                    num1         = (int)num3 * 1793480647 ^ 1795880634;
                    continue;

                case 5:
                    license.DateExpires = CoreProtector.\u200E‏‫‏‭‮‍‏‍‬‬‌‏‬‭​‌‎‫‌‌‏‎‬‬‬‌‬‏‌‪‮(CoreProtector.COMPILE_DATE).AddDays(30.0);
                    num1 = (int)num3 * -1200663270 ^ -683511489;
                    continue;

                case 6:
                    goto label_1;

                case 7:
                    num1 = (int)num3 * -1173507156 ^ 682285796;
                    continue;

                case 8:
                    license.MachineName = CoreProtector.\u202E‌‫‪‪‌‏‌‎‍‭‎‭‪‎‮‍‪‏‪​‬‬‎‬‎‎‮();
                    num1 = (int)num3 * 924916207 ^ -1157671823;
                    continue;

                case 9:
                    num1 = (int)num3 * -524718652 ^ 25558546;
                    continue;

                case 10:
                    goto label_3;

                case 11:
                    LicenseHelper.Save(license, Path.Combine(Engine.Instance.Settings.LicenseRoot, license.FileName));
                    num1 = (int)num3 * 431591654 ^ -1277521901;
                    continue;

                case 12:
                    str  = CoreProtector.\u200E‮‍​‮‌‍‍‫‪‌‭‍‌​‭‭‎‎‮‫​‮‮(macAddress, \u003CModule\u003E.\u202A‎‪‫‪‪‏‮‬‎‏‌‌‫‬‌‍‫‌‌‌‮‫‪‮‮ <string>(1772799200U));
                    num1 = (int)num3 * 738438175 ^ 832264366;
                    continue;

                case 13:
                    CoreProtector.\u200B​‍‮‎‭‮‫‮‌​‌​‭‎‫‍‌‭‪‫‏‍‫‌‎‭​‮(licenseRoot);
                    num1 = (int)num3 * -994001036 ^ 2063126318;
                    continue;

                default:
                    goto label_16;
                }
            }
label_16:
            return;

            label_3 :;
        }
Esempio n. 38
0
        public override bool Execute(ProgramOptions programOptions, JobConfiguration jobConfiguration)
        {
            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();

            StepTiming stepTimingFunction = new StepTiming();

            stepTimingFunction.JobFileName = programOptions.OutputJobFilePath;
            stepTimingFunction.StepName    = jobConfiguration.Status.ToString();
            stepTimingFunction.StepID      = (int)jobConfiguration.Status;
            stepTimingFunction.StartTime   = DateTime.Now;
            stepTimingFunction.NumEntities = jobConfiguration.Target.Count;

            this.DisplayJobStepStartingStatus(jobConfiguration);

            FilePathMap = new FilePathMap(programOptions, jobConfiguration);

            try
            {
                if (this.ShouldExecute(programOptions, jobConfiguration) == false)
                {
                    return(true);
                }

                bool reportFolderCleaned = false;

                // Process each Controller once
                int i           = 0;
                var controllers = jobConfiguration.Target.GroupBy(t => t.Controller);
                foreach (var controllerGroup in controllers)
                {
                    Stopwatch stopWatchTarget = new Stopwatch();
                    stopWatchTarget.Start();

                    JobTarget jobTarget = controllerGroup.ToList()[0];

                    StepTiming stepTimingTarget = new StepTiming();
                    stepTimingTarget.Controller      = jobTarget.Controller;
                    stepTimingTarget.ApplicationName = jobTarget.Application;
                    stepTimingTarget.ApplicationID   = jobTarget.ApplicationID;
                    stepTimingTarget.JobFileName     = programOptions.OutputJobFilePath;
                    stepTimingTarget.StepName        = jobConfiguration.Status.ToString();
                    stepTimingTarget.StepID          = (int)jobConfiguration.Status;
                    stepTimingTarget.StartTime       = DateTime.Now;

                    stepTimingTarget.NumEntities = 0;

                    try
                    {
                        this.DisplayJobTargetStartingStatus(jobConfiguration, jobTarget, i + 1);

                        #region Prepare time range

                        long   fromTimeUnix            = UnixTimeHelper.ConvertToUnixTimestamp(jobConfiguration.Input.TimeRange.From);
                        long   toTimeUnix              = UnixTimeHelper.ConvertToUnixTimestamp(jobConfiguration.Input.TimeRange.To);
                        int    differenceInMinutes     = (int)(jobConfiguration.Input.TimeRange.To - jobConfiguration.Input.TimeRange.From).Duration().TotalMinutes;
                        string DEEPLINK_THIS_TIMERANGE = String.Format(DEEPLINK_TIMERANGE_BETWEEN_TIMES, toTimeUnix, fromTimeUnix, differenceInMinutes);

                        #endregion

                        #region Account Summary

                        loggerConsole.Info("Account Summary");

                        LicenseAccountSummary licenseAccountSummary = new LicenseAccountSummary();

                        JObject accountSummaryContainerObject = FileIOHelper.LoadJObjectFromFile(FilePathMap.LicenseAccountDataFilePath(jobTarget));
                        if (accountSummaryContainerObject != null && isTokenPropertyNull(accountSummaryContainerObject, "account") == false)
                        {
                            JObject accountSummaryLicenseObject = (JObject)accountSummaryContainerObject["account"];

                            licenseAccountSummary.Controller = jobTarget.Controller;

                            licenseAccountSummary.AccountID         = getLongValueFromJToken(accountSummaryLicenseObject, "id");
                            licenseAccountSummary.AccountName       = getStringValueFromJToken(accountSummaryLicenseObject, "name");
                            licenseAccountSummary.AccountNameGlobal = getStringValueFromJToken(accountSummaryLicenseObject, "globalAccountName");
                            licenseAccountSummary.AccountNameEUM    = getStringValueFromJToken(accountSummaryLicenseObject, "eumAccountName");

                            licenseAccountSummary.AccessKey1    = getStringValueFromJToken(accountSummaryLicenseObject, "accessKey");
                            licenseAccountSummary.AccessKey2    = getStringValueFromJToken(accountSummaryLicenseObject, "key");
                            licenseAccountSummary.LicenseKeyEUM = getStringValueFromJToken(accountSummaryLicenseObject, "eumCloudLicenseKey");
                            licenseAccountSummary.ServiceKeyES  = getStringValueFromJToken(accountSummaryLicenseObject, "eumEventServiceKey");

                            licenseAccountSummary.ExpirationDate = UnixTimeHelper.ConvertFromUnixTimestamp(getLongValueFromJToken(accountSummaryLicenseObject, "expirationDate"));

                            licenseAccountSummary.LicenseLink = String.Format(DEEPLINK_LICENSE, licenseAccountSummary.Controller, DEEPLINK_THIS_TIMERANGE);

                            List <LicenseAccountSummary> licenseAccountSummaryList = new List <LicenseAccountSummary>(1);
                            licenseAccountSummaryList.Add(licenseAccountSummary);
                            FileIOHelper.WriteListToCSVFile(licenseAccountSummaryList, new LicenseAccountSummaryReportMap(), FilePathMap.LicenseAccountIndexFilePath(jobTarget));

                            stepTimingTarget.NumEntities = stepTimingTarget.NumEntities + licenseAccountSummaryList.Count;
                        }

                        #endregion

                        #region Account Level License Entitlements and Usage

                        loggerConsole.Info("Account License Summary and Usage");

                        List <License> licensesList = new List <License>(24);

                        // Typically there are 12 values per hour, if we extracted every 5 minute things
                        List <LicenseValue> licenseValuesGlobalList = new List <LicenseValue>(jobConfiguration.Input.HourlyTimeRanges.Count * 12 * licensesList.Count);

                        JObject licenseModulesContainer = FileIOHelper.LoadJObjectFromFile(FilePathMap.LicenseModulesDataFilePath(jobTarget));
                        if (licenseModulesContainer != null &&
                            isTokenPropertyNull(licenseModulesContainer, "modules") == false)
                        {
                            JArray licenseModulesArray = (JArray)licenseModulesContainer["modules"];
                            foreach (JObject licenseModuleObject in licenseModulesArray)
                            {
                                string licenseModuleName = getStringValueFromJToken(licenseModuleObject, "name");

                                License license = new License();

                                license.Controller  = jobTarget.Controller;
                                license.AccountID   = licenseAccountSummary.AccountID;
                                license.AccountName = licenseAccountSummary.AccountName;

                                // Duration
                                license.Duration = (int)(jobConfiguration.Input.TimeRange.To - jobConfiguration.Input.TimeRange.From).Duration().TotalMinutes;
                                license.From     = jobConfiguration.Input.TimeRange.From.ToLocalTime();
                                license.To       = jobConfiguration.Input.TimeRange.To.ToLocalTime();
                                license.FromUtc  = jobConfiguration.Input.TimeRange.From;
                                license.ToUtc    = jobConfiguration.Input.TimeRange.To;

                                license.AgentType = licenseModuleName;

                                JObject licenseModulePropertiesContainer = FileIOHelper.LoadJObjectFromFile(FilePathMap.LicenseModulePropertiesDataFilePath(jobTarget, licenseModuleName));
                                if (licenseModulePropertiesContainer != null &&
                                    isTokenPropertyNull(licenseModulePropertiesContainer, "properties") == false)
                                {
                                    foreach (JObject licensePropertyObject in licenseModulePropertiesContainer["properties"])
                                    {
                                        string valueOfProperty = getStringValueFromJToken(licensePropertyObject, "value");
                                        switch (getStringValueFromJToken(licensePropertyObject, "name"))
                                        {
                                        case "expiry-date":
                                            long expiryDateLong = 0;
                                            if (long.TryParse(valueOfProperty, out expiryDateLong) == true)
                                            {
                                                license.ExpirationDate = UnixTimeHelper.ConvertFromUnixTimestamp(expiryDateLong);
                                            }
                                            break;

                                        case "licensing-model":
                                            license.Model = valueOfProperty;
                                            break;

                                        case "edition":
                                            license.Edition = valueOfProperty;
                                            break;

                                        case "number-of-provisioned-licenses":
                                            long numberOfLicensesLong = 0;
                                            if (long.TryParse(valueOfProperty, out numberOfLicensesLong) == true)
                                            {
                                                license.Provisioned = numberOfLicensesLong;
                                            }
                                            break;

                                        case "maximum-allowed-licenses":
                                            long maximumNumberOfLicensesLong = 0;
                                            if (long.TryParse(valueOfProperty, out maximumNumberOfLicensesLong) == true)
                                            {
                                                license.MaximumAllowed = maximumNumberOfLicensesLong;
                                            }
                                            break;

                                        case "data-retention-period":
                                            int dataRetentionPeriodInt = 0;
                                            if (int.TryParse(valueOfProperty, out dataRetentionPeriodInt) == true)
                                            {
                                                license.Retention = dataRetentionPeriodInt;
                                            }
                                            break;

                                        default:
                                            break;
                                        }
                                    }
                                }

                                List <LicenseValue> licenseValuesList = new List <LicenseValue>(jobConfiguration.Input.HourlyTimeRanges.Count * 12);

                                JObject licenseModuleUsagesContainer = FileIOHelper.LoadJObjectFromFile(FilePathMap.LicenseModuleUsagesDataFilePath(jobTarget, licenseModuleName));
                                if (licenseModuleUsagesContainer != null &&
                                    isTokenPropertyNull(licenseModuleUsagesContainer, "usages") == false)
                                {
                                    foreach (JObject licenseUsageObject in licenseModuleUsagesContainer["usages"])
                                    {
                                        LicenseValue licenseValue = new LicenseValue();

                                        licenseValue.Controller  = license.Controller;
                                        licenseValue.AccountName = license.AccountName;
                                        licenseValue.AccountID   = license.AccountID;

                                        licenseValue.AgentType = license.AgentType;

                                        licenseValue.RuleName = "Account";

                                        licenseValue.LicenseEventTimeUtc = UnixTimeHelper.ConvertFromUnixTimestamp(getLongValueFromJToken(licenseUsageObject, "createdOn"));
                                        licenseValue.LicenseEventTime    = licenseValue.LicenseEventTimeUtc.ToLocalTime();

                                        licenseValue.Min     = getLongValueFromJToken(licenseUsageObject, "minUnitsUsed");
                                        licenseValue.Max     = getLongValueFromJToken(licenseUsageObject, "maxUnitsUsed");
                                        licenseValue.Average = getLongValueFromJToken(licenseUsageObject, "avgUnitsUsed");
                                        licenseValue.Total   = getLongValueFromJToken(licenseUsageObject, "totalUnitsUsed");
                                        licenseValue.Samples = getLongValueFromJToken(licenseUsageObject, "sampleCount");

                                        licenseValuesList.Add(licenseValue);
                                    }
                                }

                                // Do the counts and averages from per hour consumption to the total line
                                if (licenseValuesList.Count > 0)
                                {
                                    license.Average = (long)Math.Round((double)((double)licenseValuesList.Sum(mv => mv.Average) / (double)licenseValuesList.Count), 0);
                                    license.Min     = licenseValuesList.Min(l => l.Min);
                                    license.Max     = licenseValuesList.Max(l => l.Max);
                                }

                                licensesList.Add(license);
                                licenseValuesGlobalList.AddRange(licenseValuesList);
                            }
                        }

                        stepTimingTarget.NumEntities = stepTimingTarget.NumEntities + licensesList.Count;

                        licensesList = licensesList.OrderBy(l => l.AgentType).ToList();
                        FileIOHelper.WriteListToCSVFile(licensesList, new LicenseReportMap(), FilePathMap.LicensesIndexFilePath(jobTarget));

                        FileIOHelper.WriteListToCSVFile(licenseValuesGlobalList, new LicenseValueReportMap(), FilePathMap.LicenseUsageAccountIndexFilePath(jobTarget));

                        #endregion

                        #region License Rules

                        loggerConsole.Info("License Rules");

                        #region Preload the application and machine mapping

                        Dictionary <string, string> applicationsUsedByRules = null;
                        Dictionary <string, string> simMachinesUsedByRules  = null;

                        JArray licenseApplicationsReferenceArray = FileIOHelper.LoadJArrayFromFile(FilePathMap.LicenseApplicationsDataFilePath(jobTarget));
                        JArray licenseSIMMachinesReferenceArray  = FileIOHelper.LoadJArrayFromFile(FilePathMap.LicenseSIMMachinesDataFilePath(jobTarget));

                        if (licenseApplicationsReferenceArray == null)
                        {
                            applicationsUsedByRules = new Dictionary <string, string>(0);
                        }
                        else
                        {
                            applicationsUsedByRules = new Dictionary <string, string>(licenseApplicationsReferenceArray.Count);
                            foreach (JObject applicationObject in licenseApplicationsReferenceArray)
                            {
                                applicationsUsedByRules.Add(getStringValueFromJToken(applicationObject["objectReference"], "id"), getStringValueFromJToken(applicationObject, "name"));
                            }
                        }

                        if (licenseSIMMachinesReferenceArray == null)
                        {
                            simMachinesUsedByRules = new Dictionary <string, string>(0);
                        }
                        else
                        {
                            simMachinesUsedByRules = new Dictionary <string, string>(licenseSIMMachinesReferenceArray.Count);
                            foreach (JObject machineObject in licenseSIMMachinesReferenceArray)
                            {
                                simMachinesUsedByRules.Add(getStringValueFromJToken(machineObject["objectReference"], "id"), getStringValueFromJToken(machineObject, "name"));
                            }
                        }

                        List <ControllerApplication> controllerApplicationsList = FileIOHelper.ReadListFromCSVFile <ControllerApplication>(FilePathMap.ControllerApplicationsIndexFilePath(jobTarget), new ControllerApplicationReportMap());

                        #endregion

                        List <LicenseRule>      licenseRulesList      = new List <LicenseRule>(10);
                        List <LicenseRuleScope> licenseRuleScopesList = new List <LicenseRuleScope>(100);

                        JArray licenseRulesArray = FileIOHelper.LoadJArrayFromFile(FilePathMap.LicenseRulesDataFilePath(jobTarget));
                        if (licenseRulesArray != null)
                        {
                            foreach (JObject licenseRuleObject in licenseRulesArray)
                            {
                                string ruleID   = getStringValueFromJToken(licenseRuleObject, "id");
                                string ruleName = getStringValueFromJToken(licenseRuleObject, "name");

                                JObject licenseRuleDetailsObject = FileIOHelper.LoadJObjectFromFile(FilePathMap.LicenseRuleConfigurationDataFilePath(jobTarget, ruleName, ruleID));
                                if (licenseRuleDetailsObject != null)
                                {
                                    LicenseRule licenseRuleTemplate = new LicenseRule();

                                    licenseRuleTemplate.Controller  = jobTarget.Controller;
                                    licenseRuleTemplate.AccountID   = licenseAccountSummary.AccountID;
                                    licenseRuleTemplate.AccountName = licenseAccountSummary.AccountName;

                                    // Duration
                                    licenseRuleTemplate.Duration = (int)(jobConfiguration.Input.TimeRange.To - jobConfiguration.Input.TimeRange.From).Duration().TotalMinutes;
                                    licenseRuleTemplate.From     = jobConfiguration.Input.TimeRange.From.ToLocalTime();
                                    licenseRuleTemplate.To       = jobConfiguration.Input.TimeRange.To.ToLocalTime();
                                    licenseRuleTemplate.FromUtc  = jobConfiguration.Input.TimeRange.From;
                                    licenseRuleTemplate.ToUtc    = jobConfiguration.Input.TimeRange.To;

                                    licenseRuleTemplate.RuleName = getStringValueFromJToken(licenseRuleObject, "name");
                                    licenseRuleTemplate.RuleID   = getStringValueFromJToken(licenseRuleObject, "id");

                                    licenseRuleTemplate.AccessKey = getStringValueFromJToken(licenseRuleObject, "access_key");

                                    licenseRuleTemplate.RuleLicenses = getLongValueFromJToken(licenseRuleObject, "total_licenses");
                                    licenseRuleTemplate.RulePeak     = getLongValueFromJToken(licenseRuleObject, "peak_usage");

                                    if (isTokenPropertyNull(licenseRuleDetailsObject, "constraints") == false)
                                    {
                                        JArray licenseRuleConstraintsArray = (JArray)licenseRuleDetailsObject["constraints"];
                                        foreach (JObject licenseConstraintObject in licenseRuleConstraintsArray)
                                        {
                                            LicenseRuleScope licenseRuleScope = new LicenseRuleScope();

                                            licenseRuleScope.Controller  = licenseRuleTemplate.Controller;
                                            licenseRuleScope.AccountID   = licenseRuleTemplate.AccountID;
                                            licenseRuleScope.AccountName = licenseRuleTemplate.AccountName;

                                            licenseRuleScope.RuleName = licenseRuleTemplate.RuleName;
                                            licenseRuleScope.RuleID   = licenseRuleTemplate.RuleID;

                                            licenseRuleScope.ScopeSelector = getStringValueFromJToken(licenseConstraintObject, "constraint_type");

                                            string scopeType = getStringValueFromJToken(licenseConstraintObject, "entity_type_id");
                                            if (scopeType == "com.appdynamics.modules.apm.topology.impl.persistenceapi.model.ApplicationEntity")
                                            {
                                                licenseRuleScope.EntityType = "Application";
                                            }
                                            else if (scopeType == "com.appdynamics.modules.apm.topology.impl.persistenceapi.model.MachineEntity")
                                            {
                                                licenseRuleScope.EntityType = "Machine";
                                            }

                                            if (licenseRuleScope.ScopeSelector == "ALLOW_ALL")
                                            {
                                                licenseRuleScope.MatchType = "EQUALS";
                                                if (scopeType == "com.appdynamics.modules.apm.topology.impl.persistenceapi.model.ApplicationEntity")
                                                {
                                                    licenseRuleScope.EntityName = "[Any Application]";
                                                    licenseRuleTemplate.NumApplications++;
                                                }
                                                else if (scopeType == "com.appdynamics.modules.apm.topology.impl.persistenceapi.model.MachineEntity")
                                                {
                                                    licenseRuleScope.EntityName = "[Any Machine]";
                                                    licenseRuleTemplate.NumServers++;
                                                }
                                                licenseRuleScopesList.Add(licenseRuleScope);
                                            }
                                            else if (isTokenPropertyNull(licenseConstraintObject, "match_conditions") == false)
                                            {
                                                JArray licenseRuleMatcheConditionsArray = (JArray)licenseConstraintObject["match_conditions"];

                                                foreach (JObject licenseRuleMatchConditionObject in licenseRuleMatcheConditionsArray)
                                                {
                                                    LicenseRuleScope licenseRuleScopeMatchCondition = licenseRuleScope.Clone();

                                                    licenseRuleScopeMatchCondition.MatchType = getStringValueFromJToken(licenseRuleMatchConditionObject, "match_type");
                                                    if (licenseRuleScopeMatchCondition.MatchType == "EQUALS" &&
                                                        getStringValueFromJToken(licenseRuleMatchConditionObject, "attribute_type") == "ID")
                                                    {
                                                        string applicationID = getStringValueFromJToken(licenseRuleMatchConditionObject, "match_string");

                                                        if (scopeType == "com.appdynamics.modules.apm.topology.impl.persistenceapi.model.ApplicationEntity")
                                                        {
                                                            if (applicationsUsedByRules.ContainsKey(applicationID) == true &&
                                                                controllerApplicationsList != null)
                                                            {
                                                                ControllerApplication controllerApplication = controllerApplicationsList.Where(a => a.ApplicationName == applicationsUsedByRules[applicationID]).FirstOrDefault();
                                                                if (controllerApplication != null)
                                                                {
                                                                    licenseRuleScopeMatchCondition.EntityName = controllerApplication.ApplicationName;
                                                                    licenseRuleScopeMatchCondition.EntityType = controllerApplication.Type;
                                                                    licenseRuleScopeMatchCondition.EntityID   = controllerApplication.ApplicationID;
                                                                }
                                                            }
                                                            licenseRuleTemplate.NumApplications++;
                                                        }
                                                        else if (scopeType == "com.appdynamics.modules.apm.topology.impl.persistenceapi.model.MachineEntity")
                                                        {
                                                            if (simMachinesUsedByRules.ContainsKey(applicationID) == true)
                                                            {
                                                                licenseRuleScopeMatchCondition.EntityName = simMachinesUsedByRules[applicationID];
                                                            }
                                                            licenseRuleTemplate.NumServers++;
                                                        }
                                                    }
                                                    else
                                                    {
                                                        licenseRuleScopeMatchCondition.EntityName = getStringValueFromJToken(licenseRuleMatchConditionObject, "match_string");
                                                        licenseRuleScopeMatchCondition.EntityID   = -1;
                                                        if (scopeType == "com.appdynamics.modules.apm.topology.impl.persistenceapi.model.ApplicationEntity")
                                                        {
                                                            licenseRuleTemplate.NumApplications++;
                                                        }
                                                        else if (scopeType == "com.appdynamics.modules.apm.topology.impl.persistenceapi.model.MachineEntity")
                                                        {
                                                            licenseRuleTemplate.NumServers++;
                                                        }
                                                    }

                                                    licenseRuleScopesList.Add(licenseRuleScopeMatchCondition);
                                                }
                                            }
                                        }
                                    }

                                    if (isTokenPropertyNull(licenseRuleDetailsObject, "entitlements") == false)
                                    {
                                        JArray licenseRuleEntitlementsArray = (JArray)licenseRuleDetailsObject["entitlements"];
                                        foreach (JObject licenseEntitlementObject in licenseRuleEntitlementsArray)
                                        {
                                            LicenseRule licenseRule = licenseRuleTemplate.Clone();

                                            licenseRule.Licenses = getLongValueFromJToken(licenseEntitlementObject, "number_of_licenses");

                                            licenseRule.AgentType = getStringValueFromJToken(licenseEntitlementObject, "license_module_type");

                                            licenseRulesList.Add(licenseRule);
                                        }
                                    }
                                }
                            }

                            licenseRulesList = licenseRulesList.OrderBy(l => l.RuleName).ThenBy(l => l.AgentType).ToList();
                            FileIOHelper.WriteListToCSVFile(licenseRulesList, new LicenseRuleReportMap(), FilePathMap.LicenseRulesIndexFilePath(jobTarget));

                            licenseRuleScopesList = licenseRuleScopesList.OrderBy(l => l.RuleName).ThenBy(l => l.ScopeSelector).ThenBy(l => l.EntityType).ThenBy(l => l.EntityName).ToList();
                            FileIOHelper.WriteListToCSVFile(licenseRuleScopesList, new LicenseRuleScopeReportMap(), FilePathMap.LicenseRuleScopesIndexFilePath(jobTarget));
                        }

                        #endregion

                        #region License Rule consumption details

                        loggerConsole.Info("Rules License Consumption");

                        // Typically there are 12 values per hour
                        // Assume there will be 16 different license types
                        List <LicenseValue> licenseValuesRulesList = new List <LicenseValue>(jobConfiguration.Input.HourlyTimeRanges.Count * 12 * 16 * licenseRulesList.Count);

                        foreach (LicenseRule licenseRule in licenseRulesList)
                        {
                            JObject licenseValuesForRuleContainerObject = FileIOHelper.LoadJObjectFromFile(FilePathMap.LicenseRuleUsageDataFilePath(jobTarget, licenseRule.RuleName, licenseRule.RuleID));

                            if (licenseValuesForRuleContainerObject != null)
                            {
                                if (isTokenPropertyNull(licenseValuesForRuleContainerObject, "apmStackGraphViewData") == false)
                                {
                                    // Parse the APM results first
                                    JArray licenseValuesForRuleAPMContainerArray = (JArray)licenseValuesForRuleContainerObject["apmStackGraphViewData"];
                                    if (licenseValuesForRuleAPMContainerArray != null)
                                    {
                                        foreach (JObject licenseValuesContainerObject in licenseValuesForRuleAPMContainerArray)
                                        {
                                            string licenseType = getStringValueFromJToken(licenseValuesContainerObject, "licenseModuleType");

                                            // If we have the license looked up, look through the values
                                            if (licenseType != String.Empty &&
                                                isTokenPropertyNull(licenseValuesContainerObject, "graphPoints") == false)
                                            {
                                                // Looks like [[ 1555484400000, 843 ], [ 1555488000000, 843 ]]
                                                JArray licenseValuesAPMArray = (JArray)licenseValuesContainerObject["graphPoints"];

                                                List <LicenseValue> licenseValuesList = parseLicenseValuesArray(licenseValuesAPMArray, licenseRule, licenseType);
                                                if (licenseValuesList != null)
                                                {
                                                    licenseValuesRulesList.AddRange(licenseValuesList);
                                                }
                                            }
                                        }
                                    }
                                }
                                if (isTokenPropertyNull(licenseValuesForRuleContainerObject, "nonApmModuleDetailViewData") == false)
                                {
                                    // Parse the non-APM results second
                                    JArray licenseValuesForRuleNonAPMContainerArray = (JArray)licenseValuesForRuleContainerObject["nonApmModuleDetailViewData"];
                                    if (licenseValuesForRuleNonAPMContainerArray != null)
                                    {
                                        foreach (JObject licenseValuesContainerObject in licenseValuesForRuleNonAPMContainerArray)
                                        {
                                            string licenseType = getStringValueFromJToken(licenseValuesContainerObject, "licenseModuleType");

                                            // If we have the license looked up, look through the values
                                            if (licenseType != String.Empty &&
                                                isTokenPropertyNull(licenseValuesContainerObject, "graphPoints") == false)
                                            {
                                                // Looks like [[ 1555484400000, 843 ], [ 1555488000000, 843 ]]
                                                JArray licenseValuesAPMArray = (JArray)licenseValuesContainerObject["graphPoints"];

                                                List <LicenseValue> licenseValuesList = parseLicenseValuesArray(licenseValuesAPMArray, licenseRule, licenseType);
                                                if (licenseValuesList != null)
                                                {
                                                    licenseValuesRulesList.AddRange(licenseValuesList);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        FileIOHelper.WriteListToCSVFile(licenseValuesRulesList, new LicenseRuleValueReportMap(), FilePathMap.LicenseUsageRulesIndexFilePath(jobTarget));

                        #endregion

                        #region Combine All for Report CSV

                        // If it is the first one, clear out the combined folder
                        if (reportFolderCleaned == false)
                        {
                            FileIOHelper.DeleteFolder(FilePathMap.ControllerLicensesReportFolderPath());
                            Thread.Sleep(1000);
                            FileIOHelper.CreateFolder(FilePathMap.ControllerLicensesReportFolderPath());
                            reportFolderCleaned = true;
                        }

                        // Append all the individual report files into one
                        if (File.Exists(FilePathMap.LicenseAccountIndexFilePath(jobTarget)) == true && new FileInfo(FilePathMap.LicenseAccountIndexFilePath(jobTarget)).Length > 0)
                        {
                            FileIOHelper.AppendTwoCSVFiles(FilePathMap.LicenseAccountReportFilePath(), FilePathMap.LicenseAccountIndexFilePath(jobTarget));
                        }
                        if (File.Exists(FilePathMap.LicensesIndexFilePath(jobTarget)) == true && new FileInfo(FilePathMap.LicensesIndexFilePath(jobTarget)).Length > 0)
                        {
                            FileIOHelper.AppendTwoCSVFiles(FilePathMap.LicensesReportFilePath(), FilePathMap.LicensesIndexFilePath(jobTarget));
                        }
                        if (File.Exists(FilePathMap.LicenseRulesIndexFilePath(jobTarget)) == true && new FileInfo(FilePathMap.LicenseRulesIndexFilePath(jobTarget)).Length > 0)
                        {
                            FileIOHelper.AppendTwoCSVFiles(FilePathMap.LicenseRulesReportFilePath(), FilePathMap.LicenseRulesIndexFilePath(jobTarget));
                        }
                        if (File.Exists(FilePathMap.LicenseUsageAccountIndexFilePath(jobTarget)) == true && new FileInfo(FilePathMap.LicenseUsageAccountIndexFilePath(jobTarget)).Length > 0)
                        {
                            FileIOHelper.AppendTwoCSVFiles(FilePathMap.LicenseUsageAccountReportFilePath(), FilePathMap.LicenseUsageAccountIndexFilePath(jobTarget));
                        }
                        if (File.Exists(FilePathMap.LicenseUsageRulesIndexFilePath(jobTarget)) == true && new FileInfo(FilePathMap.LicenseUsageRulesIndexFilePath(jobTarget)).Length > 0)
                        {
                            FileIOHelper.AppendTwoCSVFiles(FilePathMap.LicenseUsageRulesReportFilePath(), FilePathMap.LicenseUsageRulesIndexFilePath(jobTarget));
                        }
                        if (File.Exists(FilePathMap.LicenseRuleScopesIndexFilePath(jobTarget)) == true && new FileInfo(FilePathMap.LicenseRuleScopesIndexFilePath(jobTarget)).Length > 0)
                        {
                            FileIOHelper.AppendTwoCSVFiles(FilePathMap.LicenseRuleScopesReportFilePath(), FilePathMap.LicenseRuleScopesIndexFilePath(jobTarget));
                        }

                        #endregion
                    }
                    catch (Exception ex)
                    {
                        logger.Warn(ex);
                        loggerConsole.Warn(ex);

                        return(false);
                    }
                    finally
                    {
                        stopWatchTarget.Stop();

                        this.DisplayJobTargetEndedStatus(jobConfiguration, jobTarget, i + 1, stopWatchTarget);

                        stepTimingTarget.EndTime    = DateTime.Now;
                        stepTimingTarget.Duration   = stopWatchTarget.Elapsed;
                        stepTimingTarget.DurationMS = stopWatchTarget.ElapsedMilliseconds;

                        List <StepTiming> stepTimings = new List <StepTiming>(1);
                        stepTimings.Add(stepTimingTarget);
                        FileIOHelper.WriteListToCSVFile(stepTimings, new StepTimingReportMap(), FilePathMap.StepTimingReportFilePath(), true);
                    }

                    i++;
                }

                return(true);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                loggerConsole.Error(ex);

                return(false);
            }
            finally
            {
                stopWatch.Stop();

                this.DisplayJobStepEndedStatus(jobConfiguration, stopWatch);

                stepTimingFunction.EndTime    = DateTime.Now;
                stepTimingFunction.Duration   = stopWatch.Elapsed;
                stepTimingFunction.DurationMS = stopWatch.ElapsedMilliseconds;

                List <StepTiming> stepTimings = new List <StepTiming>(1);
                stepTimings.Add(stepTimingFunction);
                FileIOHelper.WriteListToCSVFile(stepTimings, new StepTimingReportMap(), FilePathMap.StepTimingReportFilePath(), true);
            }
        }
Esempio n. 39
0
 /// <summary>
 /// Deletes the specified License.
 /// </summary>
 /// <param name="entity">The entity.</param>
 public void Delete(License entity)
 {
     factory.Delete(entity.ObjectValue);
 }
        /// <summary>
        /// Perform licence checking actions.
        /// </summary>
        /// <param name="ribbon">Ribbon control reference.</param>
        protected void PerformLicenceChecking(KryptonRibbon ribbon)
        {
            // Define the encryted licence information
            EncryptedLicenseProvider.SetParameters(_licenseParameters);

            // If an error has already been shown, then no need to test license again
            bool validated = _usageShown;

            if (!validated)
            {
                // Is there a valid license registered?
                License license = null;
                validated = LicenseManager.IsValid(typeof(KryptonRibbon), ribbon, out license);

                // Valid license is not enough!
                if (validated)
                {
                    validated = false;
                    EncryptedLicense encryptedLicense = license as EncryptedLicense;

                    string[] productInfo = encryptedLicense.ProductInfo.Split(',');

                    // Must contain two fields separated by a comma
                    if (productInfo.Length == 2)
                    {
                        // Both fields must not be empty
                        if (!string.IsNullOrEmpty(productInfo[0]) &&
                            !string.IsNullOrEmpty(productInfo[1]))
                        {
                            // Product code must be ...
                            //    'S' = Krypton Suite
                            // And version number...
                            //    '400'
                            validated = (productInfo[1].Equals("400")) && (productInfo[0][0] == 'S');
                        }
                    }
                }
            }

            // If we need to indicate the invalid licensing state...
            if (!validated)
            {
                // Get hold of the assembly version number
                Version thisVersion = Assembly.GetExecutingAssembly().GetName().Version;

                // We want a unique 30 day evaluation period for each major/minor version
                EvaluationMonitor monitor = new EvaluationMonitor(_monitorId + thisVersion.Major.ToString() + thisVersion.Minor.ToString());

                // If the first time we have failed to get the licence or
                // the 30 days evaluation period has expired or the component
                // has been created over a 3000 times then...
                if ((monitor.UsageCount == 0) ||
                    (monitor.UsageCount > 3000) ||
                    (monitor.DaysInUse > 30))
                {
                    // At runtime show a NAG screen to prevent unauthorized use of the control
                    if (LicenseManager.CurrentContext.UsageMode == LicenseUsageMode.Runtime)
                    {
                        MessageBox.Show("This application was created using an unlicensed version of\n" +
                                        "the Krypton Suite control from Component Factory Pty Ltd.\n\n" +
                                        "You must contact your software supplier in order to resolve\n" +
                                        "the licencing issue.",
                                        "Unlicensed Application",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                    }
                    else
                    {
                        LicenseInstallForm form = new LicenseInstallForm();
                        form.ShowDialog(typeof(KryptonRibbon));
                    }
                }
            }

            // No need to perform check check more than once
            _usageShown = true;
        }
Esempio n. 41
0
        public PdfFields()
        {
            var license = new License();

            license.SetLicense("Aspose.Pdf.Lic");
        }
 public Task OnLicenseSelected(License license)
 => _navigationService.NavigateTo <LicenseDetailViewModel>(license.Path);
 /// <summary>
 /// Constructs a NorthwindLicense based on the super-class license returned from DotNetLicense.LicenseManager
 /// </summary>
 /// <param name="baseLicense"></param>
 public NorthwindLicense(License baseLicense) : base(baseLicense.ToXml())
 {
 }
Esempio n. 44
0
        private static List <LicenseValue> parseLicenseValuesArray(JArray licenseValuesArray, License thisLicense)
        {
            List <LicenseValue> licenseValuesList = new List <LicenseValue>(licenseValuesArray.Count);

            foreach (JToken licenseValueToken in licenseValuesArray)
            {
                try
                {
                    JArray licenseValueArray = (JArray)licenseValueToken;

                    if (licenseValueArray.Count == 2)
                    {
                        LicenseValue licenseValue = new LicenseValue();

                        licenseValue.Controller  = thisLicense.Controller;
                        licenseValue.AccountName = thisLicense.AccountName;
                        licenseValue.AccountID   = thisLicense.AccountID;

                        licenseValue.RuleName = "Account";

                        licenseValue.AgentType = thisLicense.AgentType;

                        licenseValue.LicenseEventTimeUtc = UnixTimeHelper.ConvertFromUnixTimestamp((long)licenseValueArray[0]);
                        licenseValue.LicenseEventTime    = licenseValue.LicenseEventTimeUtc.ToLocalTime();

                        if (isTokenNull(licenseValueArray[1]) == false)
                        {
                            licenseValue.Average = (long)licenseValueArray[1];
                        }

                        licenseValuesList.Add(licenseValue);
                    }
                }
                catch { }
            }

            return(licenseValuesList);
        }
Esempio n. 45
0
        public Declaration Add(Declaration item, LicensedActivityType license_activity_type, LegalFormType legal_form_type, Company company, License license)
        {
            if (item.ActualAddrStr == null)
            {
                item.ActualAddrStr = "";
            }
            if (item.AddressForDocument == null)
            {
                item.AddressForDocument = "";
            }
            if (item.BanksName == null)
            {
                item.BanksName = "";
            }
            if (item.CheckingAccount == null)
            {
                item.CheckingAccount = "";
            }
            if (item.Email == null)
            {
                item.Email = "";
            }
            if (item.Fax == null)
            {
                item.Fax = "";
            }
            if (item.FullNameCompany == null)
            {
                item.FullNameCompany = "";
            }
            if (item.INN == null)
            {
                item.INN = "";
            }
            if (item.KPP == null)
            {
                item.KPP = "";
            }
            if (item.OGRN == null)
            {
                item.OGRN = "";
            }
            if (item.OtherReason == null)
            {
                item.OtherReason = "";
            }
            if (item.Phone == null)
            {
                item.Phone = "";
            }
            if (item.PostalAddrStr == null)
            {
                item.PostalAddrStr = "";
            }
            if (item.PostalCode == null)
            {
                item.PostalCode = "";
            }
            if (item.ShortNameCompany == null)
            {
                item.ShortNameCompany = "";
            }
            if (item.RegNomAll == null)
            {
                item.RegNomAll = "";
            }
            if (item.MasterName == null)
            {
                item.MasterName = "";
            }
            if (item.Comm == null)
            {
                item.Comm = "";
            }
            if (item.LicenseFormNom == null)
            {
                item.LicenseFormNom = "";
            }
            if (item.LicenseNom == null)
            {
                item.LicenseNom = "";
            }
            if (item.LicenseNomOfBook == null)
            {
                item.LicenseNomOfBook = "";
            }
            if (item.ActualAddrAddon == null)
            {
                item.ActualAddrAddon = "";
            }
            if (item.PostalAddrAddon == null)
            {
                item.PostalAddrAddon = "";
            }
            if (item.FSRARActualAddr == null)
            {
                item.FSRARActualAddr = "";
            }
            if (item.FSRARPostalAddr == null)
            {
                item.FSRARPostalAddr = "";
            }
            if (item.SmevId == null)
            {
                item.SmevId = "";
            }
            if (item.NameCompany == null)
            {
                item.NameCompany = "";
            }
            if (item.VakeelName == null)
            {
                item.VakeelName = "";
            }

            if (item.Id == 0)
            {
                item.IsDeleted       = null;
                item.DateTimeCreated = DateTime.Now;
                item.CreatorName     = UserDB == null ? "System" : UserDB.FIO;
                context.DeclarationSet.Add(item);
                license_activity_type.LinkDeclaration(item, LogHelper);
                legal_form_type.LinkDeclaration(item, LogHelper);
                if (company != null)
                {
                    company.LinkDeclaration(item, LogHelper);
                }
                if (license != null)
                {
                    license.LinkDeclaration(item, LogHelper);
                }
                LogHelper.Log(TryCreateRecord.Declaration, new SerializedEFObject(item));
                return(item);
            }
            else
            {
                Declaration old = context.DeclarationSet.First(x => x.Id == item.Id);
                if (old.CountOfYears != item.CountOfYears)
                {
                    LogHelper.Log(UpdateRecord.Declaration, item.Id, "Срок лицензии", old.CountOfYears.ToString(), item.CountOfYears.ToString());
                    old.CountOfYears = item.CountOfYears;
                }
                if (old.DateDeclaration != item.DateDeclaration)
                {
                    LogHelper.Log(UpdateRecord.Declaration, item.Id, "Дата заявления", old.DateDeclaration.ToSafeString(), item.DateDeclaration.ToSafeString());
                    old.DateDeclaration = item.DateDeclaration;
                }
                if (old.GetInformationType != item.GetInformationType)
                {
                    LogHelper.Log(UpdateRecord.Declaration, item.Id, "Способ получения информации", old.GetInformationType.ToString(), item.GetInformationType.ToString());
                    old.GetInformationType = item.GetInformationType;
                }
                if (old.GetResultType != item.GetResultType)
                {
                    LogHelper.Log(UpdateRecord.Declaration, item.Id, "Способ получения результата", old.GetResultType.ToString(), item.GetResultType.ToString());
                    old.GetResultType = item.GetResultType;
                }
                if (old.OtherReason != item.OtherReason)
                {
                    LogHelper.Log(UpdateRecord.Declaration, item.Id, "Другая причина переоформления", old.OtherReason, item.OtherReason);
                    old.OtherReason = item.OtherReason;
                }
                if (old.MasterName != item.MasterName)
                {
                    LogHelper.Log(UpdateRecord.Declaration, item.Id, "Заявитель", old.MasterName, item.MasterName);
                    old.MasterName = item.MasterName;
                }
                if (old.Status != item.Status)
                {
                    LogHelper.Log(UpdateRecord.Declaration, item.Id, "Статус", old.Status.ToString(), item.Status.ToString());
                    old.Status = item.Status;
                }
                if (old.Type != item.Type)
                {
                    LogHelper.Log(UpdateRecord.Declaration, item.Id, "Тип заявления", old.Type.ToString(), item.Type.ToString());
                    old.Type = item.Type;
                }
                if (old.ActualAddr != item.ActualAddr)
                {
                    old.ActualAddr = item.ActualAddr;
                }
                if (old.ActualAddrStr != item.ActualAddrStr)
                {
                    LogHelper.Log(UpdateRecord.Declaration, item.Id, "Фактический адрес", old.ActualAddrStr, item.ActualAddrStr);
                    old.ActualAddrStr = item.ActualAddrStr;
                }

                if (old.AddressForDocument != item.AddressForDocument)
                {
                    LogHelper.Log(UpdateRecord.Declaration, item.Id, "Адрес для документов", old.AddressForDocument, item.AddressForDocument);
                    old.AddressForDocument = item.AddressForDocument;
                }

                if (old.BanksName != item.BanksName)
                {
                    LogHelper.Log(UpdateRecord.Declaration, item.Id, "Банк", old.BanksName, item.BanksName);
                    old.BanksName = item.BanksName;
                }

                if (old.CheckingAccount != item.CheckingAccount)
                {
                    LogHelper.Log(UpdateRecord.Declaration, item.Id, "Номер р/с", old.CheckingAccount, item.CheckingAccount);
                    old.CheckingAccount = item.CheckingAccount;
                }

                if (old.Email != item.Email)
                {
                    LogHelper.Log(UpdateRecord.Declaration, item.Id, "Эл. почта", old.Email, item.Email);
                    old.Email = item.Email;
                }

                if (old.Fax != item.Fax)
                {
                    LogHelper.Log(UpdateRecord.Declaration, item.Id, "Факс", old.Fax, item.Fax);
                    old.Fax = item.Fax;
                }

                if (old.FullNameCompany != item.FullNameCompany)
                {
                    LogHelper.Log(UpdateRecord.Declaration, item.Id, "Полное название", old.FullNameCompany, item.FullNameCompany);
                    old.FullNameCompany = item.FullNameCompany;
                }

                if (old.NameCompany != item.NameCompany)
                {
                    LogHelper.Log(UpdateRecord.Declaration, item.Id, "Hазвание", old.NameCompany, item.NameCompany);
                    old.NameCompany = item.NameCompany;
                }


                if (old.VakeelName != item.VakeelName)
                {
                    LogHelper.Log(UpdateRecord.Declaration, item.Id, "Представитель", old.VakeelName, item.VakeelName);
                    old.VakeelName = item.VakeelName;
                }

                if (old.INN != item.INN)
                {
                    LogHelper.Log(UpdateRecord.Declaration, item.Id, "ИНН", old.INN, item.INN);
                    old.INN = item.INN;
                }

                if (old.KPP != item.KPP)
                {
                    LogHelper.Log(UpdateRecord.Declaration, item.Id, "КПП", old.KPP, item.KPP);
                    old.KPP = item.KPP;
                }

                if (old.OGRN != item.OGRN)
                {
                    LogHelper.Log(UpdateRecord.Declaration, item.Id, "ОГРН", old.OGRN, item.OGRN);
                    old.OGRN = item.OGRN;
                }

                if (old.Phone != item.Phone)
                {
                    LogHelper.Log(UpdateRecord.Declaration, item.Id, "Телефон", old.Phone, item.Phone);
                    old.Phone = item.Phone;
                }

                if (old.ShortNameCompany != item.ShortNameCompany)
                {
                    LogHelper.Log(UpdateRecord.Declaration, item.Id, "Сокращеное название", old.ShortNameCompany, item.ShortNameCompany);
                    old.ShortNameCompany = item.ShortNameCompany;
                }

                if (old.Comm != item.Comm)
                {
                    LogHelper.Log(UpdateRecord.Declaration, item.Id, "Комментарий к заявлению", old.Comm, item.Comm);
                    old.Comm = item.Comm;
                }

                if (old.LicenseFormNom != item.LicenseFormNom)
                {
                    LogHelper.Log(UpdateRecord.Declaration, item.Id, "Номер бланка лицензии", old.LicenseFormNom, item.LicenseFormNom);
                    old.LicenseFormNom = item.LicenseFormNom;
                }

                if (old.LicenseNom != item.LicenseNom)
                {
                    LogHelper.Log(UpdateRecord.Declaration, item.Id, "Номер лицензии", old.LicenseNom, item.LicenseNom);
                    old.LicenseNom = item.LicenseNom;
                }

                if (old.LicenseNomOfBook != item.LicenseNomOfBook)
                {
                    LogHelper.Log(UpdateRecord.Declaration, item.Id, "Номер дела", old.LicenseNomOfBook, item.LicenseNomOfBook);
                    old.LicenseNomOfBook = item.LicenseNomOfBook;
                }

                if (old.SmevId != item.SmevId)
                {
                    LogHelper.Log(UpdateRecord.Declaration, item.Id, "Код SmevId", old.SmevId, item.SmevId);
                    old.SmevId = item.SmevId;
                }

                if (old.LegalFormType != legal_form_type)
                {
                    legal_form_type.LinkDeclaration(old, LogHelper);
                }

                if (old.LicensedActivityType != license_activity_type)
                {
                    license_activity_type.LinkDeclaration(old, LogHelper);
                }

                old.AttachReasonForRenewList(item.ReasonForRenews.ToList(), LogHelper);

                if (old.Company != company)
                {
                    if (company != null)
                    {
                        company.LinkDeclaration(old, LogHelper);
                    }
                    else
                    {
                        if (old.Company != null)
                        {
                            old.Company.Declarations.Remove(old);
                        }
                    }
                }

                if (old.License != license)
                {
                    if (license != null)
                    {
                        license.LinkDeclaration(old, LogHelper);
                    }
                    else
                    {
                        if (old.License != null)
                        {
                            old.License.Declarations.Remove(old);
                        }
                    }
                }

                if (old.LicenseForm != item.LicenseForm)
                {
                    LogHelper.Log(UpdateRecord.Declaration, item.Id, "Привязка бланка лицензии", "", "");
                    old.LicenseForm = item.LicenseForm;
                }

                if (old.PostalAddr != item.PostalAddr)
                {
                    old.PostalAddr = item.PostalAddr;
                }

                if (old.PostalAddrStr != item.PostalAddrStr)
                {
                    LogHelper.Log(UpdateRecord.Declaration, item.Id, "Почтовый адрес", old.PostalAddrStr, item.PostalAddrStr);
                    old.PostalAddrStr = item.PostalAddrStr;
                }

                if (old.PostalCode != item.PostalCode)
                {
                    LogHelper.Log(UpdateRecord.Declaration, item.Id, "Почтовый индекс", old.PostalCode, item.PostalCode);
                    old.PostalCode = item.PostalCode;
                }

                if (old.ActualAddrAddon != item.ActualAddrAddon)
                {
                    old.ActualAddrAddon = item.ActualAddrAddon;
                }

                if (old.PostalAddrAddon != item.PostalAddrAddon)
                {
                    old.PostalAddrAddon = item.PostalAddrAddon;
                }

                if (old.FSRARActualAddr != item.FSRARActualAddr)
                {
                    LogHelper.Log(UpdateRecord.Declaration, item.Id, "Фак. адрес - ФСРАР", old.FSRARActualAddr, item.FSRARActualAddr);
                    old.FSRARActualAddr = item.FSRARActualAddr;
                }

                if (old.FSRARPostalAddr != item.FSRARPostalAddr)
                {
                    LogHelper.Log(UpdateRecord.Declaration, item.Id, "Поч. адрес - ФСРАР", old.FSRARPostalAddr, item.FSRARPostalAddr);
                    old.FSRARPostalAddr = item.FSRARPostalAddr;
                }
                return(old);
            }
        }
        private void btnCreaLicenza_Click_1(object sender, EventArgs e)
        {
            LicenseType tipo     = rbStandard.Checked ? LicenseType.Standard : LicenseType.Trial;
            int         utilizzi = 1;

            if (rbRemote.Checked)
            {
                int.TryParse(txtUse.Text, out utilizzi);
                if (utilizzi <= 0)
                {
                    utilizzi = 1;
                }
            }
            Guid id;

            if (!Guid.TryParse(txtClientId.Text, out id))
            {
                MessageBox.Show("Id Cliente {txtClientId.Text} non valido", this.Text);
                return;
            }
            ILicenseBuilder builder = null;

            if (tipo == LicenseType.Trial)
            {
                int days = 30;
                int.TryParse(txtValidity.Text, out days);
                if (days <= 30)
                {
                    days = 30;
                }

                builder = License.New()
                          .WithUniqueIdentifier(Guid.NewGuid())
                          .As(tipo)
                          .ExpiresAt(DateTime.Now.AddDays(days)).WithAdditionalAttributes(new Dictionary <string, string>
                {
                    { "ClientId", id.ToString() }
                });;
            }
            else
            {
                builder = License.New()
                          .WithUniqueIdentifier(Guid.NewGuid())
                          .As(tipo)
                          // Usare un sequence così da evitare problemi di concorrenza sul DB
                          .WithAdditionalAttributes(new Dictionary <string, string>
                {
                    { "Used", "0" },
                    { "ClientId", id.ToString() }
                });
            }
            license = builder.WithMaximumUtilization(utilizzi)
                      .WithProductFeatures(new Dictionary <string, string>
            {
                { "Contabilità", checkContabilità.Checked ? "1" : "0" },
                { "Documenti", checkDocumenti.Checked ? "1" : "0" },
                { "Magazzino", checkMagazzino.Checked ? "1" : "0" },
                { "Manutenzioni", checkManutenzioni.Checked ? "1" : "0" }
            })
                      .LicensedTo(txtUsername.Text, txtMail.Text)
                      .CreateAndSignWithPrivateKey(txtPrivateKey.Text, PASS_PHRASE + "." + txtClientId.Text);
            txtLicense.Text = license.ToString();
        }
Esempio n. 47
0
        public static void Autorizacao()
        {
            License license = new License();

            license.SetLicense("Tecnomapas.Blocos.Etx.ModuloRelatorio.AsposeEtx.Aspose.Words.lic");
        }
Esempio n. 48
0
        static int Main(string[] args)
        {
            // ServicePointManager.ServerCertificateValidationCallback = delegate { return true;  // Trust any (self-signed) certificate };

            Context context = new Context();

            context.baseUrl = "https://go.netlicensing.io/core/v2/rest";

            context.username     = "******";
            context.password     = "******";
            context.securityMode = SecurityMode.BASIC_AUTHENTICATION;

            String randomNumber = randomString(8);

            String  demoProductNumber              = numberWithPrefix("P", randomNumber);
            String  demoProductModuleNumber        = numberWithPrefix("PM", randomNumber);
            String  demoLicensingModel             = Constants.LicensingModel.TryAndBuy.NAME;
            String  demoLicenseTemplate1_Number    = numberWithPrefix("LT", randomNumber);
            String  demoLicenseTemplate1_Name      = "Demo Evaluation Period";
            String  demoLicenseTemplate1_Type      = "FEATURE";
            Decimal demoLicenseTemplate1_Price     = 12.50M;
            String  demoLicenseTemplate1_Currency  = "EUR";
            Boolean demoLicenseTemplate1_Automatic = false;
            Boolean demoLicenseTemplate1_Hidden    = false;
            String  demoLicenseeNumber             = numberWithPrefix("L", randomNumber);
            String  demoLicenseNumber              = numberWithPrefix("LC", randomNumber);
            String  demoLicenseeName = "Demo Licensee";

            try
            {
                #region ****************** Lists

                List <String> licenseTypes = UtilityService.listLicenseTypes(context);
                ConsoleWriter.WriteList("License Types:", licenseTypes);

                List <String> licensingModels = UtilityService.listLicensingModels(context);
                ConsoleWriter.WriteList("Licensing Models:", licensingModels);

                #endregion

                #region ****************** Product

                Product newProduct = new Product();
                newProduct.number = demoProductNumber;
                newProduct.name   = "Demo product";
                Product product = ProductService.create(context, newProduct);
                ConsoleWriter.WriteEntity("Added product:", product);

                product = ProductService.get(context, demoProductNumber);
                ConsoleWriter.WriteEntity("Got product:", product);

                List <Product> products = ProductService.list(context, null);
                ConsoleWriter.WriteList("Got the following products:", products);

                Product updateProduct = new Product();
                updateProduct.productProperties.Add("Updated property name", "Updated value");
                product = ProductService.update(context, demoProductNumber, updateProduct);
                ConsoleWriter.WriteEntity("Updated product:", product);

                ProductService.delete(context, demoProductNumber, true);
                ConsoleWriter.WriteMsg("Deleted Product!");

                products = ProductService.list(context, null);
                ConsoleWriter.WriteList("Got the following Products:", products);

                product = ProductService.create(context, newProduct);
                ConsoleWriter.WriteEntity("Added product again:", product);

                products = ProductService.list(context, null);
                ConsoleWriter.WriteList("Got the following Products:", products);

                #endregion

                #region ****************** ProductModule

                ProductModule newProductModule = new ProductModule();
                newProductModule.number         = demoProductModuleNumber;
                newProductModule.name           = "Demo product module";
                newProductModule.licensingModel = demoLicensingModel;
                ProductModule productModule = ProductModuleService.create(context, demoProductNumber, newProductModule);
                ConsoleWriter.WriteEntity("Added product module:", productModule);

                productModule = ProductModuleService.get(context, demoProductModuleNumber);
                ConsoleWriter.WriteEntity("Got product module:", productModule);

                List <ProductModule> productModules = ProductModuleService.list(context, null);
                ConsoleWriter.WriteList("Got the following ProductModules:", productModules);

                ProductModule updateProductModule = new ProductModule();
                updateProductModule.productModuleProperties.Add("Updated property name", "Updated property value");
                productModule = ProductModuleService.update(context, demoProductModuleNumber, updateProductModule);
                ConsoleWriter.WriteEntity("Updated product module:", productModule);

                ProductModuleService.delete(context, demoProductModuleNumber, true);
                ConsoleWriter.WriteMsg("Deleted ProductModule!");

                productModules = ProductModuleService.list(context, null);
                ConsoleWriter.WriteList("Got the following ProductModules:", productModules);

                productModule = ProductModuleService.create(context, demoProductNumber, newProductModule);
                ConsoleWriter.WriteEntity("Added product module again:", productModule);

                productModules = ProductModuleService.list(context, null);
                ConsoleWriter.WriteList("Got the following ProductModules:", productModules);

                #endregion

                #region ****************** LicenseTemplate

                LicenseTemplate newLicenseTemplate = new LicenseTemplate();
                newLicenseTemplate.number      = demoLicenseTemplate1_Number;
                newLicenseTemplate.name        = demoLicenseTemplate1_Name;
                newLicenseTemplate.licenseType = demoLicenseTemplate1_Type;
                newLicenseTemplate.price       = demoLicenseTemplate1_Price;
                newLicenseTemplate.currency    = demoLicenseTemplate1_Currency;
                newLicenseTemplate.automatic   = demoLicenseTemplate1_Automatic;
                newLicenseTemplate.hidden      = demoLicenseTemplate1_Hidden;
                ConsoleWriter.WriteEntity("Adding license template:", newLicenseTemplate);
                LicenseTemplate licenseTemplate = LicenseTemplateService.create(context, demoProductModuleNumber, newLicenseTemplate);
                ConsoleWriter.WriteEntity("Added license template:", licenseTemplate);

                licenseTemplate = LicenseTemplateService.get(context, demoLicenseTemplate1_Number);
                ConsoleWriter.WriteEntity("Got licenseTemplate:", licenseTemplate);

                List <LicenseTemplate> licenseTemplates = LicenseTemplateService.list(context, null);
                ConsoleWriter.WriteList("Got the following license templates:", licenseTemplates);

                LicenseTemplate updateLicenseTemplate = new LicenseTemplate();
                updateLicenseTemplate.active    = true;
                updateLicenseTemplate.automatic = demoLicenseTemplate1_Automatic; // workaround: at the moment not specified booleans treated as "false"
                updateLicenseTemplate.hidden    = demoLicenseTemplate1_Hidden;    // workaround: at the moment not specified booleans treated as "false"
                licenseTemplate = LicenseTemplateService.update(context, demoLicenseTemplate1_Number, updateLicenseTemplate);
                ConsoleWriter.WriteEntity("Updated license template:", licenseTemplate);

                LicenseTemplateService.delete(context, demoLicenseTemplate1_Number, true);
                ConsoleWriter.WriteMsg("Deleted LicenseTemplate!");

                licenseTemplates = LicenseTemplateService.list(context, null);
                ConsoleWriter.WriteList("Got the following license templates:", licenseTemplates);

                licenseTemplate = LicenseTemplateService.create(context, demoProductModuleNumber, newLicenseTemplate);
                ConsoleWriter.WriteEntity("Added license template again:", licenseTemplate);

                licenseTemplates = LicenseTemplateService.list(context, null);
                ConsoleWriter.WriteList("Got the following license templates:", licenseTemplates);


                #endregion

                #region ****************** Licensee

                Licensee newLicensee = new Licensee();
                newLicensee.number = demoLicenseeNumber;
                Licensee licensee = LicenseeService.create(context, demoProductNumber, newLicensee);
                ConsoleWriter.WriteEntity("Added licensee:", licensee);

                List <Licensee> licensees = LicenseeService.list(context, null);
                ConsoleWriter.WriteList("Got the following licensees:", licensees);

                LicenseeService.delete(context, demoLicenseeNumber, true);
                ConsoleWriter.WriteMsg("Deleted licensee!");

                licensees = LicenseeService.list(context, null);
                ConsoleWriter.WriteList("Got the following licensees after delete:", licensees);

                licensee = LicenseeService.create(context, demoProductNumber, newLicensee);
                ConsoleWriter.WriteEntity("Added licensee again:", licensee);

                licensee = LicenseeService.get(context, demoLicenseeNumber);
                ConsoleWriter.WriteEntity("Got licensee:", licensee);

                Licensee updateLicensee = new Licensee();
                updateLicensee.licenseeProperties.Add("Updated property name", "Updated value");
                licensee = LicenseeService.update(context, demoLicenseeNumber, updateLicensee);
                ConsoleWriter.WriteEntity("Updated licensee:", licensee);

                licensees = LicenseeService.list(context, null);
                ConsoleWriter.WriteList("Got the following licensees:", licensees);

                #endregion

                #region ****************** License

                License newLicense = new License();
                newLicense.number = demoLicenseNumber;
                License license = LicenseService.create(context, demoLicenseeNumber, demoLicenseTemplate1_Number, null, newLicense);
                ConsoleWriter.WriteEntity("Added license:", license);

                List <License> licenses = LicenseService.list(context, null);
                ConsoleWriter.WriteList("Got the following licenses:", licenses);

                LicenseService.delete(context, demoLicenseNumber);
                Console.WriteLine("Deleted license");

                licenses = LicenseService.list(context, null);
                ConsoleWriter.WriteList("Got the following licenses:", licenses);

                license = LicenseService.create(context, demoLicenseeNumber, demoLicenseTemplate1_Number, null, newLicense);
                ConsoleWriter.WriteEntity("Added license again:", license);

                license = LicenseService.get(context, demoLicenseNumber);
                ConsoleWriter.WriteEntity("Got license:", license);

                License updateLicense = new License();
                updateLicense.licenseProperties.Add("Updated property name", "Updated value");
                license = LicenseService.update(context, demoLicenseNumber, null, updateLicense);
                ConsoleWriter.WriteEntity("Updated license:", license);

                #endregion

                #region ****************** PaymentMethod

                List <PaymentMethod> paymentMethods = PaymentMethodService.list(context);
                ConsoleWriter.WriteList("Got the following payment methods:", paymentMethods);

                #endregion

                #region ****************** Token

                //NetLicensing supports API Key Identification to allow limited API access on vendor's behalf.
                //See: https://netlicensing.io/wiki/security for details.
                Token newToken = new Token();
                newToken.tokenType = Constants.Token.TYPE_APIKEY;
                Token apiKey = TokenService.create(context, newToken);
                ConsoleWriter.WriteEntity("Created APIKey:", apiKey);
                context.apiKey = apiKey.number;

                newToken.tokenType = Constants.Token.TYPE_SHOP;
                newToken.tokenProperties.Add(Constants.Licensee.LICENSEE_NUMBER, demoLicenseeNumber);
                context.securityMode = SecurityMode.APIKEY_IDENTIFICATION;
                Token shopToken = TokenService.create(context, newToken);
                context.securityMode = SecurityMode.BASIC_AUTHENTICATION;
                ConsoleWriter.WriteEntity("Got the following shop token:", shopToken);

                String       filter = Constants.Token.TOKEN_TYPE + "=" + Constants.Token.TYPE_SHOP;
                List <Token> tokens = TokenService.list(context, filter);
                ConsoleWriter.WriteList("Got the following shop tokens:", tokens);

                TokenService.delete(context, shopToken.number);
                ConsoleWriter.WriteMsg("Deactivated shop token!");

                tokens = TokenService.list(context, filter);
                ConsoleWriter.WriteList("Got the following shop tokens after deactivate:", tokens);

                #endregion

                #region ****************** Validate

                ValidationParameters validationParameters = new ValidationParameters();
                validationParameters.setLicenseeName(demoLicenseeName);
                validationParameters.setProductNumber(demoProductNumber);
                validationParameters.put(demoProductModuleNumber, "paramKey", "paramValue");
                ValidationResult validationResult = LicenseeService.validate(context, demoLicenseeNumber, validationParameters);
                ConsoleWriter.WriteEntity("Validation result for created licensee:", validationResult);

                context.securityMode = SecurityMode.APIKEY_IDENTIFICATION;
                validationResult     = LicenseeService.validate(context, demoLicenseeNumber, validationParameters);
                context.securityMode = SecurityMode.BASIC_AUTHENTICATION;
                ConsoleWriter.WriteEntity("Validation repeated with APIKey:", validationResult);

                #endregion

                #region ****************** Transfer

                Licensee transferLicensee = new Licensee();
                transferLicensee.number = "TR" + demoLicenseeNumber;
                transferLicensee.licenseeProperties.Add(Constants.Licensee.PROP_MARKED_FOR_TRANSFER, Boolean.TrueString.ToLower());
                transferLicensee = LicenseeService.create(context, demoProductNumber, transferLicensee);
                ConsoleWriter.WriteEntity("Added transfer licensee:", transferLicensee);

                License transferLicense = new License();
                transferLicense.number = "LTR" + demoLicenseNumber;
                License newTransferLicense = LicenseService.create(context, transferLicensee.number, demoLicenseTemplate1_Number, null, transferLicense);
                ConsoleWriter.WriteEntity("Added license for transfer:", newTransferLicense);

                LicenseeService.transfer(context, licensee.number, transferLicensee.number);

                licenses = LicenseService.list(context, Constants.Licensee.LICENSEE_NUMBER + "=" + licensee.number);
                ConsoleWriter.WriteList("Got the following licenses after transfer:", licenses);

                Licensee transferLicenseeWithApiKey = new Licensee();
                transferLicenseeWithApiKey.number = "Key" + demoLicenseeNumber;
                transferLicenseeWithApiKey.licenseeProperties.Add(Constants.Licensee.PROP_MARKED_FOR_TRANSFER, Boolean.TrueString.ToLower());
                transferLicenseeWithApiKey = LicenseeService.create(context, demoProductNumber, transferLicenseeWithApiKey);

                License transferLicenseWithApiKey = new License();
                transferLicenseWithApiKey.number = "Key" + demoLicenseNumber;
                LicenseService.create(context, transferLicenseeWithApiKey.number, demoLicenseTemplate1_Number, null,
                                      transferLicenseWithApiKey);

                context.securityMode = SecurityMode.APIKEY_IDENTIFICATION;
                LicenseeService.transfer(context, licensee.number, transferLicenseeWithApiKey.number);
                context.securityMode = SecurityMode.BASIC_AUTHENTICATION;

                licenses = LicenseService.list(context, Constants.Licensee.LICENSEE_NUMBER + "=" + licensee.number);
                ConsoleWriter.WriteList("Got the following licenses after transfer:", licenses);

                #endregion

                #region ****************** Transactions

                List <Transaction> transactions = TransactionService.list(context, Constants.Transaction.SOURCE_SHOP_ONLY + "=" + Boolean.TrueString.ToLower());
                ConsoleWriter.WriteList("Got the following transactions shop only:", transactions);

                transactions = TransactionService.list(context, null);
                ConsoleWriter.WriteList("Got the following transactions after transfer:", transactions);

                #endregion

                Console.WriteLine("All done.");

                return(0);
            }
            catch (NetLicensingException e)
            {
                Console.WriteLine("Got NetLicensing exception:");
                Console.WriteLine(e);
            }
            catch (Exception e)
            {
                Console.WriteLine("Got exception:");
                Console.WriteLine(e);
            }
            finally
            {
                try
                {
                    // Cleanup:
                    context.securityMode = SecurityMode.BASIC_AUTHENTICATION;

                    // deactivate api key in case APIKey was used (exists)
                    if (!String.IsNullOrEmpty(context.apiKey))
                    {
                        TokenService.delete(context, context.apiKey);
                    }
                    // delete test product with all its related items
                    ProductService.delete(context, demoProductNumber, true);
                }
                catch (NetLicensingException e)
                {
                    Console.WriteLine("Got NetLicensing exception during cleanup:");
                    Console.WriteLine(e);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Got exception during cleanup:");
                    Console.WriteLine(e);
                }
            }

            return(1);
        }
Esempio n. 49
0
        private void NextSlide()
        {
            if (counter > 0)
            {
                floatingLogo.FadeIn();
            }

            if (counter < Slides.Length)
            {
                object next = Slides[counter++];

                image.Source = ImageProc.GetImage(content);

                //
                // Install
                //
                if (next is CEIP)
                {
                    nextButton.IsEnabled = true;
                }
                else if (next is ProductKey)
                {
                    InstallerData.JoinedCEIP = (content.Content as CEIP).joinCEIP.IsChecked == true;

                    ProductKey _next = next as ProductKey;

                    _next.OptionSelected   -= ProductKey_OptionSelected;
                    _next.OptionDeselected -= ProductKey_OptionDeselected;
                    _next.OptionSelected   += ProductKey_OptionSelected;
                    _next.OptionDeselected += ProductKey_OptionDeselected;

                    if (_next.freeTrial.IsChecked == true || InstallerData.ProductKey != null)
                    {
                        nextButton.IsEnabled = true;
                    }
                }
                else if (next is License)
                {
                    // In case of upgrade, the product key slide will never be shown.
                    if (content.Content is CEIP)
                    {
                        InstallerData.JoinedCEIP = (content.Content as CEIP).joinCEIP.IsChecked == true;
                    }

                    License _next = next as License;

                    _next.Agreed    -= License_Agreed;
                    _next.Disagreed -= License_Disagreed;
                    _next.Agreed    += License_Agreed;
                    _next.Disagreed += License_Disagreed;

                    if (InstallerData.AcceptedAgreement)
                    {
                        nextButton.IsEnabled = true;
                    }

                    //	nextButton.Content = "_Install";
                }
                else if (next is Personalize)
                {
                    nextButton.IsEnabled = true;
                    nextButton.Content   = "_Install";
                }
                //else if (next is InstallLocation)
                //{
                //	nextButton.IsEnabled = true;
                //	nextButton.Content = "_Install";
                //}
                else if (next is InstallProgress)
                {
                    prevButton.FadeOut();
                    prevButton.IsEnabled = false;

                    nextButton.Content = "_Working...";

                    //InstallerData.InstallLocation = (content.Content as InstallLocation).installLocation.Text;

                    if (!InstallerData.InstallLocation.EndsWith("\\" + InstallerData.DisplayName))
                    {
                        InstallerData.InstallLocation += "\\" + InstallerData.DisplayName;
                    }

                    (next as InstallProgress).Error     += Install_Error;
                    (next as InstallProgress).Completed += Install_Completed;
                }

                //
                // Uninstall
                //
                if (next is Uninstall.UninstallOptions)
                {
                    nextButton.IsEnabled = true;
                    nextButton.Content   = "_Uninstall";
                }
                else if (next is Uninstall.UninstallProgress)
                {
                    prevButton.FadeOut();
                    prevButton.IsEnabled = false;

                    nextButton.Content = "_Working...";

                    Uninstall.UninstallOptions optns = content.Content as Uninstall.UninstallOptions;

                    InstallerData.DeleteDatabase   = (bool)optns.deleteDatabase.IsChecked;
                    InstallerData.DeleteAccounts   = (bool)optns.deleteAccounts.IsChecked;
                    InstallerData.DeleteSettings   = (bool)optns.deleteSettings.IsChecked;
                    InstallerData.DeleteDictionary = (bool)optns.deleteDictionary.IsChecked;

                    (next as Uninstall.UninstallProgress).Error     += Uninstall_Error;
                    (next as Uninstall.UninstallProgress).Completed += Uninstall_Completed;
                }

                content.Content = next;
                content.UpdateLayout();
                content.SlideDisplay(image, Extensions.SlideDirection.Right);
            }
            else
            {
                Close();
            }
        }
Esempio n. 50
0
        /// <summary>
        /// Applies the product license
        /// </summary>
        private static void SetInternalLicense()
        {
            License license = new License();

            license.SetLicense(LicensePath);
        }
Esempio n. 51
0
        public ActionResult DealWon(int id)
        {
            SSMEntities    se       = new SSMEntities();
            DealRepository dealrepo = new DealRepository(se);
            Deal           deal     = dealrepo.getByID(id);

            if (deal != null)
            {
                customer cus = new customer();
                if (se.AspNetUsers.Where(us => us.UserName.Equals(deal.contact.emails)).FirstOrDefault() == null)
                {
                    cus.cusAddress = deal.contact.Street + " " + deal.contact.City + " " + deal.contact.Region + " ";
                    cus.cusCompany = 1;
                    cus.cusEmail   = deal.contact.emails;
                    cus.cusName    = deal.contact.FirstName + " " + deal.contact.MiddleName + " " + deal.contact.LastName;
                    cus.cusPhone   = deal.contact.Phone;
                    se.customers.Add(cus);
                    se.SaveChanges();
                    AccountController ac           = new AccountController();
                    String            cusAccountID = ac.RegisterNewAccount(cus.cusEmail, "320395@qwE", System.Web.HttpContext.Current, "Customer");
                    cus.userID = cusAccountID;
                    se.SaveChanges();
                }
                else
                {
                    AspNetUser thiscus = se.AspNetUsers.Where(us => us.UserName.Equals(deal.contact.emails)).First();
                    cus = thiscus.customers.First();
                }
                deal.Status = 3;

                order order = new order();
                order.customerID = cus.id;
                float price = 0;
                order.orderNumber = se.orders.ToList().Count() + 1;
                order.subtotal    = deal.Value;
                order.status      = 1;
                order.total       = (double)order.subtotal * 1.1;
                order.VAT         = (double)order.subtotal * 0.1;
                order.fromDeal    = deal.id;
                order.createDate  = DateTime.Now;
                Storage storeage = new Storage();
                se.orders.Add(order);
                se.SaveChanges();
                order.Contract = storeage.uploadfile(cus.userID, "order" + order.id);
                se.SaveChanges();
                deal.Status = 3;
                se.SaveChanges();
                bool validLicense = true;
                foreach (Deal_Item dealitem in deal.Deal_Item)
                {
                    int lcount = se.Licenses.Where(u => u.PlanID == dealitem.planID && u.status == null && u.SaleRepResponsible == null).Count();
                    if (lcount < dealitem.Quantity)
                    {
                        validLicense = false;
                    }
                }
                if (validLicense)
                {
                    foreach (Deal_Item dealitem in deal.Deal_Item)
                    {
                        for (int i = 0; i < dealitem.Quantity; i++)
                        {
                            License license = se.Licenses.Where(u => u.PlanID == dealitem.planID && u.status == null && u.SaleRepResponsible == null).FirstOrDefault();
                            if (license != null)
                            {
                                license.customerID         = cus.id;
                                license.SaleRepResponsible = deal.Deal_SaleRep_Respon.LastOrDefault().userID;
                                license.status             = 1;
                                OrderItem orderItem = new OrderItem();
                                orderItem.orderID   = order.id;
                                orderItem.planID    = dealitem.planID;
                                orderItem.SoldPrice = (double)dealitem.price;
                                orderItem.LicenseID = license.id;
                                se.OrderItems.Add(orderItem);
                            }
                            else
                            {
                                return(RedirectToAction("Detail", new { id = deal.id }));
                            }
                        }
                    }

                    se.SaveChanges();
                }
                else
                {
                    return(RedirectToAction("Detail", new { id = deal.id }));
                }
                Notification noti = new Notification();
                noti.NotiName    = "Contract successfully created";
                noti.NotiContent = "Deal No." + deal.id + ": has finished with a contract and order";
                noti.userID      = deal.Deal_SaleRep_Respon.LastOrDefault().userID;
                noti.CreateDate  = DateTime.Now;
                noti.viewed      = false;
                noti.hreflink    = "/Deal/Detail?id=" + deal.id;
                se.Notifications.Add(noti);
                se.SaveChanges();
                deal.Status = 5;
                se.SaveChanges();
                //}
                //catch (Exception e) {
                //    return Json(new { result = "sad" }, JsonRequestBehavior.AllowGet);
                //}
            }
            return(RedirectToAction("Detail", new { id = deal.id }));
        }
Esempio n. 52
0
        public override License GetLicense(LicenseContext context, Type type,
                                           object instance, bool allowExceptions)
        {
            // Step 1: locate the license key
            string licenseKey = null;

            switch (context.UsageMode)
            {
            case LicenseUsageMode.Designtime:
                licenseKey = GetDesignTimeLicenseKey(type);
                context.SetSavedLicenseKey(type, licenseKey);
                break;

            case LicenseUsageMode.Runtime:
                licenseKey = context.GetSavedLicenseKey(type, null);
                break;
            }
            if (licenseKey == null)
            {
                if (allowExceptions)
                {
                    throw new LicenseException(type, instance,
                                               "No appropriate license key was located.");
                }
                else
                {
                    return(null);
                }
            }


            // Step 2: validate the license key
            bool isValid = IsLicenseKeyValid(type, licenseKey);

            if (!isValid)
            {
                if (allowExceptions)
                {
                    throw new LicenseException(type, instance,
                                               "License key is not valid.");
                }
                else
                {
                    return(null);
                }
            }


            // Step 3: grant a license
            License license = CreateLicense(type, licenseKey);

            if (license == null)
            {
                if (allowExceptions)
                {
                    throw new LicenseException(type, instance,
                                               "license could not be created.");
                }
                else
                {
                    return(null);
                }
            }

            return(license);
        }
Esempio n. 53
0
        private void ValidateLicense(IElasticClient client, XplatManualResetEvent handle)
        {
            if (!this._config.ShieldEnabled)
            {
                return;
            }
            var license = client.GetLicense();

            if (license.IsValid && license.License.Status == LicenseStatus.Active)
            {
                return;
            }

            var exceptionMessageStart = "Server has license plugin installed, ";

#if DOTNETCORE
            var licenseFile = string.Empty;
#else
            var licenseFile = Environment.GetEnvironmentVariable("ES_LICENSE_FILE", EnvironmentVariableTarget.Machine);
#endif
            if (!string.IsNullOrWhiteSpace(licenseFile))
            {
                var putLicense = client.PostLicense(new PostLicenseRequest {
                    License = License.LoadFromDisk(licenseFile)
                });
                if (!putLicense.IsValid)
                {
                    this.Fatal(handle, new Exception("Server has invalid license and the ES_LICENSE_FILE failed to register\r\n" + putLicense.DebugInformation));
                    return;
                }

                license = client.GetLicense();
                if (license.IsValid && license.License.Status == LicenseStatus.Active)
                {
                    return;
                }
                exceptionMessageStart += " but the installed license is invalid and we attempted to register ES_LICENSE_FILE ";
            }

            Exception exception = null;

            if (license.ApiCall.Success && license.License == null)
            {
                exception = new Exception($"{exceptionMessageStart}  but the license was deleted!");
            }

            else if (license.License.Status == LicenseStatus.Expired)
            {
                exception = new Exception($"{exceptionMessageStart} but the license has expired!");
            }

            else if (license.License.Status == LicenseStatus.Invalid)
            {
                exception = new Exception($"{exceptionMessageStart} but the license is invalid!");
            }

            if (exception != null)
            {
                this.Fatal(handle, exception);
            }
        }
Esempio n. 54
0
    protected void btn_export_Click(object sender, EventArgs e)
    {
        //btn_search_Click(null, null);

        //gridExport.WriteXlsToResponse("EmployeeDatabase", true);
        License lic = new License();

        lic.SetLicense(HttpContext.Current.Server.MapPath(@"~\Aspose.lic"));
        DataTable dtTableName = GetData();
        Workbook  workbook    = new Workbook();
        Worksheet worksheet   = workbook.Worksheets[0];

        worksheet.Name = "EmployeeDatabase";

        Cells cells = worksheet.Cells;

        Aspose.Cells.Style style  = workbook.Styles[workbook.Styles.Add()];
        Aspose.Cells.Style style1 = workbook.Styles[workbook.Styles.Add()];
        Aspose.Cells.Style style2 = workbook.Styles[workbook.Styles.Add()];
        style.Font.Name   = "Arial"; //文字字体 ,宋体
        style.Font.Size   = 10;      //文字大小
        style.Font.IsBold = true;    //粗体
        style.Borders[BorderType.TopBorder].Color        = Color.Black;
        style.Borders[BorderType.BottomBorder].Color     = Color.Black;
        style.Borders[BorderType.LeftBorder].Color       = Color.Black;
        style.Borders[BorderType.RightBorder].Color      = Color.Black;
        style.Borders[BorderType.TopBorder].LineStyle    = CellBorderType.Thin;
        style.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;
        style.Borders[BorderType.LeftBorder].LineStyle   = CellBorderType.Thin;
        style.Borders[BorderType.RightBorder].LineStyle  = CellBorderType.Thin;
        style.HorizontalAlignment = TextAlignmentType.Center; //文字居中

        style1.Font.Name   = "Arial";                         //文字字体 ,宋体
        style1.Font.Size   = 10;                              //文字大小
        style1.Font.IsBold = false;                           //粗体
        style1.Borders[BorderType.TopBorder].Color        = Color.Black;
        style1.Borders[BorderType.BottomBorder].Color     = Color.Black;
        style1.Borders[BorderType.LeftBorder].Color       = Color.Black;
        style1.Borders[BorderType.RightBorder].Color      = Color.Black;
        style1.Borders[BorderType.TopBorder].LineStyle    = CellBorderType.Thin;
        style1.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;
        style1.Borders[BorderType.LeftBorder].LineStyle   = CellBorderType.Thin;
        style1.Borders[BorderType.RightBorder].LineStyle  = CellBorderType.Thin;
        style1.HorizontalAlignment = TextAlignmentType.Center;//文字居中


        style2.Font.Name   = "Arial"; //文字字体 ,宋体
        style2.Font.Size   = 10;      //文字大小
        style2.Font.IsBold = true;    //粗体
        style2.Borders[BorderType.TopBorder].Color        = Color.Black;
        style2.Borders[BorderType.BottomBorder].Color     = Color.Black;
        style2.Borders[BorderType.LeftBorder].Color       = Color.Black;
        style2.Borders[BorderType.RightBorder].Color      = Color.Black;
        style2.Borders[BorderType.TopBorder].LineStyle    = CellBorderType.Thin;
        style2.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;
        style2.Borders[BorderType.LeftBorder].LineStyle   = CellBorderType.Thin;
        style2.Borders[BorderType.RightBorder].LineStyle  = CellBorderType.Thin;
        style2.HorizontalAlignment = TextAlignmentType.Center;//文字居中


        cells[0, 0].PutValue("Collin's Movers Employee Database");


        cells[1, 0].PutValue("Date           " + PrintDate());
        cells[1, 21].PutValue("CPF");
        cells[1, 21].SetStyle(style);
        cells[1, 22].SetStyle(style);
        Range range = worksheet.Cells.CreateRange(1, 21, 1, 2); //Merge the cells /合并单元格

        range.Merge();

        cells[2, 0].PutValue("S/N");
        cells[2, 1].PutValue("Employee Name");
        cells[2, 2].PutValue("NRIC No./ FIN No.");
        cells[2, 3].PutValue("Nationality");
        cells[2, 4].PutValue("Category");
        cells[2, 5].PutValue("Work Pass Expiry Date");
        cells[2, 6].PutValue("Days to Expiry");
        cells[2, 7].PutValue("Designation");
        cells[2, 8].PutValue("Date of Birth");
        cells[2, 9].PutValue("Age");
        cells[2, 10].PutValue("Date Jobined");
        cells[2, 11].PutValue("Year of Service");
        cells[2, 12].PutValue("Date Left");
        cells[2, 13].PutValue("CPF/Non-CPF");
        cells[2, 14].PutValue("Address");
        cells[2, 15].PutValue("Bank");
        cells[2, 16].PutValue("Account Number");
        cells[2, 17].PutValue("Basic Salary");
        cells[2, 18].PutValue("Laundry Expenses");
        cells[2, 19].PutValue("Accommodation");
        cells[2, 20].PutValue("Witholding Tax");
        cells[2, 21].PutValue("Employer");
        cells[2, 22].PutValue("Employee");
        cells[2, 23].PutValue("Levy");
        cells[2, 24].PutValue("MBMF/Sinda/CDAC");



        cells[2, 0].SetStyle(style);
        cells[2, 1].SetStyle(style);
        cells[2, 2].SetStyle(style);
        cells[2, 3].SetStyle(style);
        cells[2, 4].SetStyle(style);
        cells[2, 5].SetStyle(style);
        cells[2, 6].SetStyle(style);
        cells[2, 7].SetStyle(style);
        cells[2, 8].SetStyle(style);
        cells[2, 9].SetStyle(style);
        cells[2, 10].SetStyle(style);
        cells[2, 11].SetStyle(style);
        cells[2, 12].SetStyle(style);
        cells[2, 13].SetStyle(style);
        cells[2, 14].SetStyle(style);
        cells[2, 15].SetStyle(style);
        cells[2, 16].SetStyle(style);
        cells[2, 17].SetStyle(style);
        cells[2, 18].SetStyle(style);
        cells[2, 19].SetStyle(style);
        cells[2, 20].SetStyle(style);
        cells[2, 21].SetStyle(style);
        cells[2, 22].SetStyle(style);
        cells[2, 23].SetStyle(style);
        cells[2, 24].SetStyle(style);

        cells.SetColumnWidth(0, 5);
        cells.SetColumnWidth(1, 20);
        cells.SetColumnWidth(2, 20);
        cells.SetColumnWidth(3, 20);
        cells.SetColumnWidth(4, 20);
        cells.SetColumnWidth(5, 20);
        cells.SetColumnWidth(6, 20);
        cells.SetColumnWidth(7, 20);
        cells.SetColumnWidth(8, 20);
        cells.SetColumnWidth(9, 20);
        cells.SetColumnWidth(10, 20);
        cells.SetColumnWidth(11, 20);
        cells.SetColumnWidth(12, 20);
        cells.SetColumnWidth(13, 20);
        cells.SetColumnWidth(14, 20);
        cells.SetColumnWidth(15, 20);
        cells.SetColumnWidth(16, 20);
        cells.SetColumnWidth(17, 20);
        cells.SetColumnWidth(18, 20);
        cells.SetColumnWidth(19, 20);
        cells.SetColumnWidth(20, 20);
        cells.SetColumnWidth(21, 20);
        cells.SetColumnWidth(22, 20);
        cells.SetColumnWidth(23, 20);
        cells.SetColumnWidth(24, 20);
        for (int n = 0; n < dtTableName.Rows.Count; n++)
        {
            cells[n + 3, 0].PutValue(n + 1);
            cells[n + 3, 1].PutValue(SafeValue.SafeString(dtTableName.Rows[n]["Name"]));
            cells[n + 3, 2].PutValue(SafeValue.SafeString(dtTableName.Rows[n]["IcNo"]));
            cells[n + 3, 3].PutValue(SafeValue.SafeString(dtTableName.Rows[n]["Country"]));
            cells[n + 3, 4].PutValue(SafeValue.SafeString(dtTableName.Rows[n]["Department"]));
            cells[n + 3, 5].PutValue(SafeValue.SafeString(dtTableName.Rows[n]["ExpiryDate"]));
            cells[n + 3, 6].PutValue(SafeValue.SafeString(dtTableName.Rows[n]["Days"]));
            cells[n + 3, 7].PutValue(SafeValue.SafeString(dtTableName.Rows[n]["Remark2"]));
            cells[n + 3, 8].PutValue(SafeValue.SafeString(dtTableName.Rows[n]["BirthDay"]));
            cells[n + 3, 9].PutValue(SafeValue.SafeString(dtTableName.Rows[n]["Age"]));
            cells[n + 3, 10].PutValue(SafeValue.SafeString(dtTableName.Rows[n]["BeginDate"]));
            cells[n + 3, 11].PutValue(SafeValue.SafeString(dtTableName.Rows[n]["ServiceYears"]));
            cells[n + 3, 12].PutValue(SafeValue.SafeString(dtTableName.Rows[n]["ResignDate"]));
            cells[n + 3, 13].PutValue(SafeValue.SafeString(dtTableName.Rows[n]["IsCPF"]));
            cells[n + 3, 14].PutValue(SafeValue.SafeString(dtTableName.Rows[n]["Address"]));
            cells[n + 3, 15].PutValue(SafeValue.SafeString(dtTableName.Rows[n]["BankCode"]));
            cells[n + 3, 16].PutValue(SafeValue.SafeString(dtTableName.Rows[n]["AccNo"]));
            cells[n + 3, 17].PutValue(SafeValue.SafeString(dtTableName.Rows[n]["Salary"]));
            cells[n + 3, 18].PutValue(SafeValue.SafeString(dtTableName.Rows[n]["Account1"]));
            cells[n + 3, 19].PutValue(SafeValue.SafeString(dtTableName.Rows[n]["Account2"]));
            cells[n + 3, 20].PutValue(SafeValue.SafeString(dtTableName.Rows[n]["Account3"]));
            cells[n + 3, 21].PutValue(SafeValue.SafeString(dtTableName.Rows[n]["CPF1"]));
            cells[n + 3, 22].PutValue(SafeValue.SafeString(dtTableName.Rows[n]["CPF2"]));
            cells[n + 3, 23].PutValue(SafeValue.SafeString(dtTableName.Rows[n]["Account4"]));
            cells[n + 3, 24].PutValue(SafeValue.SafeString(dtTableName.Rows[n]["Account5"]));

            cells[n + 3, 0].SetStyle(style1);
            cells[n + 3, 1].SetStyle(style1);
            cells[n + 3, 2].SetStyle(style1);
            cells[n + 3, 3].SetStyle(style1);
            cells[n + 3, 4].SetStyle(style1);
            cells[n + 3, 5].SetStyle(style1);
            cells[n + 3, 6].SetStyle(style1);
            cells[n + 3, 7].SetStyle(style1);
            cells[n + 3, 8].SetStyle(style1);
            cells[n + 3, 9].SetStyle(style1);
            cells[n + 3, 10].SetStyle(style1);
            cells[n + 3, 11].SetStyle(style1);
            cells[n + 3, 12].SetStyle(style1);
            cells[n + 3, 13].SetStyle(style1);
            cells[n + 3, 14].SetStyle(style1);
            cells[n + 3, 15].SetStyle(style1);
            cells[n + 3, 16].SetStyle(style1);
            cells[n + 3, 17].SetStyle(style1);
            cells[n + 3, 18].SetStyle(style1);
            cells[n + 3, 19].SetStyle(style1);
            cells[n + 3, 20].SetStyle(style1);
            cells[n + 3, 21].SetStyle(style1);
            cells[n + 3, 22].SetStyle(style1);
            cells[n + 3, 23].SetStyle(style1);
            cells[n + 3, 24].SetStyle(style1);
        }

        string locaPath = MapPath("~/Excel");

        if (!Directory.Exists(locaPath))
        {
            Directory.CreateDirectory(locaPath);
        }
        string path0 = string.Format("~/Excel/Empolyee_{0:yyyyMMdd}.xlsx",
                                     DateTime.Now.ToString("yyyyMMdd-HHmmss") ?? "01-01-2014"); //Request.QueryString["d"]
        string path = HttpContext.Current.Server.MapPath(path0);                                //POD_RECORD

        //workbook.Save(path);

        System.IO.MemoryStream ms = workbook.SaveToStream(); //生成数据流
        byte[] bt = ms.ToArray();
        workbook.Save(path);
        Response.Redirect(path0.Substring(1));
    }
Esempio n. 55
0
        internal void LogLicenseStatus(LicenseStatus licenseStatus, ILog logger, License license, string developerLicenseUrl)
        {
            var whenLicenseExpiresPhrase          = GetRemainingDaysString(license.GetDaysUntilLicenseExpires());
            var whenUpgradeProtectedExpiresPhrase = GetRemainingDaysString(license.GetDaysUntilUpgradeProtectionExpires());

            switch (licenseStatus)
            {
            case LicenseStatus.Valid:
                break;

            case LicenseStatus.ValidWithExpiredUpgradeProtection:
                logger.Warn("Upgrade protection expired. In order for us to continue to provide you with support and new versions of the Particular Service Platform, contact us to renew your license: [email protected]");
                break;

            case LicenseStatus.ValidWithExpiringTrial:
                if (license.IsExtendedTrial)
                {
                    logger.Warn($"Development license expiring {whenLicenseExpiresPhrase}. If you’re still in development, renew your license for free at {developerLicenseUrl} otherwise email [email protected]");
                }
                else
                {
                    logger.Warn($"Trial license expiring {whenLicenseExpiresPhrase}. Get your free development license at {developerLicenseUrl}");
                }
                break;

            case LicenseStatus.ValidWithExpiringSubscription:
                logger.Warn($"License expiring {whenLicenseExpiresPhrase}. Contact us to renew your license: [email protected]");
                break;

            case LicenseStatus.ValidWithExpiringUpgradeProtection:
                logger.Warn($"Upgrade protection expiring {whenUpgradeProtectedExpiresPhrase}. Contact us to renew your license: [email protected]");
                break;

            case LicenseStatus.InvalidDueToExpiredTrial:
                if (license.IsExtendedTrial)
                {
                    logger.Error($"Development license expired. If you’re still in development, renew your license for free at {developerLicenseUrl} otherwise email [email protected]");
                }
                else
                {
                    logger.Error($"Trial license expired. Get your free development license at {developerLicenseUrl}");
                }
                break;

            case LicenseStatus.InvalidDueToExpiredSubscription:
                logger.Error("License expired. Contact us to renew your license: [email protected]");
                break;

            case LicenseStatus.InvalidDueToExpiredUpgradeProtection:
                logger.Error("Upgrade protection expired. In order for us to continue to provide you with support and new versions of the Particular Service Platform, contact us to renew your license: [email protected]");
                break;

            default:
                break;
            }

            string GetRemainingDaysString(int?remainingDays)
            {
                switch (remainingDays)
                {
                case null:
                    return("soon");

                case 0:
                    return("today");

                case 1:
                    return("in 1 day");

                default:
                    return($"in {remainingDays} days");
                }
            }
        }
        public void testCrearWord()
        {
            using (var streamLicencia = Assembly.GetExecutingAssembly().GetManifestResourceStream("TestAbaxXBRL.Aspose.Words.lic"))
            {
                if (streamLicencia != null)
                {
                    byte[] licBytes = null;
                    using (var br = new BinaryReader(streamLicencia))
                    {
                        licBytes = br.ReadBytes((int)streamLicencia.Length);
                    }
                    // Load the decrypted license into a stream and set the license.
                    var licenseStream = new MemoryStream(licBytes);
                    var license       = new License();
                    license.SetLicense(licenseStream);
                }
            }


            var variables = new Dictionary <string, string>();

            variables["tituloDeDocumento"] = "Reporte de Avance";
            variables["fecha"]             = DateTime.Now.ToLongDateString();
            variables["tituloDeDocumento"] = "Reporte de Avance";

            variables["etiqueta1"] = "Nombre";
            variables["etiqueta2"] = "Apellido Paterno";
            variables["etiqueta3"] = "Apellido Materno";

            variables["valor1"] = "Jose Juan";
            variables["valor2"] = "Morales";
            variables["valor3"] = "Perez";

            Document word = new Document(@"C:\temp\word\plantilla_1.docx");

            foreach (var llaveValor in variables)
            {
                word.Range.Replace("#" + llaveValor.Key, llaveValor.Value, false, false);
            }

            var docBuilder = new DocumentBuilder(word);

            docBuilder.MoveToDocumentEnd();

            var font = docBuilder.Font;

            font.Size = 8;
            font.Bold = true;
            font.Name = "Arial";

            docBuilder.Writeln("Campo Dinámico 1:");
            docBuilder.InsertParagraph();
            font.Bold = false;

            docBuilder.InsertHtml("<p style='font-family:Arial;font-size: 8pt'>" +
                                  File.ReadAllText(@"C:\temp\word\plantilla.html")
                                  + "</p>");
            docBuilder.InsertParagraph();
            docBuilder.Writeln("");

            word.Save(@"c:\temp\word\salida.pdf", new PdfSaveOptions()
            {
                UseHighQualityRendering = true
            });
        }
Esempio n. 57
0
        /// <summary>
        /// Validates the XML
        /// </summary>
        /// <param name="license">The license.</param>
        /// <returns>The validation context containing all the validation results.</returns>
        /// <exception cref="ArgumentException">The <paramref name="license" /> is <c>null</c> or whitespace.</exception>
        /// <exception cref="XmlException">The license text is not valid XML.</exception>
        /// <exception cref="Exception">The root element is not License.</exception>
        /// <exception cref="Exception">There were no inner nodes found.</exception>
        public IValidationContext ValidateXml(string license)
        {
            var validationContext = new ValidationContext();

            if (string.IsNullOrWhiteSpace(license))
            {
                validationContext.AddBusinessRuleValidationResult(BusinessRuleValidationResult.CreateError("No license available"));
            }

            var xmlDataList = new List <XmlDataModel>();

            try
            {
                var xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(license);
                var xmlRoot = xmlDoc.DocumentElement;
                if (!string.Equals(xmlRoot.Name, "License"))
                {
                    validationContext.AddBusinessRuleValidationResult(BusinessRuleValidationResult.CreateError("Please make sure that you pasted the complete license, including the <License> tags"));
                }

                var xmlNodes = xmlRoot.ChildNodes;
                foreach (XmlNode node in xmlNodes)
                {
                    if (!string.Equals(node.Name, "ProductFeatures"))
                    {
                        xmlDataList.Add(new XmlDataModel
                        {
                            Name  = node.Name,
                            Value = node.InnerText
                        });
                    }
                    else
                    {
                        foreach (XmlNode featureNode in node.ChildNodes)
                        {
                            xmlDataList.Add(new XmlDataModel
                            {
                                Name  = featureNode.Attributes[0].Value,
                                Value = featureNode.InnerText
                            });
                        }
                    }
                }

                if (xmlDataList.Count == 0)
                {
                    validationContext.AddBusinessRuleValidationResult(BusinessRuleValidationResult.CreateError("License contains no valid data"));
                }

                var expData = xmlDataList.FirstOrDefault(x => string.Equals(x.Name, LicenseElements.Expiration));
                if (expData != null)
                {
                    DateTime expirationDateTime;
                    if (DateTime.TryParse(expData.Value, out expirationDateTime))
                    {
                        Log.Debug("Using expiration behavior '{0}'", _expirationBehavior.GetType().Name);

                        var portableLicense = License.Load(license);

                        if (_expirationBehavior.IsExpired(portableLicense, expirationDateTime, DateTime.Now))
                        {
                            validationContext.AddBusinessRuleValidationResult(BusinessRuleValidationResult.CreateError("The license is expired"));
                        }
                    }
                    else
                    {
                        validationContext.AddBusinessRuleValidationResult(BusinessRuleValidationResult.CreateError("The expiration date was not a valid date / tim value"));
                    }
                }

                var xmlDataVersion = xmlDataList.FirstOrDefault(x => string.Equals(x.Name, LicenseElements.Version));
                if (xmlDataVersion != null)
                {
                    Version licenseVersion;
                    if (Version.TryParse(xmlDataVersion.Value, out licenseVersion))
                    {
                        var productVersion = Assembly.GetExecutingAssembly().GetName().Version;
                        if (productVersion > licenseVersion)
                        {
                            validationContext.AddBusinessRuleValidationResult(BusinessRuleValidationResult.CreateError("Your license only supports versions up to '{0}' while the current version of this product is '{1}'", licenseVersion, productVersion));
                        }
                    }
                    else
                    {
                        validationContext.AddBusinessRuleValidationResult(BusinessRuleValidationResult.CreateError("The version was not a valid version value"));
                    }
                }
            }
            catch (XmlException xmlex)
            {
                Log.Debug(xmlex);

                validationContext.AddBusinessRuleValidationResult(BusinessRuleValidationResult.CreateError("The license data is not a license"));
            }
            catch (Exception ex)
            {
                Log.Debug(ex);

                //var innermessage = string.Empty;
                //if (ex.InnerException != null)
                //{
                //    innermessage = ex.InnerException.Message;
                //}

                validationContext.AddBusinessRuleValidationResult(BusinessRuleValidationResult.CreateError(ex.Message));
            }

            if (validationContext.HasErrors || validationContext.HasWarnings)
            {
                Log.Warning("The XML is invalid");
            }
            return(validationContext);
        }
        protected override void Execute(CodeActivityContext executionContext)
        {
            try
            {
                EntityReference FirstAttachment  = FirstAttachmentId.Get(executionContext);
                EntityReference SecondAttachment = SecondAttachmentId.Get(executionContext);
                EntityReference Contact          = ContactId.Get(executionContext);
                string          Option           = OutputOption.Get(executionContext);
                Boolean         Logging          = EnableLogging.Get(executionContext);
                string          LicenseFilePath  = LicenseFile.Get(executionContext);

                if (Logging)
                {
                    Log("Workflow Executed");
                }

                // Create a CRM Service in Workflow.
                IWorkflowContext            context        = executionContext.GetExtension <IWorkflowContext>();
                IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
                IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

                if (Logging)
                {
                    Log("Executing Query to retrieve First Attachment");
                }

                Entity FirstNote = service.Retrieve("annotation", FirstAttachment.Id, new ColumnSet(new string[] { "subject", "documentbody" }));

                if (Logging)
                {
                    Log("First Attachment Retrieved Successfully");
                }
                if (Logging)
                {
                    Log("Executing Query to retrieve Second Attachment");
                }

                Entity SecondNote = service.Retrieve("annotation", SecondAttachment.Id, new ColumnSet(new string[] { "subject", "documentbody" }));

                if (Logging)
                {
                    Log("Second Attachment Retrieved Successfully");
                }

                MemoryStream fileStream1 = null, fileStream2 = null;
                string       FileName1 = "";
                string       FileName2 = "";
                if (FirstNote != null && FirstNote.Contains("documentbody"))
                {
                    byte[] DocumentBody = Convert.FromBase64String(FirstNote["documentbody"].ToString());
                    fileStream1 = new MemoryStream(DocumentBody);
                    if (FirstNote.Contains("filename"))
                    {
                        FileName1 = FirstNote["filename"].ToString();
                    }
                }
                if (SecondNote != null && SecondNote.Contains("documentbody"))
                {
                    byte[] DocumentBody = Convert.FromBase64String(SecondNote["documentbody"].ToString());
                    fileStream2 = new MemoryStream(DocumentBody);
                    if (SecondNote.Contains("filename"))
                    {
                        FileName2 = SecondNote["filename"].ToString();
                    }
                }
                try
                {
                    if (Logging)
                    {
                        Log("Enable Licensing");
                    }

                    if (LicenseFilePath != "" && File.Exists(LicenseFilePath))
                    {
                        Aspose.Words.License Lic = new License();
                        Lic.SetLicense(LicenseFilePath);
                        if (Logging)
                        {
                            Log("License Set");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log("Error while applying license: " + ex.Message);
                }

                if (Logging)
                {
                    Log("Merging Documents");
                }

                Document doc1 = new Document(fileStream1);
                Document doc2 = new Document(fileStream2);
                doc1.AppendDocument(doc2, ImportFormatMode.KeepSourceFormatting);

                if (Logging)
                {
                    Log("Merging Complete");
                }

                MemoryStream UpdateDoc = new MemoryStream();

                if (Logging)
                {
                    Log("Saving Document");
                }

                doc1.Save(UpdateDoc, SaveFormat.Docx);
                byte[] byteData = UpdateDoc.ToArray();

                // Encode the data using base64.
                string encodedData = System.Convert.ToBase64String(byteData);

                if (Logging)
                {
                    Log("Creating Attachment");
                }

                Entity NewNote = new Entity("annotation");

                // Add a note to the entity.
                NewNote.Attributes.Add("objectid", new EntityReference("contact", Contact.Id));

                // Set EncodedData to Document Body.
                NewNote.Attributes.Add("documentbody", encodedData);

                // Set the type of attachment.
                NewNote.Attributes.Add("mimetype", @"application\ms-word");
                NewNote.Attributes.Add("notetext", "Document Created using template");

                if (Option == "0")
                {
                    NewNote.Id = FirstNote.Id;
                    NewNote.Attributes.Add("subject", FileName1);
                    NewNote.Attributes.Add("filename", FileName1);
                    service.Update(NewNote);
                }
                else if (Option == "1")
                {
                    NewNote.Id = SecondNote.Id;
                    NewNote.Attributes.Add("subject", FileName2);
                    NewNote.Attributes.Add("filename", FileName2);
                    service.Update(NewNote);
                }
                else
                {
                    NewNote.Attributes.Add("subject", "Aspose .Net Document Merger");
                    NewNote.Attributes.Add("filename", "Aspose .Net Document Merger.docx");
                    service.Create(NewNote);
                }
                if (Logging)
                {
                    Log("Successfull");
                }
            }
            catch (Exception ex)
            {
                Log(ex.Message);
            }
        }
Esempio n. 59
0
        public void Test()
        {
            object lockObject = new object();

            //**DEFAULT CONTEXT & LicenseUsageMode**
            //Get CurrentContext, check default type
            Assert.AreEqual("System.ComponentModel.Design.RuntimeLicenseContext", LicenseManager.CurrentContext.GetType().ToString(), "LicenseManager #1");
            //Read default LicenseUsageMode, check against CurrentContext (LicCont).UsageMode
            Assert.AreEqual(LicenseManager.CurrentContext.UsageMode, LicenseManager.UsageMode, "LicenseManager #2");

            //**CHANGING CONTEXT**
            //Change the context and check it changes
            LicenseContext oldcontext = LicenseManager.CurrentContext;
            LicenseContext newcontext = new DesigntimeLicenseContext();

            LicenseManager.CurrentContext = newcontext;
            Assert.AreEqual(newcontext, LicenseManager.CurrentContext, "LicenseManager #3");
            //Check the UsageMode changed too
            Assert.AreEqual(newcontext.UsageMode, LicenseManager.UsageMode, "LicenseManager #4");
            //Set Context back to original
            LicenseManager.CurrentContext = oldcontext;
            //Check it went back
            Assert.AreEqual(oldcontext, LicenseManager.CurrentContext, "LicenseManager #5");
            //Check the UsageMode changed too
            Assert.AreEqual(oldcontext.UsageMode, LicenseManager.UsageMode, "LicenseManager #6");

            //**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.AreEqual(typeof(InvalidOperationException), e.GetType(), "LicenseManager #7");
                exceptionThrown = true;
            }
            //Check the exception was thrown
            Assert.AreEqual(true, exceptionThrown, "LicenseManager #8");
            //Check the context didn't change
            Assert.AreEqual(oldcontext, LicenseManager.CurrentContext, "LicenseManager #9");
            //Unlock it
            LicenseManager.UnlockContext(lockObject);
            //Now's unlocked, change it
            LicenseManager.CurrentContext = newcontext;
            Assert.AreEqual(newcontext, LicenseManager.CurrentContext, "LicenseManager #10");
            //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.AreEqual(typeof(ArgumentException), e.GetType(), "LicenseManager #11");
                exceptionThrown = true;
            }
            Assert.AreEqual(true, exceptionThrown, "LicenseManager #12");
            //Unlock it
            LicenseManager.UnlockContext(lockObject);

            //** bool IsValid(Type);
            Assert.AreEqual(true, LicenseManager.IsLicensed(typeof(UnlicensedObject)), "LicenseManager #13");
            Assert.AreEqual(true, LicenseManager.IsLicensed(typeof(LicensedObject)), "LicenseManager #14");
            Assert.AreEqual(false, LicenseManager.IsLicensed(typeof(InvalidLicensedObject)), "LicenseManager #15");

            Assert.AreEqual(true, LicenseManager.IsValid(typeof(UnlicensedObject)), "LicenseManager #16");
            Assert.AreEqual(true, LicenseManager.IsValid(typeof(LicensedObject)), "LicenseManager #17");
            Assert.AreEqual(false, LicenseManager.IsValid(typeof(InvalidLicensedObject)), "LicenseManager #18");

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

            //** bool IsValid(Type, object, License);
            License license = null;

            Assert.AreEqual(true, LicenseManager.IsValid(unlicensedObject.GetType(), unlicensedObject, out license), "LicenseManager #19");
            Assert.AreEqual(null, license, "LicenseManager #20");

            license = null;
            Assert.AreEqual(true, LicenseManager.IsValid(licensedObject.GetType(), licensedObject, out license), "LicenseManager #21");
            Assert.AreEqual("TestLicense", license.GetType().Name, "LicenseManager #22");

            license = null;
            Assert.AreEqual(false, LicenseManager.IsValid(invalidLicensedObject.GetType(), invalidLicensedObject, out license), "LicenseManager #23");
            Assert.AreEqual(null, license, "LicenseManager #24");

            //** 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.AreEqual(typeof(LicenseException), e.GetType(), "LicenseManager #25");
                exceptionThrown = true;
            }
            //Check the exception was thrown
            Assert.AreEqual(true, exceptionThrown, "LicenseManager #26");

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

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

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


            //** object CreateWithContext (Type, LicenseContext);
            object cwc = null;

            //Test we can create an unlicensed object with no context
            cwc = LicenseManager.CreateWithContext(typeof(UnlicensedObject), null);
            Assert.AreEqual("UnlicensedObject", cwc.GetType().Name, "LicenseManager #32");
            //Test we can create RunTime with CurrentContext (runtime)
            cwc = null;
            cwc = LicenseManager.CreateWithContext(typeof(RuntimeLicensedObject),
                                                   LicenseManager.CurrentContext);
            Assert.AreEqual("RuntimeLicensedObject", cwc.GetType().Name, "LicenseManager #33");
            //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.AreEqual(typeof(LicenseException), e.GetType(), "LicenseManager #34");
                exceptionThrown = true;
            }
            //Check the exception was thrown
            Assert.AreEqual(true, exceptionThrown, "LicenseManager #35");
            //Test we can create DesignTime with A new DesignTimeContext
            cwc = null;
            cwc = LicenseManager.CreateWithContext(typeof(DesigntimeLicensedObject),
                                                   new DesigntimeLicenseContext());
            Assert.AreEqual("DesigntimeLicensedObject", cwc.GetType().Name, "LicenseManager #36");

            //** 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.AreEqual("RuntimeLicensedObject", cwc.GetType().Name, "LicenseManager #37");
        }
Esempio n. 60
0
        public string LicenseBody => _license.Body.Substring(2); // First character must be NewLine

        public LicenseViewModel(License license)
        {
            _license = license;
        }