Esempio n. 1
0
        public static Object Deserialize(JSONELEMENT element)
        {
            if (element.ValueKind == JsonValueKind.Null)
            {
                return(null);
            }
            if (element.ValueKind == JsonValueKind.False)
            {
                return(false);
            }
            if (element.ValueKind == JsonValueKind.True)
            {
                return(true);
            }
            if (element.ValueKind == JsonValueKind.String)
            {
                return(element.GetString());
            }
            if (element.ValueKind == JsonValueKind.Number)
            {
                return(element.GetDouble());
            }
            if (element.ValueKind == JsonValueKind.Array)
            {
                return(_JsonArray.CreateFrom(element));
            }
            if (element.ValueKind == JsonValueKind.Object)
            {
                return(_JsonObject.CreateFrom(element));
            }

            throw new NotImplementedException();
        }
Esempio n. 2
0
 public async Task JsTitleClick(System.Text.Json.JsonElement ev)
 {
     if (OnTitleClick.HasDelegate)
     {
         await OnTitleClick.InvokeAsync(new ChartEvent(this, ev));
     }
 }
        public IActionResult SalvarEdicao([FromBody] System.Text.Json.JsonElement dados)
        {
            Produto prod = new Produto();
            bool    ok   = false;

            try
            {
                int catId = Convert.ToInt32(dados.GetProperty("CatId").ToString());

                prod.Id          = Convert.ToInt32(dados.GetProperty("ID").ToString());
                prod.Nome        = dados.GetProperty("Nome").ToString();
                prod.Categoria   = new Categoria(catId, dados.GetProperty("Categoria").ToString());
                prod.PrecoCompra = decimal.Parse(dados.GetProperty("vCompra").ToString());
                prod.PrecoVenda  = decimal.Parse(dados.GetProperty("vVenda").ToString());

                ok = prod.Alterar();
            }
            catch (Exception)
            {
            }

            return(Json(new
            {
                operacao = ok
            }));
        }
Esempio n. 4
0
        public static Object DeepClone(JSONELEMENT element)
        {
            if (element.ValueKind == JsonValueKind.Null)
            {
                return(null);
            }
            if (element.ValueKind == JsonValueKind.False)
            {
                return(false);
            }
            if (element.ValueKind == JsonValueKind.True)
            {
                return(true);
            }
            if (element.ValueKind == JsonValueKind.String)
            {
                return(element.GetString());
            }
            if (element.ValueKind == JsonValueKind.Number)
            {
                return(element.GetRawText());                                           // use IConvertible interface when needed.
            }
            if (element.ValueKind == JsonValueKind.Array)
            {
                return(new JsonList(element));
            }
            if (element.ValueKind == JsonValueKind.Object)
            {
                return(new JsonDictionary(element));
            }

            throw new NotImplementedException();
        }
Esempio n. 5
0
        public static object ReadValue(System.Text.Json.JsonElement elem)
        {
            if (elem.ValueKind == System.Text.Json.JsonValueKind.Object)
            {
                KeyValue[] vals = elem.EnumerateObject().ToList().SelectMany(v => DeSerializeOne(v)).ToArray();
                KeyValues  valv = new KeyValues(); valv.AddRange(vals);
                return(valv);
            }
            else if (elem.ValueKind == System.Text.Json.JsonValueKind.Array)
            {
                // déja géré par DeSerializeOne
                //KeyValue[] vals = elem.Value.EnumerateArray().ToList().Select(v => DeSerializeOne(v)).ToArray();
                //KeyValues valv = new KeyValues(); valv.AddRange(vals);
                //retour = new KeyValue(realname, valv);
                return(null);
            }
            else if (elem.ValueKind == System.Text.Json.JsonValueKind.Null || elem.ValueKind == System.Text.Json.JsonValueKind.Undefined)
            {
                return(null);
            }
            else if (elem.ValueKind == System.Text.Json.JsonValueKind.False)
            {
                return(false);
            }
            else if (elem.ValueKind == System.Text.Json.JsonValueKind.True)
            {
                return(true);
            }
            else if (elem.ValueKind == System.Text.Json.JsonValueKind.Number)
            {
                int i = 0;
                if (elem.TryGetInt32(out i))
                {
                    return(i);
                }

                long li = 0;
                if (elem.TryGetInt64(out li))
                {
                    return(li);
                }

                double di = 0;
                if (elem.TryGetDouble(out di))
                {
                    return(di);
                }

                return(elem.GetRawText()); // !!!
            }
            else if (elem.ValueKind == System.Text.Json.JsonValueKind.String)
            {
                return(elem.GetString());
            }
            else
            {
                return(elem.GetRawText());
            }
        }
Esempio n. 6
0
 public static bool TryGetProperty(Json.JsonElement e, string name, out string value)
 {
     if (e.TryGetProperty(name, out var v))
     {
         value = v.GetString();
         return(true);
     }
     value = default;
     return(false);
 }
Esempio n. 7
0
        public IActionResult Gravar([FromBody] System.Text.Json.JsonElement dados)
        {
            string msg   = "Falha ao Gravar Livro!";
            Livro  livro = new LivroDAL().seleciona(Convert.ToInt32(dados.GetProperty("idLivro").ToString()));

            if (livro == null)
            {
                string nome = dados.GetProperty("nome").ToString();
                int    editoraId;
                Int32.TryParse(dados.GetProperty("editora").ToString(), out editoraId);
                int        contautores = dados.GetProperty("autor").GetArrayLength();
                List <int> autoresId   = new List <int>();
                int        qtd;
                Int32.TryParse(dados.GetProperty("qtd").ToString(), out qtd);
                for (int i = 0; i < contautores; i++)
                {
                    autoresId.Add(Convert.ToInt32(dados.GetProperty("autor")[i].ToString()));
                }
                Editora       editora = new Editora().obterEditoraPorID(editoraId);
                List <Autor>  autores = new Autor().obterAutoresPorListID(autoresId);
                Administrador adm     = new Administrador().obter("Leonardo Custodio dos Santos");
                msg = "Preencha Todos os Campos!!!";
                if (nome.Trim().Length > 0 && editoraId != 0 && contautores > 0 && autoresId != null && qtd > 0 && editora != null && autores != null && adm != null)
                {
                    msg = new Livro().Gravar(nome, autores, editora, adm, qtd);
                }
            }
            else
            {
                string nome = dados.GetProperty("nome").ToString();
                int    editoraId;
                Int32.TryParse(dados.GetProperty("editora").ToString(), out editoraId);
                int        contautores = dados.GetProperty("autor").GetArrayLength();
                List <int> autoresId   = new List <int>();
                int        qtd;
                Int32.TryParse(dados.GetProperty("qtd").ToString(), out qtd);
                for (int i = 0; i < contautores; i++)
                {
                    autoresId.Add(Convert.ToInt32(dados.GetProperty("autor")[i].ToString()));
                }
                Editora       editora = new Editora().obterEditoraPorID(editoraId);
                List <Autor>  autores = new Autor().obterAutoresPorListID(autoresId);
                Administrador adm     = new Administrador().obter("Leonardo Custodio dos Santos");
                msg = "Preencha Todos os Campos!!!";
                if (nome.Trim().Length > 0 && editoraId != 0 && contautores > 0 && autoresId != null && qtd > 0 && editora != null && autores != null && adm != null)
                {
                    msg = new Livro().Alterar(nome, autores, editora, adm, qtd);
                }
            }

            return(Json(new
            {
                msg
            }));
        }
Esempio n. 8
0
        public IActionResult Pesquisar([FromBody] System.Text.Json.JsonElement dados)
        {
            string       termoPesquisado = dados.GetProperty("termo").ToString();
            string       tipoPesquisado  = dados.GetProperty("tipo").ToString();
            List <Livro> livros          = new Livro().PesquisarLivros(termoPesquisado, tipoPesquisado);

            return(Json(new
            {
                livros
            }));
        }
Esempio n. 9
0
        internal JsonDictionary(JSONELEMENT element)
        {
            if (element.ValueKind != JsonValueKind.Object)
            {
                throw new ArgumentException("Must be JsonValueKind.Object", nameof(element));
            }

            foreach (var item in element.EnumerateObject())
            {
                this[item.Name] = JsonValue.DeepClone(item.Value);
            }
        }
Esempio n. 10
0
        internal JsonList(JSONELEMENT element)
        {
            if (element.ValueKind != JsonValueKind.Array)
            {
                throw new ArgumentException("Must be JsonValueKind.Array", nameof(element));
            }

            foreach (var item in element.EnumerateArray())
            {
                var xitem = JsonValue.DeepClone(item);
                this.Add(xitem);
            }
        }
Esempio n. 11
0
        public static _JsonArray CreateFrom(JSONELEMENT array)
        {
            if (array.ValueKind != JsonValueKind.Array)
            {
                throw new ArgumentException("Must be JsonValueKind.Array", nameof(array));
            }

            Object convert(JsonElement element)
            {
                return(_JsonStaticUtils.Deserialize(element));
            }

            using (var entries = array.EnumerateArray())
            {
                return(_From(entries.Select(convert)));
            }
        }
Esempio n. 12
0
        public List <PredictionTransfer> GetPrediction([FromBody] System.Text.Json.JsonElement data)
        {
            //0 - Deserialize the JSON Object
            List <ModelInput>         intradayList   = JsonConvert.DeserializeObject <List <ModelInput> >(data.ToString());
            List <PredictionTransfer> predictionList = new List <PredictionTransfer>();

            if (intradayList.Count == 0)
            {
                return(predictionList);
            }

            //1 - Add RSI and MACD
            TradeIndicator.CalculateIndicator(ref intradayList);

            //2 - List models available

            var rootFolder    = Environment.CurrentDirectory + "/AI/";
            var modelPathList = Directory.GetFiles(rootFolder, "*", SearchOption.AllDirectories);

            if (modelPathList.Length == 0)
            {
                return(predictionList);
            }

            //3 - Iterate throw model and fire prediction
            foreach (var modelPath in modelPathList)
            {
                PredictionTransfer prediction = new PredictionTransfer();

                var fromIndex = Path.GetFileName(modelPath).IndexOf("-") + 1;
                var toIndex   = Path.GetFileName(modelPath).Length - fromIndex - 4;
                prediction.ModelName = Path.GetFileName(modelPath).Substring(fromIndex, toIndex);

                prediction.Future   = CalculatePrediction(intradayList.Last(), modelPath).Future;
                prediction.Rsi      = intradayList.Last().Rsi;
                prediction.Macd     = intradayList.Last().Macd;
                prediction.MacdHist = intradayList.Last().MacdHist;
                prediction.MacdSign = intradayList.Last().MacdSign;
                predictionList.Add(prediction);
            }

            return(predictionList);
        }
Esempio n. 13
0
        public static _JsonObject CreateFrom(JSONELEMENT dict)
        {
            if (dict.ValueKind != JsonValueKind.Object)
            {
                throw new ArgumentException("Must be JsonValueKind.Object", nameof(dict));
            }

            JSONPROPERTY convert(JsonProperty property)
            {
                var value = _JsonStaticUtils.Deserialize(property.Value);

                return(new JSONPROPERTY(property.Name, value));
            }

            using (var entries = dict.EnumerateObject())
            {
                return(new _JsonObject(dict.EnumerateObject().Select(convert)));
            }
        }
Esempio n. 14
0
        public async void Post([FromBody] JsonDocument gg)
        {
            // Console.WriteLine(gg.GetRawText());
            // Console.WriteLine(gg.GetProperty("board"));
            if (gg == null)
            {
                return;
            }
            // Console.WriteLine(gg);
            var g = gg;

            // var g = JsonDocument.Parse(gg.ToString());
            //string [][] ids = JsonSerializer.Deserialize<string[][]>(gg.GetProperty("board").GetRawText());
            //g.RootElement.GetProperty("board").
            string[][] ids = JsonSerializer.Deserialize <string[][]>(g.RootElement.GetProperty("board").ToString());
            System.Text.Json.JsonElement a = new System.Text.Json.JsonElement();
            int cnt = g.RootElement.GetProperty("garbage").GetInt32();
            // Console.WriteLine("-----------------------------------------------------------------");
            // Console.WriteLine("garbage = " + cnt);
            await Task.Run(() =>
            {
                //char[] ff = new char[400];
                int[,] ff = new int[40, 10];

                int idx = 0;
                for (int i = 39; i >= 0; --i)
                {
                    for (int j = 0; j < 10; ++j)
                    {
                        if (ids[i][j] != null)
                        {
                            ff[39 - i, j] = 1;
                        }
                        //ff[(39 - i) * 10 + j] = (char)1;
                    }
                }

                bot.zzz_toj.resetBoard(ff);
                bot.zzz_toj.updategar(cnt);
            });
        }
        /// <summary>
        /// Alimenta ViewBags
        /// </summary>
        /// <param name="dados">Dados json frombody</param>
        public void AlimentarDados([FromBody] System.Text.Json.JsonElement dados)
        {
            Produto   prod = new Produto();
            Categoria cat  = new Categoria();

            try
            {
                cat.Id   = Convert.ToInt32(dados.GetProperty("CatId").ToString());
                cat.Nome = dados.GetProperty("Categoria").ToString();

                prod.Id          = Convert.ToInt32(dados.GetProperty("ProdutoId").ToString());
                prod.Nome        = dados.GetProperty("Nome").ToString();
                prod.PrecoCompra = decimal.Parse(dados.GetProperty("vCompra").ToString());
                prod.PrecoVenda  = decimal.Parse(dados.GetProperty("vVenda").ToString());

                /* ALIMENTA VIEWBAGS */
                ViewBag.Produto   = prod;
                ViewBag.Categoria = cat;
            }
            catch
            { }
        }
        public IActionResult ConsultarCarrinho([FromBody] System.Text.Json.JsonElement dados)
        {
            ProdutoDAL     pd    = new ProdutoDAL();
            List <Produto> lista = new List <Produto>();

            JavaScriptSerializer js = new JavaScriptSerializer();

            LSProd[] lsprods = js.Deserialize <LSProd[]>(dados.ToString());

            foreach (var item in lsprods)
            {
                lista.Add(pd.getProduto(item.Prodid));
            }

            bool ok = (lista != null && lista.Count > 0);

            return(Json(new
            {
                operacao = ok,
                lista = lista
            }
                        ));
        }
Esempio n. 17
0
 public static System.Collections.Generic.IDictionary <string, string> ToDictionary(System.Text.Json.JsonElement jElement)
 {
     if (jElement.ValueKind != System.Text.Json.JsonValueKind.String)
     {
         return(null);
     }
     try
     {
         var jObject = JsonBase.FromJson <System.Text.Json.JsonElement>(jElement.GetString());
         var dict    = new System.Collections.Generic.Dictionary <string, string>();
         foreach (var item in jObject.EnumerateObject().OfType <JsonProperty>())
         {
             dict[item.Name] = item.Value.GetString();
         }
         return(dict);
     }
     catch (System.Exception ex)
     {
         // TODO Logging
     }
     return(null);
 }
Esempio n. 18
0
 internal IEnumerable <JsonElement?> Evaluate(JsonElement root, JsonElement t, bool errorWhenNoMatch)
 {
     return(Evaluate(Filters, root, t, errorWhenNoMatch));
 }
Esempio n. 19
0
        internal static IEnumerable <JsonElement?> Evaluate(List <PathFilter> filters, JsonElement root, JsonElement t, bool errorWhenNoMatch)
        {
            IEnumerable <JsonElement?> current = new JsonElement?[] { t };

            foreach (PathFilter filter in filters)
            {
                current = filter.ExecuteFilter(root, current, errorWhenNoMatch);
            }

            return(current);
        }
Esempio n. 20
0
        /// <summary>
        ///   This is an implementation detail and MUST NOT be called by source-package consumers.
        /// </summary>
        internal bool TryGetNamedPropertyValue(int index, ReadOnlySpan <byte> propertyName, out JsonElement value)
        {
            CheckNotDisposed();

            DbRow row = _parsedData.Get(index);

            CheckExpectedType(JsonTokenType.StartObject, row.TokenType);

            // Only one row means it was EndObject.
            if (row.NumberOfRows == 1)
            {
                value = default;
                return(false);
            }

            int endIndex = checked (row.NumberOfRows * DbRow.Size + index);

            return(TryGetNamedPropertyValue(
                       index + DbRow.Size,
                       endIndex,
                       propertyName,
                       out value));
        }
Esempio n. 21
0
        /// <summary>
        ///   This is an implementation detail and MUST NOT be called by source-package consumers.
        /// </summary>
        internal bool TryGetNamedPropertyValue(int index, ReadOnlySpan <char> propertyName, out JsonElement value)
        {
            CheckNotDisposed();

            DbRow row = _parsedData.Get(index);

            CheckExpectedType(JsonTokenType.StartObject, row.TokenType);

            // Only one row means it was EndObject.
            if (row.NumberOfRows == 1)
            {
                value = default;
                return(false);
            }

            int maxBytes   = JsonReaderHelper.s_utf8Encoding.GetMaxByteCount(propertyName.Length);
            int startIndex = index + DbRow.Size;
            int endIndex   = checked (row.NumberOfRows * DbRow.Size + index);

            if (maxBytes < JsonConstants.StackallocThreshold)
            {
                Span <byte> utf8Name = stackalloc byte[JsonConstants.StackallocThreshold];
                int         len      = JsonReaderHelper.GetUtf8FromText(propertyName, utf8Name);
                utf8Name = utf8Name.Slice(0, len);

                return(TryGetNamedPropertyValue(
                           startIndex,
                           endIndex,
                           utf8Name,
                           out value));
            }

            // Unescaping the property name will make the string shorter (or the same)
            // So the first viable candidate is one whose length in bytes matches, or
            // exceeds, our length in chars.
            //
            // The maximal escaping seems to be 6 -> 1 ("\u0030" => "0"), but just transcode
            // and switch once one viable long property is found.

            int minBytes = propertyName.Length;
            // Move to the row before the EndObject
            int candidateIndex = endIndex - DbRow.Size;

            while (candidateIndex > index)
            {
                int passedIndex = candidateIndex;

                row = _parsedData.Get(candidateIndex);
                Debug.Assert(row.TokenType != JsonTokenType.PropertyName);

                // Move before the value
                if (row.IsSimpleValue)
                {
                    candidateIndex -= DbRow.Size;
                }
                else
                {
                    Debug.Assert(row.NumberOfRows > 0);
                    candidateIndex -= DbRow.Size * (row.NumberOfRows + 1);
                }

                row = _parsedData.Get(candidateIndex);
                Debug.Assert(row.TokenType == JsonTokenType.PropertyName);

                if (row.SizeOrLength >= minBytes)
                {
                    byte[] tmpUtf8 = ArrayPool <byte> .Shared.Rent(maxBytes);

                    Span <byte> utf8Name = default;

                    try
                    {
                        int len = JsonReaderHelper.GetUtf8FromText(propertyName, tmpUtf8);
                        utf8Name = tmpUtf8.AsSpan(0, len);

                        return(TryGetNamedPropertyValue(
                                   startIndex,
                                   passedIndex + DbRow.Size,
                                   utf8Name,
                                   out value));
                    }
                    finally
                    {
                        // While property names aren't usually a secret, they also usually
                        // aren't long enough to end up in the rented buffer transcode path.
                        //
                        // On the basis that this is user data, go ahead and clear it.
                        utf8Name.Clear();
                        ArrayPool <byte> .Shared.Return(tmpUtf8);
                    }
                }

                // Move to the previous value
                candidateIndex -= DbRow.Size;
            }

            // None of the property names were within the range that the UTF-8 encoding would have been.
            value = default;
            return(false);
        }
Esempio n. 22
0
        private bool TryGetNamedPropertyValue(
            int startIndex,
            int endIndex,
            ReadOnlySpan <byte> propertyName,
            out JsonElement value)
        {
            ReadOnlySpan <byte> documentSpan = _utf8Json.Span;

            // Move to the row before the EndObject
            int index = endIndex - DbRow.Size;

            while (index > startIndex)
            {
                DbRow row = _parsedData.Get(index);
                Debug.Assert(row.TokenType != JsonTokenType.PropertyName);

                // Move before the value
                if (row.IsSimpleValue)
                {
                    index -= DbRow.Size;
                }
                else
                {
                    Debug.Assert(row.NumberOfRows > 0);
                    index -= DbRow.Size * (row.NumberOfRows + 1);
                }

                row = _parsedData.Get(index);
                Debug.Assert(row.TokenType == JsonTokenType.PropertyName);

                ReadOnlySpan <byte> currentPropertyName = documentSpan.Slice(row.Location, row.SizeOrLength);

                if (row.HasComplexChildren)
                {
                    // An escaped property name will be longer than an unescaped candidate, so only unescape
                    // when the lengths are compatible.
                    if (currentPropertyName.Length > propertyName.Length)
                    {
                        int idx = currentPropertyName.IndexOf(JsonConstants.BackSlash);
                        Debug.Assert(idx >= 0);

                        // If everything up to where the property name has a backslash matches, keep going.
                        if (propertyName.Length > idx &&
                            currentPropertyName.Slice(0, idx).SequenceEqual(propertyName.Slice(0, idx)))
                        {
                            int    remaining = currentPropertyName.Length - idx;
                            int    written   = 0;
                            byte[] rented    = null;

                            try
                            {
                                Span <byte> utf8Unescaped = remaining <= JsonConstants.StackallocThreshold ?
                                                            stackalloc byte[remaining] :
                                                            (rented = ArrayPool <byte> .Shared.Rent(remaining));

                                // Only unescape the part we haven't processed.
                                JsonReaderHelper.Unescape(currentPropertyName.Slice(idx), utf8Unescaped, 0, out written);

                                // If the unescaped remainder matches the input remainder, it's a match.
                                if (utf8Unescaped.Slice(0, written).SequenceEqual(propertyName.Slice(idx)))
                                {
                                    // If the property name is a match, the answer is the next element.
                                    value = new JsonElement(this, index + DbRow.Size);
                                    return(true);
                                }
                            }
                            finally
                            {
                                if (rented != null)
                                {
                                    rented.AsSpan(0, written).Clear();
                                    ArrayPool <byte> .Shared.Return(rented);
                                }
                            }
                        }
                    }
                }
                else if (currentPropertyName.SequenceEqual(propertyName))
                {
                    // If the property name is a match, the answer is the next element.
                    value = new JsonElement(this, index + DbRow.Size);
                    return(true);
                }

                // Move to the previous value
                index -= DbRow.Size;
            }

            value = default;
            return(false);
        }
Esempio n. 23
0
 void IBaubleButton.LoadFromJson(System.Text.Json.JsonElement json)
 {
     Text = json.GetProperty("text").GetString();
 }
Esempio n. 24
0
 internal JsonProperty(JsonElement value, string?name = null)
 {
     Value = value;
     _name = name;
 }
        public bool TryGet <T>(string key, out T value)
        {
            if (storage.TryGetValue(key, out object target))
            {
                if (target == null)
                {
                    value = default(T);
                    return(true);
                }

                log.Debug($"Get: Key: '{key}', RequiredType: '{typeof(T).FullName}', ActualType: '{target.GetType().FullName}'.");

                if (target is T targetValue)
                {
                    value = targetValue;
                    return(true);
                }

                JsonElement element = (JsonElement)target;

                if (typeof(T) == typeof(string))
                {
                    value = (T)(object)element.GetString();
                    return(true);
                }

                if (typeof(T) == typeof(int))
                {
                    value = (T)(object)element.GetInt32();
                    return(true);
                }

                if (typeof(T) == typeof(long))
                {
                    value = (T)(object)element.GetInt64();
                    return(true);
                }

                if (typeof(T) == typeof(decimal))
                {
                    value = (T)(object)element.GetDecimal();
                    return(true);
                }

                if (typeof(T) == typeof(double))
                {
                    value = (T)(object)element.GetDouble();
                    return(true);
                }

                if (typeof(T) == typeof(bool))
                {
                    value = (T)(object)element.GetBoolean();
                    return(true);
                }

                if (typeof(T) == typeof(IKey))
                {
                    if (element.ValueKind == JsonValueKind.Null)
                    {
                        value = default(T);
                        return(true);
                    }

                    string type = element.GetProperty("Type").GetString();
                    if (element.TryGetProperty("Guid", out JsonElement rawGuid))
                    {
                        string rawGuidValue = rawGuid.GetString();
                        if (rawGuidValue == null)
                        {
                            value = (T)(object)GuidKey.Empty(type);
                        }
                        else
                        {
                            value = (T)(object)GuidKey.Create(Guid.Parse(rawGuidValue), type);
                        }

                        return(true);
                    }
                    else if (element.TryGetProperty("Identifier", out JsonElement rawIdentifier))
                    {
                        string rawIdentifierValue = rawIdentifier.GetString();
                        if (rawIdentifierValue == null)
                        {
                            value = (T)(object)StringKey.Empty(type);
                        }
                        else
                        {
                            value = (T)(object)StringKey.Create(rawIdentifierValue, type);
                        }

                        return(true);
                    }
                }

                if (typeof(T) == typeof(Color))
                {
                    byte[] parts = element.GetString().Split(new char[] { ';' }).Select(p => Byte.Parse(p)).ToArray();
                    value = (T)(object)Color.FromArgb(parts[0], parts[1], parts[2], parts[3]);
                    log.Debug($"Get: Color: '{value}'.");
                    return(true);
                }

                if (typeof(T) == typeof(Price))
                {
                    log.Debug($"Get: Price value type: '{element.GetProperty("Value").GetType().FullName}'.");
                    decimal priceValue    = element.GetProperty("Value").GetDecimal();
                    string  priceCurrency = element.GetProperty("Currency").GetString();
                    value = (T)(object)new Price(priceValue, priceCurrency);
                    return(true);
                }

                if (typeof(T) == typeof(DateTime))
                {
                    string rawDateTime = element.GetString();
                    if (DateTime.TryParse(rawDateTime, out DateTime dateTime))
                    {
                        value = (T)(object)dateTime;
                        return(true);
                    }
                    else
                    {
                        log.Warning($"Get: Key: '{key}' not parseable to datetime from value '{rawDateTime}'.");
                        value = default(T);
                        return(false);
                    }
                }
            }

            log.Debug($"Get: Key: '{key}' NOT FOUND. Storage: '{JsonSerializer.Serialize(storage)}'.");
            value = default(T);
            return(false);
        }
        public IActionResult Gravar([FromBody] System.Text.Json.JsonElement dados)
        {
            string  msg      = "";
            bool    operacao = false;
            Produto prod     = new Produto();

            string sId = dados.GetProperty("ProdId").ToString();
            int    id  = 0;

            if (sId != null && !sId.Equals("0"))
            {
                id = Convert.ToInt32(sId);
            }

            try
            {
                int catId = Convert.ToInt32(dados.GetProperty("catId").ToString());

                prod.Nome        = dados.GetProperty("Nome").ToString();
                prod.Categoria   = new Categoria(catId, dados.GetProperty("Categoria").ToString());
                prod.PrecoCompra = decimal.Parse(dados.GetProperty("vCompra").ToString());
                prod.PrecoVenda  = decimal.Parse(dados.GetProperty("vVenda").ToString());


                if (id > 0)
                {
                    prod.Id = id;
                    if (prod.Alterar())
                    {
                        operacao = true;
                        msg      = "Produto " + prod.Nome + " foi alterado com sucesso!";
                    }
                    else
                    {
                        msg = "Houve algum problema ao alterar " + prod.Nome + " no Banco de Dados.";
                    }
                }
                else
                {
                    if (prod.Gravar())
                    {
                        prod.Id  = prod.getMaxPK();
                        operacao = true;
                        msg      = "Produto " + prod.Nome + " foi cadastrado com sucesso!";
                    }
                    else
                    {
                        msg = "Houve algum problema ao gravar " + prod.Nome + " no Banco de Dados.";
                    }
                }
            }
            catch (Exception ex)
            {
                msg = "[Produto/Cadastrar]: " + ex.Message;
            }



            return(Json(new
            {
                operacao = operacao,
                msg = msg,
                id = prod.Id
            }));
        }