Example #1
0
        public async Task <IActionResult> PutContact(int id, Contact contact)
        {
            if (id != contact.Id)
            {
                return(BadRequest());
            }

            _context.Entry(contact).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ContactExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
        public async Task <IActionResult> Create([Bind("Id,FirstName,LastName,Email,Phone")] Contact contact)
        {
            if (ModelState.IsValid)
            {
                _context.Add(contact);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(contact));
        }
Example #3
0
        public async Task <ActionResult <ContactItem> > PostContactItem([FromForm] ContactItem item, IFormFile profileImage)
        {
            if (profileImage != null && profileImage.Length > 0)
            {
                item.ProfileImage = handleFile(profileImage);
            }

            _context.ContactItems.Add(item);
            await _context.SaveChangesAsync();

            return(CreatedAtAction(nameof(GetContactItem), new { id = item.Id }, item));
        }
Example #4
0
        public async Task <ActionResult <Contact> > DeleteContactAsync(int id)
        {
            try
            {
                using (var _context = new ContactsDBContext())
                {
                    //buscamos el elemento que tenga el id indicado
                    var contact = await _context.Contacts.FindAsync(id);

                    //si no se encuentra el elemento retornamos NotFound
                    if (contact == null)
                    {
                        return(NotFound(
                                   Helper.CustomMessageResponseHelper(false, null, "404", "No se encontró el ID indicado.")
                                   ));
                    }

                    //caso afirmativo eliminamos de la base y guardamos los cambios
                    _context.Contacts.Remove(contact);
                    await _context.SaveChangesAsync();

                    return(Ok(
                               Helper.CustomMessageResponseHelper(true, null, null, "Se elimino el registro indicado.")
                               ));
                }
            }
            catch (Exception e)
            {
                //capturamos la excepcion
                return(NotFound(
                           Helper.CustomMessageResponseHelper(false, null, "Excepción inesperada", "Se ha producido el siguiente error: " + e.ToString())
                           ));
            }
        }
Example #5
0
        public async Task <IActionResult> UpdateContactAsync(int id, TempContact tempContact)
        {
            //creamos un contacto nuevo
            Contact contact = new Contact();

            try
            {
                using (var _context = new ContactsDBContext())
                {
                    //Buscamos el contacto que va a ser modificado
                    contact = await _context.Contacts.Where(i => i.ContactId == id).FirstAsync();

                    //funcion helper que recibe el contacto inicial y actualiza los campos en funcion del tempContact enviado, pisando solo los campos que no sean nulos
                    contact = Validator.UpdateContactWithTempContact(contact, tempContact);

                    //guardamos los cambios
                    await _context.SaveChangesAsync();

                    //informamos que la operacion fue existosa
                    return(Ok(
                               Helper.CustomMessageResponseHelper(true, new List <Contact>()
                    {
                        contact
                    }, "200OK", "Se actualiza el registro correctamente.")
                               ));
                }
            }
            catch (Exception e)
            {
                //capturamos la excepcion
                return(NotFound(
                           Helper.CustomMessageResponseHelper(false, null, "Excepción inesperada", "Se ha producido el siguiente error: " + e.ToString())
                           ));
            }
        }
Example #6
0
        public async Task <IActionResult> PostContactAsync(TempContact tempContact)
        {
            //creamos un nuevo contacto vacio
            Contact contact = new Contact();

            //preparamos una lista de errores en caso de algun valor nulo
            //consideramos todos los campos como obligatorios
            List <string> errorList = new List <string>();

            //consultamos con la funcion helper que verifica si hay algun campo vacio
            errorList = Validator.IsContactValid(tempContact);

            //si recibimos algun error se cancela la operacion y se devuelve un mensaje al usuario con los errores
            if (errorList.Count > 0)
            {
                return(Ok(
                           Helper.CustomMessageResponseHelper(false, null, "Error", "Se produjeron los siguientes errores: " + string.Join <string>(",", errorList))
                           ));
            }
            else
            {
                //si no hay errores se completa el objeto contacto con los datos recibidos
                contact.Company     = tempContact.Company;
                contact.Email       = tempContact.Email;
                contact.FirstName   = tempContact.FirstName;
                contact.LastName    = tempContact.LastName;
                contact.PhoneNumber = tempContact.PhoneNumber;
            }

            try
            {
                using (var _context = new ContactsDBContext())
                {
                    //agregamos y guardamos cambios
                    _context.Contacts.Add(contact);
                    await _context.SaveChangesAsync();
                }

                //retornamos el mensaje de exito con todos los detalles
                return(Ok(
                           Helper.CustomMessageResponseHelper(true, new List <Contact>()
                {
                    contact
                }, "200OK", "El elemento fue correctamente guardado.")
                           ));
            }
            catch (Exception e)
            {
                //capturamos la excepcion
                return(NotFound(
                           Helper.CustomMessageResponseHelper(false, null, "Excepción inesperada", "Se ha producido el siguiente error: " + e.ToString())
                           ));
            }
        }
        public async Task <IActionResult> PutExpertiseLev([FromRoute] int id, [FromBody] ExpertiseLvLEditModel expertiseL)
        {
            //In this api we are using this type of model that complicates the code, because swagger generates the
            // scheme in the documentation more precise with this one
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != expertiseL.ExpertiseLvlid)
            {
                return(BadRequest("No ExpertiseLvLID is added to the input or the added one is wrong"));
            }

            try
            {
                _context.ExpertiseLev.Update(new ExpertiseLvLModel()
                {
                    ExpertiseLvlid = expertiseL.ExpertiseLvlid,
                    ExpertiseLevel = expertiseL.ExpertiseLevel
                });
                await _context.SaveChangesAsync();
            }
            catch (Exception e)
            {
                if (!ExpertiseLevExists(id))
                {
                    return(NotFound("The record with id " + id + " does not exist in the database"));
                }
                else
                {
                    return(BadRequest(e.InnerException.Message));
                }
            }

            return(Ok("Success"));
        }
Example #8
0
        public async Task <IActionResult> PutSkills([FromRoute] int id, [FromBody] EditSkillModel skills)
        {
            //In this api we are using this type of model that complicates the code, because swagger generates the
            // scheme in the documentation more precise with this one
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != skills.SkillId)
            {
                return(BadRequest("No SkillID is added or the added one is wrong"));
            }

            _context.Entry(new SkillModel()
            {
                SkillId   = skills.SkillId,
                SkillName = skills.SkillName
            }).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (Exception e)
            {
                if (!SkillsExists(id))
                {
                    return(NotFound("The record with id " + id + " does not exist in the database"));
                }
                else
                {
                    return(BadRequest(e.InnerException.Message));
                }
            }

            return(Ok("Success"));
        }
Example #9
0
        public async Task <IActionResult> PutContact([FromRoute] int id, [FromBody] ContactEditModel contact)
        {
            //In this api we are using this type of model that complicates the code, because swagger generates the
            // scheme in the documentation more precise with this one
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var identity = HttpContext.User.Identity as ClaimsIdentity;

            if (identity != null)
            {
                IEnumerable <Claim> claims = identity.Claims;
                if (!(claims.FirstOrDefault().Value == id.ToString() || claims.FirstOrDefault().Value == "Administrator"))
                {
                    return(BadRequest("You do not have permission to edit this Contact"));
                }
            }
            if (id != contact.ContactId)
            {
                return(BadRequest("No contactID added or the added one is wrong"));
            }

            var existingSkills = from u in _context.ContactSkillExpertise
                                 where u.ContactId == id
                                 select u;

            foreach (var item in existingSkills)
            {
                _context.ContactSkillExpertise.Remove(item);
            }



            foreach (var item in contact.ContactSkillExpertise)
            {
                if (_context.Skills.FirstOrDefault(x => x.SkillId == item.SkillId) == null)
                {
                    return(BadRequest("One of the skills you are trying to add or modify does not exist as a base skill"));
                }
                ICollection <ContactSkillExpertiseModel> ContactSkillList = new HashSet <ContactSkillExpertiseModel>();
                foreach (var itemm in contact.ContactSkillExpertise)
                {
                    ContactSkillExpertiseModel ContactSkill = new ContactSkillExpertiseModel();
                    ContactSkill.ExpertiseLvlid = itemm.ExpertiseLvlid;
                    ContactSkill.SkillId        = itemm.SkillId;
                    ContactSkillList.Add(ContactSkill);
                }
                _context.Contact.Update(new ContactModel()
                {
                    ContactId             = contact.ContactId,
                    Firstname             = contact.Firstname,
                    Lastname              = contact.Lastname,
                    Fullname              = contact.Fullname,
                    Email                 = contact.Email,
                    Address               = contact.Address,
                    MobileNum             = contact.MobileNum,
                    ContactSkillExpertise = ContactSkillList
                });
            }



            try
            {
                await _context.SaveChangesAsync();
            }
            catch (Exception e)
            {
                if (!ContactExists(id))
                {
                    return(NotFound("The record with id " + id + " does not exist in the database"));
                }
                else
                {
                    return(NotFound(e.InnerException.Message));
                }
            }

            return(Ok("Success"));
        }