Beispiel #1
0
        private XmlDocument GetFormattedDocument(LicenseTemplate licenseTemplate, IList <LicenseSection> sections, IList <OrganizationLicenseClause> licenseClauses, IList <LicenseClause> clauses)
        {
            var document = new XmlDocument();

            document.LoadXml(licenseTemplate.LicenseText);
            var docSections = document.GetElementsByTagName(ClauseTagName);

            // Process clauses for each section
            foreach (var section in sections)
            {
                // Get clauses for this section
                var sectionClauses = clauses.Where(i => i.LicenseSectionID == section.ID).ToList();
                // Check if provider has clauses for section
                var licenseClausesForSection = new List <OrganizationLicenseClause>();
                foreach (var clause in sectionClauses)
                {
                    licenseClausesForSection.AddRange(licenseClauses.Where(o => o.LicenseClauseID == clause.ID));
                }
                // Skip if section was not selected
                if (!licenseClausesForSection.Any())
                {
                    continue;
                }
                foreach (var licenseClause in licenseClausesForSection)
                {
                    AddClauseToSection(docSections, section, licenseClause);
                }
            }
            return(document);
        }
Beispiel #2
0
 protected async Task GenerateLicenseTxt(CodeModelJs codeModel, GeneratorSettingsJs generatorSettings)
 {
     if (generatorSettings.GenerateLicenseTxt)
     {
         LicenseTemplate license = new LicenseTemplate {
             Model = codeModel
         };
         await Write(license, "LICENSE.txt").ConfigureAwait(false);
     }
 }
        /** Helper test methods **/

        private LicenseTemplate BuildLicenceTemplate(PublishStatus status = PublishStatus.Draft)
        {
            var licenseTemplate = new LicenseTemplate()
            {
                ID          = 0,
                Name        = "Test License",
                Description = "Test description.",
                CreatedAt   = DateTime.Now,
                Status      = (int)status,
                CreatedBy   = 0
            };

            return(licenseTemplate);
        }
        private void SetLicense(LicenseTemplate license)
        {
            if (null == license)
            {
                throw new ArgumentNullException(nameof(license));
            }

            licenseValueLabel.Text = license.LicenseName;

            if (null != license.LicenseUrl && CheckUrl(license.LicenseUrl))
            {
                licenseValueLabel.ForeColor = Color.Blue;
                licenseValueLabel.Font      = new Font(licenseValueLabel.Font, FontStyle.Underline);
                licenseValueLabel.Cursor    = Cursors.Hand;
                licenseValueLabel.Tag       = license.LicenseUrl;
            }
        }
Beispiel #5
0
        public static LicenseTemplateDetails ToModel(this LicenseTemplate licenseTemplate)
        {
            var result = new LicenseTemplateDetails();

            result.ID          = licenseTemplate.ID;
            result.LicenseId   = licenseTemplate.LicenseID;
            result.Name        = licenseTemplate.Name;
            result.Description = licenseTemplate.Description;
            result.Status      = (TemplateStatus)licenseTemplate.Status;
            result.CreatedAt   = licenseTemplate.CreatedAt;
            result.Version     = licenseTemplate.Version;
            result.IsActive    = licenseTemplate.Status == (int)TemplateStatus.Active;
            result.IsDraft     = licenseTemplate.Status == (int)TemplateStatus.Draft;
            result.IsRetracted = licenseTemplate.Status == (int)TemplateStatus.Retracted;

            return(result);
        }
        /// <summary>
        /// Create new license template from model
        /// </summary>
        /// <param name="model"></param>
        private void CreateLicenseTemplate(LicenseTemplateDetails model, byte[] file, LoggedInUserDetails user)
        {
            var licenseTemplate = new LicenseTemplate();

            UpdateSectionsFromTemplateFile(file, user);
            if (model.IsActive)
            {
                licenseTemplate.Version += 1;
            }
            else
            {
                licenseTemplate.Version = 1;
            }
            // Setup license details
            licenseTemplate.LicenseID   = model.LicenseId;
            licenseTemplate.LicenseText = model.LicenseText;
            licenseTemplate.Status      = (int)PublishStatus.Draft;
            licenseTemplate.Name        = model.Name;
            licenseTemplate.Description = string.IsNullOrEmpty(model.Description) ? string.Empty : model.Description;
            licenseTemplate.UpdatedAt   = GetDate;
            licenseTemplate.UpdatedBy   = user.ID;
            licenseTemplate.CreatedAt   = GetDate;
            licenseTemplate.CreatedBy   = user.ID.Value;
            // Create new license if no licenses
            // ??? What is the purpose of generic licenses
            var globalLicense = _genericLicenses.All().FirstOrDefault();

            if (globalLicense == null)
            {
                var license = new License
                {
                    CreatedBy = user.ID.Value,
                    CreatedAt = GetDate,
                };
                _genericLicenses.Add(license);
                licenseTemplate.LicenseID = license.ID;
            }
            else
            {
                // We have only one published license
                licenseTemplate.LicenseID = globalLicense.ID;
            }
            // Add new license
            _templates.Add(licenseTemplate);
        }
Beispiel #7
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);
        }
Beispiel #8
0
        public void Init()
        {
            sysAdmin = new User
            {
                Email          = "*****@*****.**",
                ID             = 1,
                IsActive       = true,
                IsSysAdmin     = true,
                OrganizationID = 2
            };

            otherOrganization = new Organization
            {
                ID       = 3,
                Name     = "OrgName3",
                IsActive = true
            };

            user = new User
            {
                Email          = "*****@*****.**",
                ID             = 2,
                IsSysAdmin     = false,
                OrganizationID = 2
            };

            otherUser = new User
            {
                Email          = "*****@*****.**",
                ID             = 3,
                IsSysAdmin     = false,
                OrganizationID = otherOrganization.ID
            };

            organization = new Organization
            {
                ID       = 2,
                Name     = "OrgName2",
                IsActive = true
            };


            activeService = new Application
            {
                OrganizationID             = organization.ID,
                IsActive                   = true,
                Name                       = "activeService",
                PublicID                   = new Guid("421befd1-ef28-4c25-bcf6-5ead09dabb71"),
                ID                         = 1,
                IsIntroducedAsIndustryGood = true,
                IsProvider                 = true
            };

            consumerApplication = new Application
            {
                OrganizationID = 2,
                IsActive       = true,
                Name           = "active applications",
                PublicID       = new Guid("421befd1-ef28-4c25-bcf6-5ead09dabb71"),
                ID             = 4,
                IsProvider     = false
            };

            notActiveService = new Application
            {
                OrganizationID = 2,
                IsActive       = false,
                Name           = "notActiveService",
                PublicID       = new Guid("421befd1-ef28-4c25-bcf6-5ead09dabb71"),
                ID             = 2,
                IsProvider     = false
            };

            otherService = new Application
            {
                OrganizationID = 3,
                IsActive       = true,
                Name           = "otherService",
                PublicID       = new Guid("421befd1-ef28-4c25-bcf6-5ead09dabb71"),
                ID             = 3,
                IsProvider     = false
            };

            dataSchema = new DataSchema
            {
                ID   = 1,
                Name = "Schema1"
            };

            providerEndpoint = new ProviderEndpoint
            {
                ApplicationId  = activeService.ID,
                ID             = 1,
                DataSchemaID   = dataSchema.ID,
                IsIndustryGood = true,
                Description    = "Description"
            };

            licenseTemplate = new LicenseTemplate
            {
                ID        = 1,
                LicenseID = 1,
                Status    = (int)TemplateStatus.Active
            };

            _organizationLicense = new OrganizationLicense
            {
                ID                 = 1,
                Status             = (int)PublishStatus.Published,
                ProviderEndpointID = providerEndpoint.ID,
                DataSchemaID       = providerEndpoint.DataSchemaID,
                LicenseTemplateID  = licenseTemplate.ID
            };
            applicationToken = new ApplicationToken
            {
                ID            = 1,
                ApplicationID = activeService.ID,
                Token         = "token"
            };

            appService                       = new Mock <IApplicationsService>();
            _userService                     = new Mock <IUserService>();
            orgService                       = new Mock <IOrganizationService>();
            schemaService                    = new Mock <IDataSchemaService>();
            endpointService                  = new Mock <IProviderEndpointService>();
            licenseTemplateService           = new Mock <ILicenseTemplatesService>();
            sectionService                   = new Mock <ILicenseSectionService>();
            clauseService                    = new Mock <ILicenseClauseService>();
            clauseTemplateService            = new Mock <ILicenseClauseTemplateService>();
            endpointLicClauseService         = new Mock <IOrganizationLicenseClauseService>();
            licenseService                   = new Mock <IOrganizationLicenseService>();
            notificationService              = new Mock <INotificationService>();
            applicationTokenService          = new Mock <IService <ApplicationToken> >();
            applicationAuthenticationService = new Mock <IService <ApplicationAuthentication> >();
            configService                    = new Mock <IConfigurationService>();
            licenseContentBuilder            = new Mock <ILicenseContentBuilder>();
            adminNotificationService         = new Mock <IAdminNotificationService>();
            // Notification service
            notificationService.Setup(i => i.Admin).Returns(adminNotificationService.Object);
            configService.SetupProperty(p => p.ManageApplicationsPageSize, 5);
            var mockUrl = new Mock <UrlHelper>();

            // Setup application token service
            applicationTokenService.Setup(i => i.Get(applicationToken.ID)).Returns(applicationToken);
            applicationTokenService.Setup(i => i.Add(It.IsAny <ApplicationToken>())).Returns(true);
            applicationTokenService.Setup(i => i.Update(It.IsAny <ApplicationToken>())).Returns(true);
            // Schema service
            schemaService.Setup(p => p.Get(dataSchema.ID)).Returns(dataSchema);
            schemaService.Setup(p => p.Get(10)).Returns(new DataSchema {
                ID = 10, IsIndustryGood = false
            });
            schemaService.Setup(p => p.GetPublishedSchemas()).Returns(new List <DataSchema> {
                dataSchema, new DataSchema {
                    ID = 10, IsIndustryGood = false
                }
            });

            // Endpoint service
            endpointService.Setup(p => p.Get(It.IsAny <Expression <Func <ProviderEndpoint, bool> > >()))
            .Returns(new List <ProviderEndpoint> {
                providerEndpoint
            });
            endpointService.Setup(p => p.Get(providerEndpoint.ID)).Returns(providerEndpoint);

            licenseService.Setup(p => p.Get(It.IsAny <Expression <Func <OrganizationLicense, bool> > >()))
            .Returns(new List <OrganizationLicense> {
                _organizationLicense
            });

            // License template service
            licenseTemplateService.Setup(p => p.GetAll(false)).Returns(new List <LicenseTemplate> {
                licenseTemplate
            });
            licenseTemplateService.Setup(p => p.GetPublishedGlobalLicense()).Returns(licenseTemplate);

            // Application service
            appService.Setup(p => p.GetApplicationsFor((int)user.OrganizationID))
            .Returns(new List <Application> {
                activeService, notActiveService
            });
            appService.Setup(p => p.GetAllApplications())
            .Returns(new List <Application> {
                activeService, otherService, notActiveService
            });
            appService.Setup(p => p.Get(activeService.ID)).Returns(activeService);
            appService.Setup(p => p.Get(notActiveService.ID)).Returns(notActiveService);
            appService.Setup(p => p.Get(otherService.ID)).Returns(otherService);
            appService.Setup(p => p.Get(consumerApplication.ID)).Returns(consumerApplication);
            appService.Setup(p => p.GetAuthenticationFor(activeService.ID)).Returns(new ApplicationAuthentication());

            // Organization service
            orgService.Setup(p => p.Get(organization.ID)).Returns(organization);
            orgService.Setup(p => p.Get(otherOrganization.ID)).Returns(otherOrganization);

            var context = new Mock <ControllerContext>();

            context.Setup(m => m.HttpContext.Request.Form).Returns(new FormCollection());
            context.Setup(m => m.HttpContext.Request.Url).Returns(new Uri("http://test.com"));
            context.Setup(m => m.HttpContext.Request.Browser).Returns(new Mock <HttpBrowserCapabilitiesBase>().Object);

            controller = new ApplicationsController(appService.Object, applicationTokenService.Object,
                                                    applicationAuthenticationService.Object, _userService.Object,
                                                    orgService.Object, schemaService.Object, endpointService.Object,
                                                    licenseService.Object, configService.Object,
                                                    notificationService.Object);
            controller.ControllerContext = context.Object;
            controller.Url = mockUrl.Object;
        }
        /// <summary>
        /// Update existing license templates from model
        /// </summary>
        /// <param name="model"></param>
        private void UpdateLicenseTemplate(LicenseTemplateDetails model, byte[] file, LicenseTemplate licenseTemplate, LoggedInUserDetails user)
        {
            if (licenseTemplate == null)
            {
                throw new BaseException("License template with such Id was not found");
            }

            // Return error if license is retracted
            if (licenseTemplate.Status == (int)TemplateStatus.Retracted)
            {
                throw new BaseException("Retracted license can't be processed");
            }

            // Process attached license file
            UpdateSectionsFromTemplateFile(file, user);

            // Setup license details
            licenseTemplate.Name        = model.Name;
            licenseTemplate.LicenseText = model.LicenseText;
            licenseTemplate.Description = model.Description;
            licenseTemplate.UpdatedAt   = GetDate;
            licenseTemplate.UpdatedBy   = user.ID;
            licenseTemplate.Version    += 1;
            // Save changes
            _templates.Update(licenseTemplate);
        }
Beispiel #10
0
        /// <summary>
        /// Updates license template properties. See NetLicensingAPI JavaDoc for details:
        /// http://netlicensing.labs64.com/javadoc/v2/com/labs64/netlicensing/core/service/LicenseTemplateService.html
        /// </summary>
        public static LicenseTemplate update(Context context, String number, LicenseTemplate updateLicenseTemplate)
        {
            netlicensing output = NetLicensingAPI.request(context, NetLicensingAPI.Method.POST, Constants.LicenseTemplate.ENDPOINT_PATH + "/" + number, updateLicenseTemplate.ToDictionary());

            return(new LicenseTemplate(output.items.item[0]));
        }
Beispiel #11
0
        /// <summary>
        /// Creates new license template object with given properties. See NetLicensingAPI JavaDoc for details:
        /// http://netlicensing.labs64.com/javadoc/v2/com/labs64/netlicensing/core/service/LicenseTemplateService.html
        /// </summary>
        public static LicenseTemplate create(Context context, String productModuleNumber, LicenseTemplate newLicenseTemplate)
        {
            newLicenseTemplate.productModuleNumber = productModuleNumber;
            netlicensing output = NetLicensingAPI.request(context, NetLicensingAPI.Method.POST, Constants.LicenseTemplate.ENDPOINT_PATH, newLicenseTemplate.ToDictionary());

            return(new LicenseTemplate(output.items.item[0]));
        }
Beispiel #12
0
        /// <summary>
        /// Create the License key.
        /// </summary>
        /// <example>
        /// <code>
        /// gkey = new Key();
        /// gkey.LicenseTemplate = "vvvvppppxxxxxxxxxxxx-wwwwwwwwxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxx";
        /// gkey.MaxTokens = 3;
        /// gkey.AddToken(0, "v", LicenseKey.Key.TokenTypes.NUMBER, "1");
        /// gkey.AddToken(1, "p", LicenseKey.Key.TokenTypes.NUMBER, "2");
        /// gkey.AddToken(2, "w", LicenseKey.Key.TokenTypes.CHARACTER, "QR");
        /// gkey.UseBase10 = false;
        /// gkey.UseBytes = false;
        /// gkey.<b>CreateKey</b>();
        /// finalkey = gkey.GetLicenseKey();
        /// </code>
        /// </example>
        /// <exception cref="System.ApplicationException">Thrown when no key template has been entered.</exception>
        /// <exception cref="System.ApplicationException">Thrown when no the Tokens is not found in input list.</exception>
        /// <returns>None</returns>
        public string CreateKey()
        {
            //
            // Initialize the finalkey so we do not reuse it.
            //
            _strLicensekey = string.Empty;
            //
            // Check the length of the template string
            //
            if (LicenseTemplate.Length == 0)
            {
                // throw a exception that the user can understand.
                throw new ApplicationException("Enter a key template");
            }
            //
            // if a token is in the license string then make sure it fits into it's field for size.
            // make sure it is as large as what is entered in the tempate string
            //
            foreach (var token in _tokens)
            {
                token.Datatype.CheckToken(LicenseTemplate, token.InitialValue, token.CharacterToken);
            }

            // initialize the variables.
            var slast = '\0';
            var scnt  = 0;

            // now go through the license template to see what tokens are found.
            // fill in the license key string now that we know everything will fit.

            foreach (var stok in LicenseTemplate.ToCharArray())
            {
                if (stok != slast)
                {
                    if (scnt != 0)
                    {
                        GetToken(slast, scnt);
                        scnt = 1;
                    }
                    else
                    {
                        scnt++;
                    }
                }
                else
                {
                    scnt++;
                }
                slast = stok;
            }

            //
            // handle anything that was left over.
            //
            if (scnt != 0)
            {
                GetToken(slast, scnt);
            }

            return(_strLicensekey);
        }
Beispiel #13
0
        static int Main(string[] args)
        {
            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

                string privateKey      = @"-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC7mCuhtyeM+HM6
/IbTkM45bpKVQgpruiaEksheXwPx+iG4dRpkugYDYWi3g4/+oVKDQMrh6BsJtT6k
Otqwy8q81MIzPDTKnNvIERphKbrC0R5TjmmlrCPQeM6Hc1GnYOzSFHzFIwoVFz/h
3zuGySPKMpc6qg5mGqNfBiTuhwh7oAM+kXhgKzl5jj/cIvUmci12UpBGyXxknRip
75+KB/1qAJa9DQ7R9pF2aCavt5SFT1pc29IlpUlduDpOOGHFW6PN6EXyyH/uzGAb
CpvK6cTXk5ajp0CtELI1R5E6770mni0RP7ZED8+6pBtZboRslYGGmSo13OL0Ji6G
5SO+TyZ3AgMBAAECggEBAItqwjKDbg9kri7Ocl1Vpw4j0SjAVgJN7EZm2CbaspHp
dZoi3aSyY7mrcSnBywhQWIRXaPCPkVibrJxdaR4vttKzxEhTnGBgRy7fFx3S54vV
4pXypy2LS2qp/cPIvoyIijhvJXNVYS7fgoiZYSIA5mplQuNEc0MK1RPP+y6SiIlm
0SEXUXl5OYn3AGQ6hJJXxbN36kOtcwb33C/cY3b9jPl1acAVk84dFl0aAv92ArST
PahsxQDbRDaDxZ/lfk1mZqPexiWorAZWMck8nOyZhKu5/oXy6OcXfqVjdwmlqY05
hNS7mxSOUy+7umqbcV/bdhvqMJr+DeI1vqQS5J+t3vECgYEA8GZ6oxUiuwYJ98jS
Nx+i7Jj+ZTEFJ7WiepX5mOU13GlS0vAvhPdK9juEYbS7Znpp35WgwxuPsCn9hXIO
gjR0eSYN7QB5RVn7zjo+SQRw2C+HAt7G/wazq3ekSdNgKe8+Wa7YxLL8ypaOy1me
7L4JQGgM6ORgnYH/+BC7P/KO80MCgYEAx8R7W2Fzo1I+RPfKQeVQ/i4a+/DMK0js
XhpkMh/8NXbdHYNDdsQTQ2E8V+5gNi+zCqMuwIxA8cx9lAL32x1fMWnbHV9YwSFZ
ZOEG/YFyqcBOtQztt8jHGtXN70FQdwSwqcFdntNTCjJquN2gX1n2qFR2bezcULaj
Iiyc/j3AWr0CgYBQmbtidFKpq/OpnS5GBxhkBUO9/7p/vtlUCnad+bOeS73WNWtp
RFRgzEGtVKBEUqSurwcwg0wgv2Nd24jbxOSMPeMLZE5En0/arBJ3/sIq6Xx1zOWh
Wcjho4J0sicayDj6brIE+RHihqonqcusCmclrf0uFGwEQzLkJA/z98pP6wKBgAti
iEE5+ZQqQMA/evhscEQ8Lm+DVq901Xu7d1BgAEivwIRJEdQ38n0Zko3UWQldiI+n
oyd4Fs9w/wsrbCLBtsYjKUiwQWeoVebo6DQUZ4uDGTk6RmX9/FLsMnNbPpG547OZ
AJPnqUjgfLKSduxYPTV0stcq85dqATwWXNAkhszlAoGBAOKLU6IKuiRLcOrVon/a
KlXkjBMP2EkTVhuIzgZp6v7P8LK+UfU/6vkJvBW5U9ZosS7f13t7/bJ0AzfJLW6m
J1IedEJExbLmuW7+HfEMyZ5g8dFJZvYBmN/zHQEhFUKDISDI2O2gmd9cPPsMnOxW
WW8VMSYMi1Wtb9v7eRPvRZlE
-----END PRIVATE KEY-----";
                string publicKey       = @"-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAu5grobcnjPhzOvyG05DO
OW6SlUIKa7omhJLIXl8D8fohuHUaZLoGA2Fot4OP/qFSg0DK4egbCbU+pDrasMvK
vNTCMzw0ypzbyBEaYSm6wtEeU45ppawj0HjOh3NRp2Ds0hR8xSMKFRc/4d87hskj
yjKXOqoOZhqjXwYk7ocIe6ADPpF4YCs5eY4/3CL1JnItdlKQRsl8ZJ0Yqe+figf9
agCWvQ0O0faRdmgmr7eUhU9aXNvSJaVJXbg6TjhhxVujzehF8sh/7sxgGwqbyunE
15OWo6dArRCyNUeROu+9Jp4tET+2RA/PuqQbWW6EbJWBhpkqNdzi9CYuhuUjvk8m
dwIDAQAB
-----END PUBLIC KEY-----";
                string publicKey_wrong = @"-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtq96itv1m00/czFD7IzE
mLiXPpvok1vjqB9VU6kTkq6QFGAfJF1G+m1fbK5NvpiDCsfuofdCFuhVnvLnzrpd
xUlse8erWEr9p9RAyh25NMK9/v0MAEAYV7zRa+ZOh31G54DwR7zk0TxyVzxKpjPi
wQSnv7UCY/IR7remLIYO92K7jAg9ZB4IHTuVulCtSrSQajZ8Ep2rFGPr8OeTsj9c
rBPpmL/ShdJOnL4NR0UnVWSpsCFW6wEqNafcUWnWpb98V49/p7fWDFJ1Tg6+OlVg
lgsNrqrqwJpxDLKnGAkkxHaVxSnZzAYh+HP8CbJmbzzE1GRXNgy3w+smWMv6M996
9wIDAQAB
-----END PUBLIC KEY-----";
                Console.WriteLine("loaded privateKey: {0}", privateKey);
                Console.WriteLine("loaded publicKey: {0}", publicKey);
                Console.WriteLine("loaded publicKey_wrong: {0}", publicKey_wrong);

                //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;
                newToken.tokenProperties.Add(Constants.Token.TOKEN_PROP_PRIVATE_KEY, privateKey);
                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 = null;

                // Validate using Basic Auth
                context.securityMode = SecurityMode.BASIC_AUTHENTICATION;
                validationResult     = LicenseeService.validate(context, demoLicenseeNumber, validationParameters);
                ConsoleWriter.WriteEntity("Validation result (Basic Auth):", validationResult);

                OSPlatform operatingSystem = GetOperatingSystem();
                Console.WriteLine("operatingSystem: {0}", operatingSystem);

                // Verify signature on Linux or OSX only
                // TODO: https://github.com/Labs64/NetLicensingClient-csharp/issues/25
                if (operatingSystem.Equals(OSPlatform.Linux) || operatingSystem.Equals(OSPlatform.OSX))
                {
                    // Validate using APIKey
                    context.securityMode = SecurityMode.APIKEY_IDENTIFICATION;
                    validationResult     = LicenseeService.validate(context, demoLicenseeNumber, validationParameters);
                    ConsoleWriter.WriteEntity("Validation result (APIKey):", validationResult);

                    // Validate using APIKey signed
                    context.securityMode = SecurityMode.APIKEY_IDENTIFICATION;
                    context.publicKey    = publicKey;
                    validationResult     = LicenseeService.validate(context, demoLicenseeNumber, validationParameters);
                    ConsoleWriter.WriteEntity("Validation result (APIKey / signed):", validationResult);

                    // Validate using APIKey wrongly signed
                    context.securityMode = SecurityMode.APIKEY_IDENTIFICATION;
                    context.publicKey    = publicKey_wrong;
                    try
                    {
                        validationResult = LicenseeService.validate(context, demoLicenseeNumber, validationParameters);
                    }
                    catch (NetLicensingException e)
                    {
                        Console.WriteLine("Validation result exception (APIKey / wrongly signed): {0}", e);
                    }
                }

                // Reset context for futher use
                context.securityMode = SecurityMode.BASIC_AUTHENTICATION;
                context.publicKey    = null;

                #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 APIKey in case this 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);
        }
Beispiel #14
0
        public XmlDocument GetDocument(List <SectionsWithClauses> model, int schemaId, int organizationId, LicenseTemplate licenseTemplate, string urlToDataLinker, string urlToDownloadSchema)
        {
            var document = new XmlDocument();

            document.LoadXml(licenseTemplate.LicenseText);
            var docSections = document.GetElementsByTagName(ClauseTagName);

            foreach (var section in model)
            {
                // Skip not selected section
                if (!_licenseClauseService.IsClauseSelected(section))
                {
                    continue;
                }

                var selectedClause = section.Clauses.First(p => p.ClauseTemplateId == section.SelectedClause);
                var clauseTemplate = _clauseTemplates.FirstOrDefault(i => i.ID == selectedClause.ClauseTemplateId);

                switch ((ClauseType)selectedClause.Type)
                {
                case ClauseType.Text:
                {
                    InsertContentIntoNodes(docSections, section.Section.Title,
                                           clauseTemplate.LegalText);
                    break;
                }

                case ClauseType.Input:
                {
                    var input = selectedClause;
                    var indexOfOpenBracket = clauseTemplate.LegalText.IndexOf('{');
                    var temp = new string(clauseTemplate.LegalText.Where(p => p != '{' && p != '}').ToArray());
                    temp = temp.Insert(indexOfOpenBracket, input.InputValue ?? string.Empty);
                    InsertContentIntoNodes(docSections, section.Section.Title,
                                           temp);
                    break;
                }

                case ClauseType.InputAndDropDown:
                {
                    var inputAndDropDown     = selectedClause;
                    var indexOfOpenBracket   = clauseTemplate.LegalText.IndexOf('{');
                    var index2OfOpenBracket  = clauseTemplate.LegalText.LastIndexOf('{');
                    var index2OfCloseBracket = clauseTemplate.LegalText.LastIndexOf('}');
                    // remove dropdown list items from text
                    var temp = clauseTemplate.LegalText.Remove(index2OfOpenBracket,
                                                               index2OfCloseBracket - index2OfOpenBracket + 1);
                    // Insert DropDown selected value into a brackets location
                    temp = temp.Insert(index2OfOpenBracket, inputAndDropDown.SelectedItem);
                    // Remove all brackets
                    temp = new string(temp.Where(p => p != '{' && p != '}').ToArray());
                    temp = temp.Insert(indexOfOpenBracket, inputAndDropDown.InputValue);
                    InsertContentIntoNodes(docSections, section.Section.Title,
                                           temp);
                    break;
                }

                default:
                    throw new BaseException("Unknown clause type");
                }
            }
            // Get schema file
            var schemaFile = _schemaFileService.FirstOrDefault(i => i.DataSchemaID == schemaId);

            // Setup url to schema
            InsertLicenseDetails(document, urlToDownloadSchema, urlToDataLinker, organizationId, isProvider: true);

            // Return result
            return(document);
        }
Beispiel #15
0
        public void Init()
        {
            var today = DateTime.Now;

            userSysAdmin = new User
            {
                ID             = 2,
                OrganizationID = 1,
                IsActive       = true,
                Email          = "*****@*****.**",
                IsSysAdmin     = true,
            };

            user = new User
            {
                ID             = 3,
                IsActive       = true,
                Email          = "*****@*****.**",
                IsSysAdmin     = false,
                OrganizationID = null,
            };

            sectionA = new LicenseSection
            {
                ID        = 1,
                CreatedBy = user.ID,
                Title     = "sectionA"
            };

            sectionB = new LicenseSection
            {
                ID        = 2,
                CreatedBy = user.ID,
                Title     = "sectionB"
            };

            sectionC = new LicenseSection
            {
                ID        = 3,
                CreatedBy = user.ID,
                Title     = "sectionC"
            };

            licenseTemplate = new LicenseTemplate
            {
                ID        = 1,
                CreatedAt = today,
                CreatedBy = 1,
                Status    = (int)TemplateStatus.Active,
                Name      = "titleLicense"
            };

            clauseTemplateDraft = new LicenseClauseTemplate
            {
                ID              = 1,
                Status          = (int)TemplateStatus.Draft,
                Description     = "Descr",
                LegalText       = "text",
                ShortText       = "shortText",
                LicenseClauseID = 1,
                Version         = 1
            };

            clauseTemplateActive = new LicenseClauseTemplate
            {
                ID          = 2,
                Status      = (int)TemplateStatus.Active,
                Description = "Descr",
                LegalText   = "text",
                ShortText   = "shortText",
                Version     = 1
            };

            clause1SectionA = new LicenseClause
            {
                ID               = 1,
                OrderNumber      = 0,
                LicenseSectionID = sectionA.ID
            };

            clause2SectionA = new LicenseClause
            {
                ID               = 2,
                OrderNumber      = 0,
                LicenseSectionID = sectionA.ID
            };

            clause1SectionB = new LicenseClause
            {
                ID               = 3,
                OrderNumber      = 0,
                LicenseSectionID = sectionA.ID
            };

            var fileMock = new Mock <HttpPostedFileBase>();

            _clauseService          = new Mock <ILicenseClauseService>();
            _clauseTemplateService  = new Mock <ILicenseClauseTemplateService>();
            _sectionService         = new Mock <ILicenseSectionService>();
            organizationService     = new Mock <IOrganizationService>();
            userService             = new Mock <IUserService>();
            licenseTemplateService  = new Mock <ILicenseTemplatesService>();
            userNotificationService = new Mock <IUserNotificationService>();
            notificationService     = new Mock <INotificationService>();
            // Setup notification service
            notificationService.SetupGet(m => m.User).Returns(userNotificationService.Object);
            var urlHelper = new Mock <UrlHelper>();

            context = new Mock <ControllerContext>();
            context.Setup(m => m.HttpContext.Request.Files.Count).Returns(1);
            context.Setup(m => m.HttpContext.Request.Files[0]).Returns(fileMock.Object);

            _sectionService.Setup(m => m.GetAll()).Returns(new List <LicenseSection> {
                sectionA, sectionB, sectionC
            });
            _sectionService.Setup(m => m.Get(sectionA.ID)).Returns(sectionA);
            _sectionService.Setup(m => m.Get(sectionB.ID)).Returns(sectionB);
            _sectionService.Setup(m => m.Get(sectionC.ID)).Returns(sectionC);

            _clauseService.Setup(m => m.Get(It.IsAny <Expression <Func <LicenseClause, bool> > >()))
            .Returns(new List <LicenseClause> {
                clause1SectionA, clause2SectionA
            });
            _clauseService.Setup(i => i.Get(clause1SectionA.ID)).Returns(clause1SectionA);

            _clauseTemplateService.Setup(m => m.Get(It.IsAny <Expression <Func <LicenseClauseTemplate, bool> > >()))
            .Returns(new List <LicenseClauseTemplate> {
                clauseTemplateDraft
            });
            _clauseTemplateService.Setup(m => m.Get(clauseTemplateDraft.ID)).Returns(clauseTemplateDraft);
            _clauseTemplateService.Setup(m => m.Get(clauseTemplateActive.ID)).Returns(clauseTemplateActive);

            licenseTemplateService.Setup(m => m.GetPublishedGlobalLicense()).Returns(licenseTemplate);

            controller = new LicenseClausesController(_clauseService.Object, _sectionService.Object,
                                                      _clauseTemplateService.Object, userService.Object, organizationService.Object,
                                                      licenseTemplateService.Object, notificationService.Object)
            {
                LoggedInUser      = new LoggedInUserDetails(userSysAdmin),
                Url               = urlHelper.Object,
                ControllerContext = context.Object
            };
        }
Beispiel #16
0
        static void Main(string[] args)
        {
            // ServicePointManager.ServerCertificateValidationCallback = delegate { return true;  // Trust any (self-signed) certificate };

            Context context = new Context();

            context.baseUrl      = "https://netlicensing.labs64.com";
            context.username     = "******";
            context.password     = "******";
            context.securityMode = SecutiryMode.BASIC_AUTHENTICATION;

            String  demoProductNumber              = "P001demo";
            String  demoProductModuleNumber        = "M001demo";
            String  demoLicensingModel             = "TimeLimitedEvaluation";
            String  demoLicenseTemplate1_Number    = "E001demo";
            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             = "I001demo";
            String  demoLicenseNumber              = "L001demoTV";

            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 license templates:", licenses);

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

                licenses = LicenseService.list(context, null);
                ConsoleWriter.WriteList("Got the following license templates:", 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

                Token newToken = new Token();
                newToken.tokenType = Constants.Token.TYPE_APIKEY;
                Token apiKey = TokenService.create(context, newToken);
                ConsoleWriter.WriteEntity("Created API Key:", apiKey);
                context.apiKey = apiKey.number;

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

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

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

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

                #endregion

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

                ValidationResult validationResult = LicenseeService.validate(context, demoLicenseeNumber, demoProductNumber);
                ConsoleWriter.WriteEntity("Validation result for created licensee:", validationResult);

                context.securityMode = SecutiryMode.APIKEY_IDENTIFICATION;
                validationResult     = LicenseeService.validate(context, demoLicenseeNumber, demoProductNumber);
                context.securityMode = SecutiryMode.BASIC_AUTHENTICATION;
                ConsoleWriter.WriteEntity("Validation repeated with API Key:", validationResult);

                #endregion
            }
            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 = SecutiryMode.BASIC_AUTHENTICATION;
                    // deactivate api key
                    TokenService.deactivate(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);
                }
            }

            Console.WriteLine("Press <Enter> to exit...");
            Console.ReadLine();
        }