コード例 #1
0
        public void AllCultures()
        {
            var original = CultureInfo.DefaultThreadCurrentCulture;

            try
            {
                var cultures = new[]
                {
                    "en-US",
                    "ru-RU"
                };

                foreach (var c in cultures)
                {
                    var ci = new CultureInfo(c);
                    CultureInfo.DefaultThreadCurrentCulture = ci;
                    Thread.CurrentThread.CurrentUICulture   = ci;

                    foreach (var key in FailureStrings.GetKeys().Where(x => x.EndsWith("Code")))
                    {
                        var actual = FailureStrings.Get(key);

                        Assert.NotNull(actual);
                    }
                }
            }
            finally
            {
                CultureInfo.DefaultThreadCurrentCulture = original;
            }
        }
コード例 #2
0
 public void GetFailureThrowsIfKeyNotFoundTest()
 {
     Assert.Throws <InvalidOperationException>(() =>
     {
         var actual = FailureStrings.Get("Fake");
     });
 }
コード例 #3
0
        public void GetFailureTest()
        {
            var actual = FailureStrings.Get(FailureStrings.ACT00Code);

            Assert.Equal("ACT.00", actual.Code);
            Assert.Equal("Activation failed.", actual.Message);
            Assert.Equal("Your product is having trouble connecting with License servers.", actual.HowToResolve);
        }
コード例 #4
0
        public void AllKeysValid()
        {
            foreach (var key in FailureStrings.GetKeys().Where(x => x.EndsWith("Code")))
            {
                var actual = FailureStrings.Get(key);

                Assert.NotNull(actual);
            }
        }
コード例 #5
0
        public async Task <LicenseRegisterResult> CreateAsync(LicenseRegisterRequest request, string userName)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            if (string.IsNullOrWhiteSpace(userName))
            {
                throw new ArgumentNullException(nameof(userName));
            }

            try
            {
                _logger.LogDebug(JsonSerializer.Serialize(request));

                var failure = await ValidateAsync(request);

                if (failure != null)
                {
                    return(new LicenseRegisterResult
                    {
                        Failure = (GeneralValidationFailure)failure
                    });
                }

                string attributesJson     = null;
                string attributesChecksum = null;

                if (request.Attributes != null && request.Attributes.Any())
                {
                    attributesJson     = JsonSerializer.Serialize(request.Attributes);
                    attributesChecksum = Utils.GetSha256HashFromString(attributesJson);
                }

                var activationId  = Guid.NewGuid();
                var product       = _context.Products.Single(x => x.LicenseProductId == request.ProductUuid);
                var registration  = _context.Registrations.Single(x => x.LicenseRegistrationId == request.LicenseUuid);
                var licenseString = await CreateLicenseAsync(request, registration, product, activationId);

                await CreateLicenseRecordAsync(registration, licenseString, attributesJson, attributesChecksum, userName, activationId);

                var result = new LicenseRegisterResult();
                result.License = licenseString;

                return(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);

                return(new LicenseRegisterResult
                {
                    Failure = (GeneralValidationFailure)FailureStrings.Get(FailureStrings.ACT06Code)
                });
            }
        }
コード例 #6
0
        /// <summary>
        /// Validates if the license has been expired.
        /// </summary>
        /// <param name="validationChain">The current <see cref="IStartValidationChain"/>.</param>
        /// <returns>An instance of <see cref="IStartValidationChain"/>.</returns>
        public static IValidationChain ExpirationDate(this IStartValidationChain validationChain)
        {
            var validationChainBuilder = (validationChain as ValidationChainBuilder);
            var validator = validationChainBuilder.StartValidatorChain();

            validator.Validate = license => license.ExpirationUtc > DateTime.UtcNow;

            validator.FailureResult = FailureStrings.Get(FailureStrings.VAL03Code);

            return(validationChainBuilder);
        }
コード例 #7
0
        /// <summary>
        /// Validates the <see cref="License.Signature"/>.
        /// </summary>
        /// <param name="validationChain">The current <see cref="IStartValidationChain"/>.</param>
        /// <returns>An instance of <see cref="IStartValidationChain"/>.</returns>
        public static IValidationChain Signature(this IStartValidationChain validationChain)
        {
            var validationChainBuilder = (validationChain as ValidationChainBuilder);
            var validator = validationChainBuilder.StartValidatorChain();

            validator.Validate = license => license.VerifySignature();

            validator.FailureResult = FailureStrings.Get(FailureStrings.VAL02Code);

            return(validationChainBuilder);
        }
コード例 #8
0
        protected override Task <IEnumerable <IValidationFailure> > ValidateInternalAsync(License actual)
        {
            var failure = FailureStrings.Get(FailureStrings.VAL04Code);

            var appId = GetAttributes()[LicenseGlobals.MachineName];

            var failures = actual.Validate()
                           .ExpirationDate()
                           .When(lic => lic.Type == LicenseType.Standard)
                           .And()
                           .Signature()
                           .And()
                           .AssertThat(x => string.Equals(appId, x.AdditionalAttributes.Get(LicenseGlobals.MachineName), StringComparison.OrdinalIgnoreCase), failure)
                           .AssertValidLicense().ToList();

            return(Task.FromResult(failures.AsEnumerable()));
        }
コード例 #9
0
        public Task <IValidationFailure> ValidateAsync(LicenseRegisterRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            if (request.LicenseUuid == Guid.Empty)
            {
                return(Task.FromResult(FailureStrings.Get(FailureStrings.ACT01Code)));
            }
            if (request.ProductUuid == Guid.Empty)
            {
                return(Task.FromResult(FailureStrings.Get(FailureStrings.ACT02Code)));
            }

            var registration = _context.Registrations.SingleOrDefault(x => x.LicenseRegistrationId == request.LicenseUuid);

            if (registration == null)
            {
                return(Task.FromResult(FailureStrings.Get(FailureStrings.ACT01Code)));
            }

            if (registration.ProductId != request.ProductUuid)
            {
                return(Task.FromResult(FailureStrings.Get(FailureStrings.ACT02Code)));
            }

            if (registration.IsActive == false)
            {
                return(Task.FromResult(FailureStrings.Get(FailureStrings.ACT03Code)));
            }

            if (registration.ExpireUtc != null && registration.ExpireUtc <= DateTime.UtcNow)
            {
                return(Task.FromResult(FailureStrings.Get(FailureStrings.ACT04Code)));
            }

            if (registration.Quantity > 1 && (LicenseGetUsage(request.LicenseUuid) >= registration.Quantity))
            {
                return(Task.FromResult(FailureStrings.Get(FailureStrings.ACT05Code)));
            }

            return(Task.FromResult <IValidationFailure>(null));
        }
コード例 #10
0
        public Task <IEnumerable <IValidationFailure> > ValidateAsync(Stream license)
        {
            if (license == null)
            {
                throw new ArgumentNullException(nameof(license));
            }

            var task = Task.Run(() =>
            {
                var results = new List <IValidationFailure>();

                try
                {
                    var actual = License.Load(license);

                    var failure = FailureStrings.Get(FailureStrings.VAL04Code);

                    var validationFailures = actual.Validate()
                                             .ExpirationDate()
                                             .When(lic => lic.Type == LicenseType.Standard)
                                             .And()
                                             .Signature()
                                             .And()
                                             .AssertThat(x => string.Equals(AppId, x.AdditionalAttributes.Get(LicenseGlobals.AppId), StringComparison.OrdinalIgnoreCase), failure)
                                             .AssertValidLicense().ToList();

                    foreach (var f in validationFailures)
                    {
                        results.Add(f);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);

                    var failure = FailureStrings.Get(FailureStrings.VAL01Code);
                    results.Add(failure);
                }
                return(results.AsEnumerable());
            });

            return(task);
        }
コード例 #11
0
        public IEnumerable <IValidationFailure> AssertValidLicense()
        {
            CompleteValidatorChain();

            while (validators.Count > 0)
            {
                var validator = validators.Dequeue();
                if (validator.ValidateWhen != null && !validator.ValidateWhen(license))
                {
                    continue;
                }

                if (!validator.Validate(license))
                {
                    yield return(validator.FailureResult
                                 ?? FailureStrings.Get(FailureStrings.VAL05Code));
                }
            }
        }
コード例 #12
0
        /// <summary>
        /// Check whether the product build date of the provided assemblies
        /// exceeded the <see cref="License.ExpirationUtc"/> date.
        /// </summary>
        /// <param name="validationChain">The current <see cref="IStartValidationChain"/>.</param>
        /// <param name="assemblies">The list of assemblies to check.</param>
        /// <returns>An instance of <see cref="IStartValidationChain"/>.</returns>
        public static IValidationChain ProductBuildDate(this IStartValidationChain validationChain, Assembly[] assemblies)
        {
            var validationChainBuilder = (validationChain as ValidationChainBuilder);
            var validator = validationChainBuilder.StartValidatorChain();

#if !NEW_REFLECTION
            validator.Validate = license => assemblies.All(
                asm =>
                asm.GetCustomAttributes(typeof(AssemblyBuildDateAttribute), false)
                .Cast <AssemblyBuildDateAttribute>()
                .All(a => a.BuildDateUtc < license.ExpirationUtc));
#else
            validator.Validate = license => assemblies.All(
                asm =>
                asm.GetCustomAttributes <AssemblyBuildDateAttribute>()
                .Cast <AssemblyBuildDateAttribute>()
                .All(a => a.BuildDateUtc < license.ExpirationUtc));
#endif

            validator.FailureResult = FailureStrings.Get(FailureStrings.VAL03Code);

            return(validationChainBuilder);
        }
コード例 #13
0
        public async void CreateAsync()
        {
            var logger = Substitute.For <ILogger <LicenseService> >();

            // In-memory database only exists while the connection is open
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            try
            {
                var contextOptions = new DbContextOptionsBuilder <EfDbContext>()
                                     .UseSqlite(connection)
                                     .Options;

                // Create the schema in the database
                using (var context = new EfDbContext(contextOptions))
                {
                    context.Database.EnsureCreated();
                    var service = new LicenseService(context, logger);

                    var product = CreateProduct();
                    context.Add(product);
                    context.SaveChanges();

                    var expireDate   = DateTime.UtcNow.AddDays(1);
                    var registration = CreateRegistration(product);
                    registration.Quantity  = 2;
                    registration.ExpireUtc = expireDate;
                    context.Add(registration);
                    context.SaveChanges();

                    var request = new LicenseRegisterRequest
                    {
                        LicenseUuid = registration.LicenseRegistrationId,
                        ProductUuid = registration.ProductId,
                        Attributes  = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase)
                    };

                    request.Attributes.Add("AppId", "app-id-0001");

                    var result = await service.CreateAsync(request, "test-user");

                    var lic           = context.Licenses.ToArray();
                    var licenseRecord = await context.Licenses.SingleAsync(x => x.LicenseId == registration.LicenseRegistrationId);

                    Assert.Null(result.Failure);
                    Assert.NotNull(result.License);
                    Assert.NotNull(licenseRecord);
                    Assert.False(licenseRecord.LicenseActivationId == Guid.Empty);
                    Assert.Equal(registration.LicenseRegistrationId, licenseRecord.LicenseId);
                    Assert.Equal(registration.ProductId, licenseRecord.ProductId);
                    Assert.Equal(registration.CompanyId, licenseRecord.CompanyId);
                    Assert.NotNull(licenseRecord.LicenseString);
                    Assert.NotNull(licenseRecord.LicenseAttributes);
                    Assert.NotNull(licenseRecord.LicenseChecksum);
                    Assert.NotNull(licenseRecord.AttributesChecksum);
                    Assert.Equal(Utils.ChecksumType, licenseRecord.ChecksumType);
                    Assert.Equal(DateTime.UtcNow.ToString("yyyyMMdd"), licenseRecord.CreatedDateTimeUtc.ToString("yyyyMMdd"));
                    Assert.NotNull(licenseRecord.CreatedByUser);

                    var license = License.Load(result.License);

                    var failure = FailureStrings.Get(FailureStrings.VAL04Code);

                    var failures = license.Validate()
                                   .ExpirationDate()
                                   .When(lic => lic.Type == LicenseType.Standard)
                                   .And()
                                   .Signature()
                                   .And()
                                   .AssertThat(x => string.Equals(request.Attributes["AppId"], x.AdditionalAttributes.Get("AppId"), StringComparison.OrdinalIgnoreCase), failure)
                                   .AssertValidLicense().ToList();

                    // Valid
                    Assert.False(failures.Any());

                    // License
                    Assert.Equal(licenseRecord.LicenseActivationId, license.ActivationUuid);
                    Assert.Equal(request.LicenseUuid, license.Id);
                    Assert.Equal(registration.LicenseType, license.Type);
                    Assert.Equal(expireDate.ToString("yyyyMMdd"), license.ExpirationUtc.ToString("yyyyMMdd"));
                    Assert.Equal(2, license.Quantity);
                    Assert.Equal(registration.LicenseName, license.Customer.Name);
                    Assert.Equal(registration.LicenseEmail, license.Customer.Email);
                    Assert.Equal(registration.LicenseName, license.Customer.Company);
                    Assert.Equal(request.Attributes["AppId"], license.AdditionalAttributes.Get("AppId"));
                }
            }
            finally
            {
                connection.Close();
            }
        }