Пример #1
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
            }));
        }
        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
            }));
        }
        /// <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
            { }
        }
Пример #4
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
            }));
        }
Пример #5
0
 void IBaubleButton.LoadFromJson(System.Text.Json.JsonElement json)
 {
     Text = json.GetProperty("text").GetString();
 }
Пример #6
0
        private static void AssertJsonEqualCore(JsonElement expected, JsonElement actual, Stack <object> path)
        {
            JsonValueKind valueKind = expected.ValueKind;

            AssertTrue(passCondition: valueKind == actual.ValueKind);

            switch (valueKind)
            {
            case JsonValueKind.Object:
                var expectedProperties = new List <string>();
                foreach (JsonProperty property in expected.EnumerateObject())
                {
                    expectedProperties.Add(property.Name);
                }

                var actualProperties = new List <string>();
                foreach (JsonProperty property in actual.EnumerateObject())
                {
                    actualProperties.Add(property.Name);
                }

                foreach (var property in expectedProperties.Except(actualProperties))
                {
                    AssertTrue(passCondition: false, $"Property \"{property}\" missing from actual object.");
                }

                foreach (var property in actualProperties.Except(expectedProperties))
                {
                    AssertTrue(passCondition: false, $"Actual object defines additional property \"{property}\".");
                }

                foreach (string name in expectedProperties)
                {
                    path.Push(name);
                    AssertJsonEqualCore(expected.GetProperty(name), actual.GetProperty(name), path);
                    path.Pop();
                }
                break;

            case JsonValueKind.Array:
                JsonElement.ArrayEnumerator expectedEnumerator = expected.EnumerateArray();
                JsonElement.ArrayEnumerator actualEnumerator   = actual.EnumerateArray();

                int i = 0;
                while (expectedEnumerator.MoveNext())
                {
                    AssertTrue(passCondition: actualEnumerator.MoveNext(), "Actual array contains fewer elements.");
                    path.Push(i++);
                    AssertJsonEqualCore(expectedEnumerator.Current, actualEnumerator.Current, path);
                    path.Pop();
                }

                AssertTrue(passCondition: !actualEnumerator.MoveNext(), "Actual array contains additional elements.");
                break;

            case JsonValueKind.String:
                AssertTrue(passCondition: expected.GetString() == actual.GetString());
                break;

            case JsonValueKind.Number:
            case JsonValueKind.True:
            case JsonValueKind.False:
            case JsonValueKind.Null:
                AssertTrue(passCondition: expected.GetRawText() == actual.GetRawText());
                break;

            default:
                Debug.Fail($"Unexpected JsonValueKind: JsonValueKind.{valueKind}.");
                break;
            }

            void AssertTrue(bool passCondition, string?message = null)
            {
                if (!passCondition)
                {
                    message ??= "Expected JSON does not match actual value";
                    Assert.Fail($"{message}\nExpected JSON: {expected}\n  Actual JSON: {actual}\n  in JsonPath: {BuildJsonPath(path)}");
                }
        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
            }));
        }