public void ValidateCurrentToken(JsonToken token, object value, int depth)
        {
            if (_scopes.Count == 0)
            {
                if (Schema == null)
                {
                    throw new JSchemaException("No schema has been set for the validator.");
                }

                LicenseHelpers.IncrementAndCheckValidationCount();
                SchemaScope.CreateTokenScope(token, Schema, _context, null, depth);
            }

            TokenWriter?.WriteToken(token, value);

            for (int i = _scopes.Count - 1; i >= 0; i--)
            {
                Scope scope = _scopes[i];

                if (!scope.Complete)
                {
                    scope.EvaluateToken(token, value, depth);
                }
                else
                {
                    _scopes.RemoveAt(i);
                    _scopesCache.Add(scope);
                }
            }

            if (TokenWriter != null && TokenWriter.Top == 0)
            {
                TokenWriter = null;
            }
        }
        public void InvalidLicenseText()
        {
            LicenseDetails license = new LicenseDetails
            {
                Id         = 1001,
                ExpiryDate = new DateTime(2016, 12, 27, 0, 0, 0, DateTimeKind.Utc),
                Type       = LicenseType.Test
            };

            string licenseText = "";

            ExceptionAssert.Throws <JSchemaException>(() => LicenseHelpers.RegisterLicense(licenseText, new DateTime(2016, 12, 26, 0, 0, 0, DateTimeKind.Utc)), "License text is empty.");

            licenseText = "1002";
            ExceptionAssert.Throws <JSchemaException>(() => LicenseHelpers.RegisterLicense(licenseText, new DateTime(2016, 12, 26, 0, 0, 0, DateTimeKind.Utc)), "Specified license text is invalid.");

            licenseText = "1003-N8/Xc2RXpYddnHEH881tBKyb4itL4Wiyh3VL3HMQP3phVElppL3GNeSqYDQQcxSz34lXOHfWTrKEdAw2oNcyohMkXTKjlr5T7kASfLHaHPV3mUrFJPFlWhwfEzJ/+Fie0HT0chcXJnxFu50hJT++IfVYtcYwc+gNHzvQc2E2mRt7IklkIjoxMDAyLCJFeHBpcnlEYXRlIjoiMjExNi0xMi0yN1QwMDowMDowMFoiLCJUeXBlIjoiVGVzdCJ9";
            ExceptionAssert.Throws <JSchemaException>(() => LicenseHelpers.RegisterLicense(licenseText, new DateTime(2016, 12, 26, 0, 0, 0, DateTimeKind.Utc)), "License ID does not match signature license ID.");

            licenseText = "PIES-N8/Xc2RXpYddnHEH881tBKyb4itL4Wiyh3VL3HMQP3phVElppL3GNeSqYDQQcxSz34lXOHfWTrKEdAw2oNcyohMkXTKjlr5T7kASfLHaHPV3mUrFJPFlWhwfEzJ/+Fie0HT0chcXJnxFu50hJT++IfVYtcYwc+gNHzvQc2E2mRt7IklkIjoxMDAyLCJFeHBpcnlEYXRlIjoiMjExNi0xMi0yN1QwMDowMDowMFoiLCJUeXBlIjoiVGVzdCJ9";
            ExceptionAssert.Throws <JSchemaException>(() => LicenseHelpers.RegisterLicense(licenseText, new DateTime(2016, 12, 26, 0, 0, 0, DateTimeKind.Utc)), "Specified license text is invalid.");

            licenseText = "1002-!!/Xc2RXpYddnHEH881tBKyb4itL4Wiyh3VL3HMQP3phVElppL3GNeSqYDQQcxSz34lXOHfWTrKEdAw2oNcyohMkXTKjlr5T7kASfLHaHPV3mUrFJPFlWhwfEzJ/+Fie0HT0chcXJnxFu50hJT++IfVYtcYwc+gNHzvQc2E2mRt7IklkIjoxMDAyLCJFeHBpcnlEYXRlIjoiMjExNi0xMi0yN1QwMDowMDowMFoiLCJUeXBlIjoiVGVzdCJ9";
            ExceptionAssert.Throws <JSchemaException>(() => LicenseHelpers.RegisterLicense(licenseText, new DateTime(2016, 12, 27, 0, 0, 0, DateTimeKind.Utc)), "Specified license text is invalid.");

            licenseText = "1001-" + Convert.ToBase64String(Encoding.UTF8.GetBytes("Hello world"));
            ExceptionAssert.Throws <JSchemaException>(() => LicenseHelpers.RegisterLicense(licenseText, new DateTime(2016, 12, 28, 0, 0, 0, DateTimeKind.Utc)), "Specified license text is invalid.");
        }
Beispiel #3
0
        protected void TestSetup()
        {
            //CultureInfo turkey = CultureInfo.CreateSpecificCulture("tr");
            //Thread.CurrentThread.CurrentCulture = turkey;
            //Thread.CurrentThread.CurrentUICulture = turkey;

            LicenseHelpers.ResetCounts(null);
        }
        /// <summary>
        /// Generate a <see cref="JSchema"/> from the specified type.
        /// </summary>
        /// <param name="type">The type to generate a <see cref="JSchema"/> from.</param>
        /// <param name="rootSchemaNullable">Specify whether the generated root <see cref="JSchema"/> will be nullable.</param>
        /// <returns>A <see cref="JSchema"/> generated from the specified type.</returns>
        public JSchema Generate(Type type, bool rootSchemaNullable)
        {
            ValidationUtils.ArgumentNotNull(type, "type");

            LicenseHelpers.IncrementAndCheckGenerationCount();

            return(GenerateInternal(type, (!rootSchemaNullable) ? Required.Always : Required.Default, null, null));
        }
        /// <summary>
        /// Performs a batch refresh of all entities.
        /// </summary>
        /// <param name="entities">The entities to refresh.</param>
        /// <param name="ct">(Optional) A cancellation token for async processing.</param>
        /// <remarks>
        /// Trello imposes a limit of 10 entities per call.  Therefore this method will break all entities into batches
        /// of 10 and make a single call for each, returning when all have completed.
        /// </remarks>
        public static Task Refresh(IEnumerable <IBatchRefreshable> entities, CancellationToken ct = default(CancellationToken))
        {
            var groupedByAuth = entities.OfType <IBatchRefresh>()
                                .GroupBy(e => e.Auth);
            var batches = groupedByAuth.SelectMany(ga => ga.Select((entity, index) => new { entity, index })
                                                   .GroupBy(gc => gc.index / 10, gc => gc.entity)
                                                   .Select(g => g.ToList()));

            return(LicenseHelpers.Batch(Task.WhenAll(batches.Select(g => _RefreshBatch(g, ct)))));
        }
        /// <summary>
        /// Processes webhook notification content.
        /// </summary>
        /// <param name="content">The string content of the notification.</param>
        /// <param name="auth">The <see cref="TrelloAuthorization"/> under which the notification should be processed</param>
        public static void ProcessNotification(string content, TrelloAuthorization auth = null)
        {
            LicenseHelpers.IncrementAndCheckRetrieveCount();
            var notification = TrelloConfiguration.Deserializer.Deserialize <IJsonWebhookNotification>(content);
            var action       = new Action(notification.Action, auth);

            foreach (var obj in TrelloConfiguration.Cache.OfType <ICanWebhook>())
            {
                obj.ApplyAction(action);
            }
        }
        public void ValidateCurrentToken(JsonToken token, object?value, int depth)
        {
            if (depth == 0)
            {
                // Handle validating multiple content
                RemoveCompletedScopes();
            }

            if (_scopes.Count == 0)
            {
                if (Schema == null)
                {
                    throw new JSchemaException("No schema has been set for the validator.");
                }

                if (!_hasValidatedLicense)
                {
                    LicenseHelpers.IncrementAndCheckValidationCount();
                    _hasValidatedLicense = true;
                }

                SchemaScope.CreateTokenScope(token, Schema, _context, null, depth);
            }

            if (TokenWriter != null)
            {
                // JTokenReader can return JsonToken.String with a null value which WriteToken doesn't like.
                // Hacky - change token to JsonToken.Null. Can be removed when fixed Newtonsoft.Json is public.
                JsonToken fixedToken = (token == JsonToken.String && value == null) ? JsonToken.Null : token;

                TokenWriter.WriteToken(fixedToken, value);
            }

            for (int i = _scopes.Count - 1; i >= 0; i--)
            {
                Scope scope = _scopes[i];

                if (scope.Complete != CompleteState.Completed)
                {
                    scope.EvaluateToken(token, value, depth);
                }
                else
                {
                    _scopes.RemoveAt(i);
                    _scopesCache.Add(scope);
                }
            }

            if (TokenWriter != null && (TokenWriter.WriteState == WriteState.Start || TokenWriter.WriteState == WriteState.Closed))
            {
                TokenWriter = null;
            }
        }
Beispiel #8
0
        /// <summary>
        /// Generate a <see cref="JSchema"/> from the specified type.
        /// </summary>
        /// <param name="type">The type to generate a <see cref="JSchema"/> from.</param>
        /// <param name="rootSchemaNullable">Specify whether the generated root <see cref="JSchema"/> will be nullable.</param>
        /// <returns>A <see cref="JSchema"/> generated from the specified type.</returns>
        public virtual JSchema Generate(Type type, bool rootSchemaNullable)
        {
            ValidationUtils.ArgumentNotNull(type, nameof(type));

            LicenseHelpers.IncrementAndCheckGenerationCount();

            Required required = rootSchemaNullable ? Required.AllowNull : Required.Always;

            JSchemaGeneratorInternal generator = new JSchemaGeneratorInternal(this);

            return(generator.Generate(type, required));
        }
Beispiel #9
0
        public void ValidateCurrentToken(JsonToken token, object value, int depth)
        {
            if (depth == 0)
            {
                // Handle validating multiple content
                RemoveCompletedScopes();
            }

            if (_scopes.Count == 0)
            {
                if (Schema == null)
                {
                    throw new JSchemaException("No schema has been set for the validator.");
                }

                if (!_hasValidatedLicense)
                {
                    LicenseHelpers.IncrementAndCheckValidationCount();
                    _hasValidatedLicense = true;
                }

                SchemaScope.CreateTokenScope(token, Schema, _context, null, depth);
            }

            TokenWriter?.WriteToken(token, value);

            for (int i = _scopes.Count - 1; i >= 0; i--)
            {
                Scope scope = _scopes[i];

                if (!scope.Complete)
                {
                    scope.EvaluateToken(token, value, depth);
                }
                else
                {
                    _scopes.RemoveAt(i);
                    _scopesCache.Add(scope);
                }
            }

            if (TokenWriter != null && (TokenWriter.WriteState == WriteState.Start || TokenWriter.WriteState == WriteState.Closed))
            {
                TokenWriter = null;
            }
        }
        public void LicenseValidation()
        {
            LicenseDetails license = new LicenseDetails
            {
                Id         = 1001,
                ExpiryDate = new DateTime(2016, 12, 27, 0, 0, 0, DateTimeKind.Utc),
                Type       = LicenseType.Test
            };

            string licenseText = "1001-N70qM5lisTgmXINQXrhM7jfbLxMs0Rkq8nF5V10yf4OMjSZQyI/IR8Oz9hfIyEs5hSzI8eX8dFb1KcKsMySTuQ/wHU6EKX6SzsBHzbOSxHhjR5XuBFUznGM+u1FyK7hGOxsyRZgBDS2rClcD/9bfn7SgitQU4nd1fGXnnQK1s5h7IklkIjoxMDAxLCJFeHBpcnlEYXRlIjoiMjAxNi0xMi0yN1QwMDowMDowMFoiLCJUeXBlIjoiVGVzdCJ9";

            ExceptionAssert.Throws <JSchemaException>(() => LicenseHelpers.RegisterLicense(licenseText, new DateTime(2016, 12, 26, 0, 0, 0, DateTimeKind.Utc)), "Specified license is for testing only.");
            ExceptionAssert.Throws <JSchemaException>(() => LicenseHelpers.RegisterLicense(licenseText, new DateTime(2016, 12, 27, 0, 0, 0, DateTimeKind.Utc)), "Specified license is for testing only.");
            ExceptionAssert.Throws <JSchemaException>(() => LicenseHelpers.RegisterLicense(licenseText, new DateTime(2016, 12, 28, 0, 0, 0, DateTimeKind.Utc)), "License is not valid for this version of Json.NET Schema. License expired on 2016-12-27. This version of Json.NET Schema was released on 2016-12-28.");

            licenseText = "1001-BADqM5lisTgmXINQXrhM7jfbLxMs0Rkq8nF5V10yf4OMjSZQyI/IR8Oz9hfIyEs5hSzI8eX8dFb1KcKsMySTuQ/wHU6EKX6SzsBHzbOSxHhjR5XuBFUznGM+u1FyK7hGOxsyRZgBDS2rClcD/9bfn7SgitQU4nd1fGXnnQK1s5h7IklkIjoxMDAxLCJFeHBpcnlEYXRlIjoiMjAxNi0xMi0yN1QwMDowMDowMFoiLCJUeXBlIjoiVGVzdCJ9";
            ExceptionAssert.Throws <JSchemaException>(() => LicenseHelpers.RegisterLicense(licenseText, new DateTime(2016, 12, 27, 0, 0, 0, DateTimeKind.Utc)), "License text does not match signature.");
        }
        private static void ManageLicenseCounts(RestMethod method)
        {
            switch (method)
            {
            case RestMethod.Get:
                LicenseHelpers.IncrementAndCheckRetrieveCount();
                break;

            case RestMethod.Put:
            case RestMethod.Post:
            case RestMethod.Delete:
                LicenseHelpers.IncrementAndCheckSubmissionCount();
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(method), method, null);
            }
        }
Beispiel #12
0
        private void GenerateSchemaAndSerializeFromType <T>(T value)
        {
            LicenseHelpers.ResetCounts(null);

            JSchemaGenerator generator = new JSchemaGenerator();

            generator.UndefinedSchemaIdHandling = JSchemaUndefinedIdHandling.UseAssemblyQualifiedName;
            JSchema typeSchema = generator.Generate(typeof(T));
            string  schema     = typeSchema.ToString();

            string json  = JsonConvert.SerializeObject(value, Formatting.Indented);
            JToken token = JToken.ReadFrom(new JsonTextReader(new StringReader(json)));

            List <string> errors = new List <string>();

            token.Validate(typeSchema, (sender, args) => { errors.Add(args.Message); });

            if (errors.Count > 0)
            {
                Assert.Fail("Schema generated for type '{0}' is not valid." + Environment.NewLine + string.Join(Environment.NewLine, errors.ToArray()), typeof(T));
            }
        }
        /// <summary>
        /// Signals the processor that the application is shutting down.  The processor will perform a "last call" for pending requests.
        /// </summary>
        public static async Task Flush()
        {
            await RestRequestProcessor.Flush();

            LicenseHelpers.SaveCurrentState();
        }
Beispiel #14
0
 /// <summary>
 /// Register the specified license with Json.NET Schema. A license can be purchased at <see href="http://www.newtonsoft.com/jsonschema">http://www.newtonsoft.com/jsonschema</see>.
 /// </summary>
 /// <param name="license">The license text to register.</param>
 /// <remarks>
 /// The recommended way to register the license key is to call <see cref="RegisterLicense"/> once during application start up.
 /// In ASP.NET web applications it can be placed in the <c>Startup.cs</c> or <c>Global.asax.cs</c>,
 /// in WPF applications it can be placed in the <c>Application.Startup</c> event,
 /// and in Console applications it can be placed in the <c>static void Main(string[] args)</c> event.
 /// </remarks>
 /// <example>
 /// This sample shows how to register a Json.NET Schema license with the <see cref="RegisterLicense"/> method.
 /// <code>
 /// // replace with your license key
 /// string licenseKey = "json-schema-license-key";
 /// License.RegisterLicense(licenseKey);
 /// </code>
 /// </example>
 public static void RegisterLicense(string license)
 {
     LicenseHelpers.RegisterLicense(license);
 }
 /// <summary>
 /// Signals the processor that the application is shutting down.  The processor will perform a "last call" for pending requests.
 /// </summary>
 public static async Task Flush()
 {
     await LicenseHelpers.Batch(RestRequestProcessor.Flush());
 }
        protected void TestSetup()
#endif
        {
            LicenseHelpers.ResetCounts(null);
        }
Beispiel #17
0
 /// <summary>
 /// Get a flag indicating whether license has been registered. A license is registered using <see cref="RegisterLicense"/>.
 /// </summary>
 /// <returns><c>true</c> if a license has been registered; otherwise <c>false</c>.</returns>
 public static bool HasRegisteredLicense()
 {
     return(LicenseHelpers.HasRegisteredLicense());
 }