Пример #1
0
 /// <summary>
 /// Gets the JSON object from body.
 /// </summary>
 /// <param name="request">The HTTP request.</param>
 /// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
 /// <returns>A JSON object instance; or null, if no body.</returns>
 /// <exception cref="JsonException">json does not represent a valid single JSON object.</exception>
 /// <exception cref="ArgumentException">options contains unsupported options.</exception>
 public static Task <JsonObjectNode> ReadBodyAsJsonAsync(this HttpRequest request, CancellationToken cancellationToken)
 {
     if (request == null || request.Body == null)
     {
         return(null);
     }
     return(JsonObjectNode.ParseAsync(request.Body, default, cancellationToken));
Пример #2
0
 static EmbeddedDiagnostic?CheckObject(JsonObjectNode node)
 {
     foreach (var child in node.Sequence)
     {
         if (child is JsonLiteralNode {
             LiteralToken.Kind: JsonKind.StringToken
         })
        /// <inheritdoc/>
        /// <seealso cref="Path"/>
        /// <seealso cref="Load()"/>
        public override void SaveDirtySettings()
        {
            if (string.IsNullOrEmpty(this.Path))
            {
                throw new InvalidOperationException("Cannot save settings because 'Path' string is null or empty.");
            }

            JsonNode jsonSettings = new JsonObjectNode();

            if (File.Exists(this.Path))
            {
                using (var stream = new FileStream(this.Path, FileMode.Open, FileAccess.Read)) {
                    jsonSettings = JsonUtility.ReadFrom(stream);
                }
            }

            if (this._data.Sync(jsonSettings, this.Manager))
            {
                // Ensure that path exists!
                string directoryName = System.IO.Path.GetDirectoryName(this.Path);
                if (!Directory.Exists(directoryName))
                {
                    Directory.CreateDirectory(directoryName);
                }

                File.WriteAllText(this.Path, this._data.ToJson());
            }
        }
Пример #4
0
        public virtual async Task <IActionResult> SaveAsync(string id)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(id))
                {
                    return(this.ExceptionResult(400, "An entity identifier is required in path.", "NoBody"));
                }
                var provider = await GetProviderAsync();

                var content = await JsonObjectNode.ParseAsync(Request.Body);

                var r = await provider.SaveAsync(id, content);

                var entity = (r as ChangingResultInfo <TEntity>)?.Data;
                Logger?.LogInformation(new EventId(17006004, "UpdateEntity"), entity != null ? $"Update entity {entity.GetType().Name} {entity.Name} ({entity.Id})." : $"Failed update entity {id} because of non-existing.");
                return(r.ToActionResult());
            }
            catch (Exception ex)
            {
                var er = this.ExceptionResult(ex, true);
                if (er != null)
                {
                    Logger?.LogError(new EventId(17006004, "UpdateEntity"), $"Update entity {id} failed. {ex.GetType().Name} {ex.Message}");
                    return(er);
                }

                Logger?.LogError(new EventId(17006004, "UpdateEntity"), $"Update entity {id} failed with internal error. {ex.GetType().Name} {ex.Message}");
                throw;
            }
        }
Пример #5
0
        internal static async Task <IActionResult> SaveEntityAsync <T>(this ControllerBase controller, Func <string, BaseResourceAccessClient, Task <T> > entityResolver, Func <T, BaseResourceAccessClient, JsonObjectNode, Task <ChangingResultInfo> > save, string id) where T : BaseResourceEntity
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                return(ChangeErrorKinds.Argument.ToActionResult("Requires entity identifier."));
            }
            var instance = await controller.GetResourceAccessClientAsync();

            var entity = await entityResolver(id, instance);

            if (controller.Request.Body == null)
            {
                return(new ChangingResultInfo <T>(ChangeMethods.Unchanged, entity).ToActionResult());
            }
            if (entity == null)
            {
                return(ChangeErrorKinds.NotFound.ToActionResult("The resource does not exist."));
            }
            var delta = await JsonObjectNode.ParseAsync(controller.Request.Body);

            if (delta.Count == 0)
            {
                return(new ChangingResultInfo <T>(ChangeMethods.Unchanged, entity, "Nothing update request.").ToActionResult());
            }
            entity.SetProperties(delta);
            var result = await save(entity, instance, delta);

            return(result.ToActionResult());
        }
Пример #6
0
 /// <summary>
 /// Initializes a new instance of the SettingsEntity.Model class.
 /// </summary>
 /// <param name="key">The settings key.</param>
 /// <param name="siteId">The site identifier.</param>
 /// <param name="siteConfig">The site settings configuration data.</param>
 /// <param name="globalConfig">The global settings configuration data.</param>
 public Model(string key, string siteId, JsonObjectNode siteConfig, JsonObjectNode globalConfig = null)
 {
     Key                = key;
     SiteId             = siteId;
     SiteConfigString   = siteConfig?.ToString();
     GlobalConfigString = globalConfig?.ToString();
 }
Пример #7
0
        /// <summary>
        /// Saves.
        /// </summary>
        /// <param name="id">The entity identifier.</param>
        /// <param name="delta">The data to change.</param>
        /// <param name="cancellationToken">The optional token to monitor for cancellation requests.</param>
        /// <returns>The change method.</returns>
        public virtual async Task <ChangingResultInfo> SaveAsync(string id, JsonObjectNode delta, CancellationToken cancellationToken = default)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                if (delta == null)
                {
                    return(null);
                }
                try
                {
                    var newEntity = delta.Deserialize <T>();
                    return(await SaveAsync(newEntity, cancellationToken) ?? new ChangingResultInfo(ChangeErrorKinds.Service, "No response."));
                }
                catch (System.Text.Json.JsonException)
                {
                    return(new ChangingResultInfo(ChangeErrorKinds.Argument, "Failed to convert the JSON object."));;
                }
            }

            var entity = await GetAsync(id, true, cancellationToken);

            if (delta == null || delta.Count == 0)
            {
                return(new ChangingResultInfo <T>(ChangeMethods.Unchanged, entity, "Update properties."));
            }
            ;
            entity.SetProperties(delta);
            await SaveAsync(entity, cancellationToken);

            return(new ChangingResultInfo <T>(ChangeMethods.MemberModify, entity, "Update properties."));
        }
Пример #8
0
        public void FromDictionary_Null()
        {
            // Arrange
            Dictionary <string, int> dictionary = null;

            // Act
            JsonObjectNode.FromDictionary(dictionary);
        }
Пример #9
0
        public static JsonObjectNode CreateIdentityCard(string name)
        {
            var card = new JsonObjectNode();

            card["Name"] = new JsonStringNode(name);
            card["Age"]  = new JsonIntegerNode(22);
            return(card);
        }
Пример #10
0
        public static JsonObjectNode CreateSimpleObject()
        {
            var obj = new JsonObjectNode();

            obj["EvenNumbers"] = CreateNumericArrayWithEvenNumbers();
            obj["Cards"]       = CreateIdentityCardArray();
            return(obj);
        }
Пример #11
0
 /// <summary>
 /// Indicates whether this instance and a specified object are equal.
 /// </summary>
 /// <param name="other">The object to compare with the current instance.</param>
 /// <returns>true if obj and this instance represent the same value; otherwise, false.</returns>
 public bool Equals(JsonObjectNode other)
 {
     if (other is null)
     {
         return(false);
     }
     return(AtomicNumber == other.TryGetInt32Value("number") &&
            Symbol == other.TryGetStringValue("symbol"));
 }
Пример #12
0
        public void Callback_OnDeserialized()
        {
            // Arrange
            var node = new JsonObjectNode();

            // Act
            var instance = node.ConvertTo <SerializationCallback_OnDeserialized>();

            // Assert
            Assert.AreEqual("OnDeserialized", instance.Result);
        }
Пример #13
0
        public void FromDictionary_Empty()
        {
            // Arrange
            var dictionary = new Dictionary <string, int>();

            // Act
            var objectNode = JsonObjectNode.FromDictionary(dictionary);

            // Assert
            Assert.IsNotNull(objectNode);
            Assert.AreEqual(0, objectNode.Count);
        }
Пример #14
0
            private static EmbeddedDiagnostic?CheckObject(JsonObjectNode node)
            {
                foreach (var child in node.Sequence)
                {
                    if (child.Kind != JsonKind.Property)
                    {
                        return(new EmbeddedDiagnostic(FeaturesResources.Only_properties_allowed_in_an_object, GetFirstToken(child).GetSpan()));
                    }
                }

                return(null);
            }
Пример #15
0
            private static EmbeddedDiagnostic?CheckObject(JsonObjectNode node, bool allowTrailingComma)
            {
                foreach (var child in node.Sequence)
                {
                    if (child.Kind != JsonKind.Property)
                    {
                        return(new EmbeddedDiagnostic(FeaturesResources.Only_properties_allowed_in_an_object, GetFirstToken(child).GetSpan()));
                    }
                }

                if (!allowTrailingComma && node.Sequence.NodesAndTokens.Length != 0 && node.Sequence.NodesAndTokens.Length % 2 == 0)
                {
                    return(new EmbeddedDiagnostic(FeaturesResources.Trailing_comma_not_allowed, node.Sequence.NodesAndTokens[^ 1].Token.GetSpan()));
Пример #16
0
        public void ToString_IndentWithTabs()
        {
            // Arrange
            JsonObjectNode simpleObjectNode = JsonObjectGraphs.CreateSimpleObject();

            // Act
            string result = JsonUtility.ToJsonString(simpleObjectNode, new JsonWriterSettings());

            // Assert
            string expectedResult = File.ReadAllText("SimpleObject.json");

            Assert.AreEqual(expectedResult, result);
        }
        private JsonObjectNode ToJsonObject()
        {
            var jsonData = new JsonObjectNode();

            foreach (var groupData in this._groups.Values)
            {
                var jsonGroup = groupData.ToJsonObject();
                if (jsonGroup != null)
                {
                    jsonData[groupData.Key] = jsonGroup;
                }
            }
            return(jsonData);
        }
Пример #18
0
        public async Task <IActionResult> SaveSettingsDataByKeyAsync(string key)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                return(BadRequest());
            }
            var instance = await this.GetResourceAccessClientAsync();

            var body = await JsonObjectNode.ParseAsync(Request.Body);

            var result = await instance.SaveSettingsAsync(key, null, body);

            Logger?.LogInformation(new EventId(17001103, "SaveGlobalSettings"), "Save global settings {0}.", key);
            return(result.ToActionResult());
        }
        public JsonObjectNode ToJsonObject()
        {
            if (this._settings.Count == 0)
            {
                return(null);
            }

            var jsonGroup = new JsonObjectNode();

            foreach (var settingData in this._settings)
            {
                jsonGroup[settingData.Key] = settingData.Value;
            }
            return(jsonGroup);
        }
Пример #20
0
    /// <summary>
    /// Deserializes the HTTP JSON content into an object as the specific type.
    /// </summary>
    /// <typeparam name="T">The type of the result expected.</typeparam>
    /// <param name="httpContent">The http response content.</param>
    /// <param name="origin">A value of type seek origin indicating the reference point used to obtain the new position before deserialziation.</param>
    /// <param name="cancellationToken">The optional cancellation token.</param>
    /// <returns>The result serialized.</returns>
    /// <exception cref="ArgumentNullException">The argument is null.</exception>
    public static async Task <T> DeserializeJsonAsync <T>(this HttpContent httpContent, SeekOrigin origin, CancellationToken cancellationToken = default)
    {
        if (httpContent == null)
        {
            throw new ArgumentNullException(nameof(httpContent), "httpContent should not be null.");
        }
#if NET5_0_OR_GREATER
        var stream = await httpContent.ReadAsStreamAsync(cancellationToken);
#else
        var stream = await httpContent.ReadAsStreamAsync();
#endif
        IO.StreamCopy.TrySeek(stream, origin);
        var type = typeof(T);
        if (type == typeof(JsonObjectNode))
        {
            return((T)(object)await JsonObjectNode.ParseAsync(stream, default, cancellationToken));
Пример #21
0
        public void ToString_KeysWithEscapeSequences()
        {
            // Arrange
            var node = new JsonObjectNode();

            node["Simple Key"]    = null;
            node["Hello\nWorld!"] = null;

            // Act
            string result = node.ToString();

            // Assert
            string expectedResult = File.ReadAllText("ToString_KeysWithEscapeSequences.json");

            Assert.AreEqual(expectedResult, result);
        }
Пример #22
0
        public void ToString_IndentWithSpaces()
        {
            // Arrange
            JsonObjectNode simpleObjectNode = JsonObjectGraphs.CreateSimpleObject();

            // Act
            var settings = new JsonWriterSettings();

            settings.IndentChars = "   ";
            string result = JsonUtility.ToJsonString(simpleObjectNode, settings);

            // Assert
            string expectedResult = File.ReadAllText("SimpleObject_WithSpaces.json");

            Assert.AreEqual(expectedResult, result);
        }
        private JsonObjectNode ProduceJsonObject(JsonTokenizer tokenizer)
        {
            var lcurl = NextAndGetType(tokenizer); // pop the leading {.

            if (lcurl != TokenType.LCURLY)
            {
                // this cannot happen.
                throw new InvalidJsonTokenException("JSON object should start with {.", GetTailCharStream(tokenizer), PeekCharStream(tokenizer));
            }

            IDictionary <string, object> map = new Dictionary <string, object>();
            var type = PeekAndGetType(tokenizer);

            if (type == TokenType.RCURLY)
            {
                // empty object
                tokenizer.Next(); // discard the trailing }.
            }
            else
            {
                IDictionary <string, JsonNode> members = ProduceJsonObjectMembers(tokenizer);
                var rcurl = NextAndGetType(tokenizer); // discard the trailing }.
                if (rcurl == TokenType.RCURLY)
                {
                    // Done
                    // ???
                    // (map as Dictionary<string, object>)?.putAll(members);
                    // map = (IDictionary<string, JsonNode>) members; ????
                    foreach (var m in members)
                    {
                        map[m.Key] = m.Value;
                    }
                    // ???
                }
                else
                {
                    // ???
                    throw new InvalidJsonTokenException("JSON object should end with }.", GetTailCharStream(tokenizer), PeekCharStream(tokenizer));
                }
            }
            JsonObjectNode jObject = (JsonObjectNode)jsonTypeFactory.CreateObject(map);

            //if (log.isLoggable(Level.FINE)) {
            //    log.fine("jObject = " + jObject);
            //}
            return(jObject);
        }
Пример #24
0
        /// <summary>
        /// Parses query arguments.
        /// </summary>
        /// <param name="json">The JSON object.</param>
        /// <returns>An instance of query arguments</returns>
        public static QueryArgs Parse(JsonObjectNode json)
        {
            var q = new QueryArgs
            {
                NameQuery   = json.GetStringValue("q") ?? json.GetStringValue("name"),
                NameExactly = json.TryGetBooleanValue("eqname") ?? false,
                Offset      = json.TryGetInt32Value("offset") ?? 0,
                Count       = json.TryGetInt32Value("count") ?? ResourceEntityExtensions.PageSize,
                State       = json.TryGetEnumValue <ResourceEntityStates>("state", true) ?? ResourceEntityStates.Normal,
                Order       = json.TryGetEnumValue <ResourceEntityOrders>("order", true) ?? ResourceEntityOrders.Default
            };

            if (!json.ContainsKey("offset") && json.TryGetInt32Value("pgno", out var pgIndex) && pgIndex > 0)
            {
                q.Offset = pgIndex * q.Count;
            }
            return(q);
        }
Пример #25
0
        public void WriteTo_ManualSetup()
        {
            // Arrange
            JsonObjectNode simpleObjectNode = JsonObjectGraphs.CreateSimpleObject();

            // Act
            var settings = new JsonWriterSettings();

            settings.IndentChars = "   ";
            var writer = JsonWriter.Create(settings);

            simpleObjectNode.Write(writer);
            string result = writer.ToString();

            // Assert
            string expectedResult = File.ReadAllText("SimpleObject_WithSpaces.json");

            Assert.AreEqual(expectedResult, result);
        }
        public bool Sync(ISettingGroup group, JsonObjectNode jsonGroup)
        {
            bool dirty = false;

            this._settings.Clear();

            if (group != null)
            {
                // Serialize modified properties.
                foreach (ISetting setting in group.Settings)
                {
                    if (setting.IsDirty)
                    {
                        try {
                            setting.Serialize(this);
                            dirty = true;
                        }
                        catch (Exception ex) {
                            this.Owner.LogFeedback(MessageFeedbackType.Error, string.Format("Was unable to serialize setting '{0}.{1}', skipping...", setting.GroupKey, setting.Key), ex);
                        }
                    }
                }
            }

            if (!this._clean)
            {
                if (jsonGroup != null)
                {
                    // Merge freshly loaded setting data with setting data.
                    foreach (var jsonSetting in jsonGroup)
                    {
                        if (!this._settings.ContainsKey(jsonSetting.Key))
                        {
                            this._settings[jsonSetting.Key] = jsonSetting.Value;
                        }
                    }
                }
                this._clean = false;
            }

            return(dirty);
        }
Пример #27
0
    /// <summary>
    /// Registers file extension mapping.
    /// </summary>
    /// <param name="json">The mapping source.</param>
    /// <param name="overrideIfExist">true if override the existed one; otherwise, false.</param>
    /// <returns>The count of item added or changed.</returns>
    public static int RegisterFileExtensionMapping(JsonObjectNode json, bool overrideIfExist = false)
    {
        var mapping = FileExtensionMapping;

        if (json == null || mapping == null)
        {
            return(0);
        }
        var arr = json.TryGetArrayValue("mime");

        if (arr != null)
        {
            return(RegisterFileExtensionMapping(arr, overrideIfExist));
        }
        var body = json.TryGetObjectValue("mime");

        if (body != null)
        {
            json = body;
        }
        var i = 0;

        foreach (var item in json)
        {
            if (item.Value?.ValueKind != JsonValueKind.String)
            {
                continue;
            }
            if (!item.Value.TryGetString(out var s))
            {
                continue;
            }
            if (mapping.Set(item.Key, s, overrideIfExist))
            {
                i++;
            }
        }

        return(i);
    }
Пример #28
0
        public void TestCustomizedJwt()
        {
            var payload = new JsonObjectNode();

            payload.SetValue("abcdefg", "hijklmn");
            payload.SetValue("opqrst", HashUtility.ComputeSHA3512String("uvwxyz"));
            var hash = HashSignatureProvider.CreateHS512("key");
            var jwt  = new JsonWebToken <JsonObjectNode>(payload, hash);

            Assert.AreEqual(true, jwt.CanSign);
            Assert.AreEqual(payload, jwt.Payload);
            Assert.AreEqual(hash.Name, jwt.AlgorithmName);
            var header = jwt.ToAuthenticationHeaderValue();

            Assert.IsTrue(header.Parameter.Length > 10);
            var jwt2 = JsonWebToken <JsonObjectNode> .Parse(header.Parameter, hash);

            Assert.AreEqual(header.Parameter, jwt2.ToEncodedString());
            var parser = new JsonWebToken <JsonObjectNode> .Parser(header.Parameter);

            Assert.AreEqual(header.Parameter, parser.ToString());
        }
Пример #29
0
        public virtual async Task <IActionResult> SaveAsync(string id)
        {
            try
            {
                var delta = await JsonObjectNode.ParseAsync(Request.Body);

                var r = await SaveAsync(id, delta);

                return(r.ToActionResult());
            }
            catch (Exception ex)
            {
                var er = this.ExceptionResult(ex, true);
                if (er != null)
                {
                    Logger?.LogError(new EventId(17006014, "UpdateEntity"), $"Update entity {id} failed. {ex.GetType().Name} {ex.Message}");
                    return(er);
                }

                Logger?.LogError(new EventId(17006014, "UpdateEntity"), $"Update entity {id} failed with internal error. {ex.GetType().Name} {ex.Message}");
                throw;
            }
        }
Пример #30
0
        /// <summary>
        /// Parses query arguments.
        /// </summary>
        /// <param name="s">The input string to parse.</param>
        /// <returns>An instance of query arguments</returns>
        public static QueryArgs Parse(string s)
        {
            if (string.IsNullOrWhiteSpace(s))
            {
                return(null);
            }
            if (!s.StartsWith("{"))
            {
                if (s.IndexOf("=") < 0 && s.IndexOf(":") < 0)
                {
                    return new QueryArgs {
                               NameQuery = s
                    }
                }
                ;
                try
                {
                    return(QueryData.Parse(s));
                }
                catch (ArgumentException)
                {
                }
                catch (FormatException)
                {
                }
                catch (InvalidOperationException)
                {
                }
                catch (NotSupportedException)
                {
                }
            }

            var json = JsonObjectNode.Parse(s);

            return(Parse(json));
        }