Esempio n. 1
0
        public IActionResult Gravar([FromBody] System.Text.Json.JsonElement dados)
        {
            //cpf
            //livro

            string     msg        = "Falha ao Gravar Emprestimo!";
            List <int> livrosId   = new List <int>();
            string     cpf        = dados.GetProperty("cpf").ToString();
            int        contlivros = dados.GetProperty("livro").GetArrayLength();

            for (int i = 0; i < contlivros; i++)
            {
                livrosId.Add(Convert.ToInt32(dados.GetProperty("livro")[i].ToString()));
            }
            List <Livro> livros = new LivroDAL().obterLivrosPorListID(livrosId);

            if (cpf.Length > 0 && contlivros > 0)
            {
                msg = new Emprestimo().Gravar(cpf, livros);
            }
            return(Json(new
            {
                msg
            }));
        }
Esempio n. 2
0
        public IActionResult Insert([FromBody] System.Text.Json.JsonElement data)
        {
            bool   operation = false;
            string msg       = "";

            //string id = data.GetProperty("id").ToString();

            /*string name = data.GetProperty("name").ToString();
             * string category = data.GetProperty("category").ToString();
             * string sellPrice = data.GetProperty("sellPrice").ToString();
             * string buyPrice = data.GetProperty("buyPrice").ToString();*/

            Models.Product prod = new Models.Product();

            prod.Name      = data.GetProperty("name").ToString();
            prod.Category  = data.GetProperty("category").ToString();
            prod.SellPrice = Convert.ToDecimal(data.GetProperty("sellPrice").ToString());
            prod.BuyPrice  = Convert.ToDecimal(data.GetProperty("buyPrice").ToString());

            if (prod.Insert())
            {
                operation = true;
                msg       = "Produto cadastrado com sucesso";
            }
            else
            {
                msg = "Dados inválidos";
            }

            return(Json(new
            {
                operation = operation,
                msg = msg
            }));
        }
Esempio n. 3
0
 void IBaubleButton.LoadFromJson(System.Text.Json.JsonElement json)
 {
     _imageFilePath    = json.GetProperty("image").GetString();
     Text              = json.GetProperty("text").GetString();
     ExecutablePath    = json.GetProperty("executable").GetString();
     _workingDirectory = json.GetProperty("workingDirectory").GetString();
     _arguments        = json.GetProperty("arguments").GetString();
 }
        public IActionResult Logar([FromBody] System.Text.Json.JsonElement dados, [FromServices] SigningConfiguration signingConfiguration)
        {
            string usuario = dados.GetProperty("usuario").ToString();
            string senha   = dados.GetProperty("senha").ToString();

            //obteve usuário.. Nome, email....
            string nome  = "Andre Menegassi";
            string email = "*****@*****.**";
            string id    = "123456";

            if (usuario == "adm" && senha == "123")
            {
                var ig        = new GenericIdentity(id, "id");
                var isecEMail = new Claim(JwtRegisteredClaimNames.Email, email);
                var isecNome  = new Claim(JwtRegisteredClaimNames.GivenName, nome);

                var identidade = new ClaimsIdentity(ig, new Claim[] { isecEMail, isecNome });

                //var provider = new RSACryptoServiceProvider(2048);
                //SecurityKey chave = new RsaSecurityKey(provider.ExportParameters(true));

                var handler    = new JwtSecurityTokenHandler();
                var dadosToken = handler.CreateToken(new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor
                {
                    Audience           = _appSettings.Audencie,
                    Issuer             = _appSettings.Issuer,
                    NotBefore          = DateTime.Now,
                    Expires            = DateTime.Now.AddDays(_appSettings.Days),
                    Subject            = identidade,
                    SigningCredentials = signingConfiguration.SigningCredentials
                });

                string token = handler.WriteToken(dadosToken);

                return(Ok(new
                {
                    operacao = true,
                    token
                }));
            }
            else
            {
                return(NotFound(new
                {
                    operacao = false,
                }));
            }
        }
Esempio n. 5
0
        public ActionResult <string> UpdateQuestion([FromBody] System.Text.Json.JsonElement inputData)
        {
            short  QuestionID       = 0;
            string Description      = string.Empty;
            bool   AllowYesNo       = false;
            bool   AllowShortAnswer = false;

            try
            {
                QuestionID       = inputData.GetProperty("QuestionID").GetInt16();
                Description      = inputData.GetProperty("Description").GetString();
                AllowYesNo       = inputData.GetProperty("AllowYesNo").GetBoolean();
                AllowShortAnswer = inputData.GetProperty("AllowShortAnswer").GetBoolean();
            }
            catch (Exception ex)
            {
                return(StatusCode(StatusCodes.Status400BadRequest, $"Survey InsertQuestion - Invalid parameters detected"));
            }

            DataAccess.SurveyAccess dataAccess = new DataAccess.SurveyAccess();
            try
            {
                bool bResult = dataAccess.UpdateQuestion(QuestionID, Description, AllowYesNo, AllowShortAnswer);
                if (dataAccess._lastSqlException != null && !string.IsNullOrWhiteSpace(dataAccess._lastSqlException.Message))
                {
                    return(StatusCode(StatusCodes.Status500InternalServerError, dataAccess._lastSqlException.Message));
                }
                else
                {
                    //Build output
                    Output output = new Output(bResult, null);
                    return(Ok(JsonConvert.SerializeObject(output)));
                }
            }
            catch (Exception x)
            {
                if (dataAccess._lastSqlException != null && !string.IsNullOrWhiteSpace(dataAccess._lastSqlException.Message))
                {
                    return(StatusCode(StatusCodes.Status500InternalServerError, dataAccess._lastSqlException.Message));
                }
                else
                {
                    return(StatusCode(StatusCodes.Status500InternalServerError, x.Message));
                }
            }
        }
Esempio n. 6
0
        public IActionResult Login([FromBody] System.Text.Json.JsonElement data)
        {
            bool   operation = false;
            string msg       = "";
            string email     = data.GetProperty("email").ToString();
            string password  = data.GetProperty("password").ToString();

            Models.User user = new Models.User();

            if (user.AuthentifyPassword(email, password))
            {
                operation = true;
                msg       = "Bem-vindo";

                #region Gerando Cookie de Autorização

                var userClaims = new List <Claim>();
                userClaims.Add(new Claim("id", email));
                //userClaims.Add(new Claim("name", user.Name));

                var identity = new ClaimsIdentity(userClaims, "Identificação do Usuario");

                ClaimsPrincipal principal = new ClaimsPrincipal(identity);

                //Gerando cookie
                Microsoft.AspNetCore.Authentication.AuthenticationHttpContextExtensions.SignInAsync(HttpContext, principal);


                #endregion
            }
            else
            {
                msg = "Dados inválidos";
            }

            return(Json(new
            {
                operation = operation,
                msg = msg
            }));
        }
Esempio n. 7
0
        public IActionResult Logar([FromBody] System.Text.Json.JsonElement dados)
        {
            Usuario user = new Usuario();
            bool    ok   = false;

            user.Email = dados.GetProperty("Email").ToString();
            user.Senha = dados.GetProperty("Senha").ToString();


            if (user.ValidarLogin() && user.getUsuario(user.Email))
            {
                ok = true;

                #region gerando Cookie de Autorização

                var userClaims = new List <Claim>();

                userClaims.Add(new Claim("id", user.Email));
                userClaims.Add(new Claim("nome", user.Nome));

                //identidades - é possível ter varias
                var identity = new ClaimsIdentity(userClaims, "Identificação do Usuário");

                //define identity princiapal
                ClaimsPrincipal principal = new ClaimsPrincipal(identity);

                //Gerando o cookie.
                Microsoft.AspNetCore.Authentication.AuthenticationHttpContextExtensions.SignInAsync(HttpContext, principal);

                #endregion
            }



            //retorna objeto anonimo
            return(Json(new
            {
                operacao = ok,
                userName = user.Nome
            }));
        }
Esempio n. 8
0
        public void AtribuirNome([FromBody] System.Text.Json.JsonElement dados)
        {
            string userName = dados.GetProperty("Nome").ToString();

            if (userName != "")
            {
                ViewData["userName"] = userName;
            }
            else
            {
                ViewData["userName"] = "******";
            }
        }
Esempio n. 9
0
        static void Main(string[] args)
        {
            while (true)
            {
                var client    = new HttpClient();
                var request   = new HttpRequestMessage(HttpMethod.Get, "http://*****:*****@localhost:15672/api/queues");
                var byteArray = Encoding.ASCII.GetBytes("guest:guest");
                request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
                var result = client.SendAsync(request).Result;
                var list   = System.Text.Json.JsonSerializer.Deserialize <dynamic>(result.Content.ReadAsStringAsync().Result);

                Console.WriteLine("------------");
                for (var i = 0; i < list.GetArrayLength(); i++)
                {
                    System.Text.Json.JsonElement item = list[i];
                    Console.WriteLine(item.GetProperty("backing_queue_status").GetProperty("len").GetInt32());
                }
                System.Threading.Thread.Sleep(1000);
            }
        }
Esempio n. 10
0
        public ActionResult <string> DeleteQuestion([FromBody] System.Text.Json.JsonElement inputData)
        {
            short QuestionID = 0;

            try
            {
                QuestionID = inputData.GetProperty("QuestionID").GetInt16();
            }
            catch (Exception ex)
            {
                return(StatusCode(StatusCodes.Status400BadRequest, $"Survey DeleteQuestion - Invalid parameters detected"));
            }

            DataAccess.SurveyAccess dataAccess = new DataAccess.SurveyAccess();
            try
            {
                bool bResult = dataAccess.DeleteQuestion(QuestionID);
                if (dataAccess._lastSqlException != null && !string.IsNullOrWhiteSpace(dataAccess._lastSqlException.Message))
                {
                    return(StatusCode(StatusCodes.Status500InternalServerError, dataAccess._lastSqlException.Message));
                }
                else
                {
                    //Build output
                    Output output = new Output(bResult, null);
                    return(Ok(JsonConvert.SerializeObject(output)));
                }
            }
            catch (Exception x)
            {
                if (dataAccess._lastSqlException != null && !string.IsNullOrWhiteSpace(dataAccess._lastSqlException.Message))
                {
                    return(StatusCode(StatusCodes.Status500InternalServerError, dataAccess._lastSqlException.Message));
                }
                else
                {
                    return(StatusCode(StatusCodes.Status500InternalServerError, x.Message));
                }
            }
        }
Esempio n. 11
0
 void IBaubleButton.LoadFromJson(System.Text.Json.JsonElement json)
 {
     Text = json.GetProperty("text").GetString();
 }
Esempio n. 12
0
        public IActionResult Adicionar([FromBody] System.Text.Json.JsonElement item)
        {
            string x = item.GetProperty("item").ToString();

            return(Ok(true));
        }
Esempio n. 13
0
        //public object SaveContact([FromBody] dynamic data)//
        //public object SaveContact([FromBody] Contact contact)
        //public async Task SaveContact()
        public Object SaveContact([FromBody] System.Text.Json.JsonElement entity) //[FromBody]Newtonsoft.Json.Linq.JObject value
        {
            try
            {
                ApplicationUser user = GetUserAsync().Result;
                this.db.Users.Include(u => u.Account.Contacts).First(u => u == user);



                //var huy = value.for

                var     p   = entity.GetProperty("params");
                var     idv = p.GetProperty("id");
                int     id  = idv.GetInt32();
                Contact contact;
                if (id != 0)
                {
                    contact = user.Account.Contacts.FirstOrDefault(c => c.Id == id);
                }
                else
                {
                    contact = new Contact();
                }


                var    photov     = p.GetProperty("photo");
                var    namev      = photov.GetProperty("name");
                var    imageDatav = photov.GetProperty("imageData");
                string imageData  = imageDatav.GetString();
                Image  image;
                if (!String.IsNullOrEmpty(imageData))
                {
                    image = new Image()
                    {
                        Name = namev.GetString(), ImageData = imageData
                    };
                    db.Images.Add(image);
                    contact.Photo = image;
                }


                var dateOfBirthv = p.GetProperty("dateOfBirth");
                DateTime.TryParse(dateOfBirthv.GetString(), out var parsedDateValue);

                // Объединяем полученные значения в один объект DateTime
                DateTime fullDateTime = new DateTime(parsedDateValue.Year,
                                                     parsedDateValue.Month,
                                                     parsedDateValue.Day);
                contact.DateOfBirth = fullDateTime;

                string position = p.GetProperty("position").GetString();
                if (!String.IsNullOrEmpty(position))
                {
                    contact.Position = position;
                }

                var phonesv = p.GetProperty("phones").EnumerateArray();
                foreach (var res in phonesv)
                {
                    var obj = res.EnumerateObject();
                    if (obj.GetType() == null)
                    {
                        continue;                       ///??????????????????????????????????????????????????????????????????????????????
                    }
                    Phone item = new Phone();
                    foreach (var prop in obj)
                    {
                        if (prop.Value.GetString() == "")
                        {
                            continue;                              ///???????????????????????????????????????????????????????????????????????
                        }
                        PropertyInfo propertyInfo = item.GetType().GetProperty(prop.Name, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
                        if (propertyInfo.PropertyType == typeof(string))
                        {
                            propertyInfo.SetValue(item, Convert.ChangeType(prop.Value.GetString(), propertyInfo.PropertyType), null);
                        }
                        else if (propertyInfo.PropertyType == typeof(bool))
                        {
                            propertyInfo.SetValue(item, Convert.ChangeType(prop.Value.GetBoolean(), propertyInfo.PropertyType), null);
                        }
                        else if (propertyInfo.PropertyType == typeof(int))
                        {
                            int i = 0;
                            try { i = prop.Value.GetInt32(); } catch (Exception) { }
                            propertyInfo.SetValue(item, Convert.ChangeType(i, propertyInfo.PropertyType), null);
                        }
                    }
                    if (item.Id != 0)
                    {
                        db.Phones.Remove(db.Phones.FirstOrDefault(p => p.Id == item.Id));
                        // db.Phones.Remove(await db.Phones.FirstOrDefaultAsync(p => p.Id == item.Id));
                    }
                    db.Phones.Add(item);
                    contact.Phones.Add(item);
                }
                var emailsv       = p.GetProperty("emails");
                var sitesv        = p.GetProperty("sites");
                var messangerUrls = p.GetProperty("messangerUrls");
                var addresses     = p.GetProperty("addresses");

                string contactType = p.GetProperty("contactType").GetString();
                if (!String.IsNullOrEmpty(contactType))
                {
                    contact.Type = contactType;
                }

                string contactSource = p.GetProperty("contactSource").GetString();
                if (!String.IsNullOrEmpty(contactSource))
                {
                    contact.Source = contactSource;
                }

                string description = p.GetProperty("description").GetString();
                if (!String.IsNullOrEmpty(description))
                {
                    contact.Description = description;
                }


                var    Name  = p.GetProperty("name");
                string first = Name.GetProperty("firstName").GetString(); if (!String.IsNullOrEmpty(first))
                {
                    contact.Name.FirstName = first;
                }
                string last = Name.GetProperty("lastName").GetString(); if (!String.IsNullOrEmpty(last))
                {
                    contact.Name.LastName = last;
                }
                string sur = Name.GetProperty("surName").GetString(); if (!String.IsNullOrEmpty(sur))
                {
                    contact.Name.SurName = sur;
                }

                var permissionsv             = p.GetProperty("permissions").EnumerateObject();//.Select(i=>i.Value);
                ContactFieldsPermissions per = new ContactFieldsPermissions();
                foreach (var prop in permissionsv)
                {
                    PropertyInfo propertyInfo = per.GetType().GetProperty(prop.Name, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
                    propertyInfo.SetValue(per, Convert.ChangeType(prop.Value.GetBoolean(), propertyInfo.PropertyType), null);
                }
                contact.Permissions = per;
                db.Contacts.Add(contact);
                db.SaveChanges();

                //Dictionary<string, string> dict = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, string>>(.);
                //string id;
                //dict.TryGetValue("id",out id);

                //var y = data.getType().GetProperty("id").GetValue(data, null);
                //var x = data.getType().GetProperty("name").GetValue(data, null);


                return(new { data = true });
            }
            catch (Exception ex)
            {
                return(new { data = false });
            }
        }