public async Task <HttpResponseMessage> CreateOrUpdate(int customerId, List <ServiceDay> serviceDays)
        {
            var validationMessage = ValidateServiceDays(customerId, serviceDays);

            if (validationMessage != "")
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, validationMessage));
            }

            try
            {
                var newServiceDays      = serviceDays.Where(x => x.Id == 0);
                var updatedServiceDays  = serviceDays.Where(x => x.Id != 0);
                var updatedIds          = updatedServiceDays.Select(x => x.Id);
                var serviceDaysToDelete = db.ServiceDays.Where(x => x.CustomerId == customerId && !updatedIds.Contains(x.Id));

                if (serviceDaysToDelete.Count() > 0)
                {
                    db.ServiceDays.RemoveRange(serviceDaysToDelete);
                }

                foreach (var newDay in newServiceDays)
                {
                    db.ServiceDays.Add(newDay);
                }

                foreach (var update in updatedServiceDays)
                {
                    db.Entry(update).State = EntityState.Modified;
                    foreach (var sd in update.ServiceDetails)
                    {
                        if (sd.Id == 0)
                        {
                            db.ServiceDetails.Add(sd);
                        }
                        else
                        {
                            db.Entry(sd).State = EntityState.Modified;
                        }
                    }
                }


                await db.SaveChangesAsync();

                //{
                //    var entry = db.Entry(update);
                //    if (entry.State == EntityState.Detached || entry.State == EntityState.Modified)
                //    {
                //        entry.State = EntityState.Modified;
                //        db.Set<ServiceDay>().Attach(update);
                //    }
                //}

                //await db.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message));
            }

            var resp = Request.CreateResponse(HttpStatusCode.NoContent); //, new GenericCreateResponse());

            resp.Headers.Location = new Uri($"{Request.RequestUri.Scheme}://{Request.RequestUri.Authority}/ServiceDetails/Edit?id={customerId}");

            return(resp);
        }
Example #2
0
        public async Task <HttpResponseMessage> Update(int id, [FromBody] Customer customer)
        {
            bool   isNew      = customer.Id == 0;
            string validation = null;
            var    props      = customer.GetType().GetProperties(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance).ToList();

            if (!ModelState.IsValid)
            {
                var errors = new List <string>();
                foreach (var value in ModelState.Values)
                {
                    foreach (var error in value.Errors)
                    {
                        errors.Add(error.ErrorMessage);
                    }
                }
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, string.Join(" | ", errors)));
            }
            else
            {
                validation = customer.Validate();
            }

            if (validation != null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, validation));
            }

            var resp = Request.CreateResponse(isNew ? HttpStatusCode.Created : HttpStatusCode.NoContent, new GenericCreateResponse());

            try
            {
                DeleteUnfinishedChildren(customer);
                if (isNew)
                {
                    db.Customers.Add(customer);
                }
                else
                {
                    StampCustIdOnChildObjects(customer);
                    db.Entry(customer).State = EntityState.Modified;
                    customer.SaveChildObjects(db);
                }

                await db.SaveChangesAsync();

                if (isNew)
                {
                    resp.Headers.Location = new Uri($"{Request.RequestUri.Scheme}://{Request.RequestUri.Authority}/Customers/edit?id={customer.Id}");
                }
            }

            catch (DbEntityValidationException ve)
            {
                var errorList = new List <string>();
                foreach (var e in ve.EntityValidationErrors)
                {
                    errorList.Add($"props:{string.Join(",", e.ValidationErrors.Select(x => x.PropertyName).ToArray())} | errors:{string.Join(",", e.ValidationErrors.Select(x => x.ErrorMessage).ToArray())} ");
                }
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, string.Join("<br />", errorList)));
            }

            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message));
            }

            return(resp);
        }
        public async Task <HttpResponseMessage> Update(int id, [FromBody] Employee emp)
        {
            bool isNew = emp.Id == 0;

            string validation = null;
            var    props      = emp.GetType().GetProperties(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance).ToList();

            if (!ModelState.IsValid)
            {
                var errors = new List <string>();
                foreach (var value in ModelState.Values)
                {
                    foreach (var error in value.Errors)
                    {
                        errors.Add(error.ErrorMessage);
                    }
                }
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, string.Join(" | ", errors)));
            }

            var appUser = await ApplicationUserManager.GetApplicationUserAsync(id);

            if (emp.User != null)
            {
                if (appUser == null)
                {
                    var manager = ApplicationUserManager.GetCurrent();
                    appUser = new ApplicationUser {
                        UserName = emp.User.UserName, Email = emp.User.Email, EmployeeId = emp.Id
                    };

                    var result = await manager.CreateAsync(appUser, "qwerASDF1234!@#$asdf");

                    //var result = await manager.CreateAsync(appUser, "qwerASDF1234!@#$asdf");
                    if (result.Succeeded)
                    {
                        //appUser = await ApplicationUserManager.GetApplicationUserAsync(id);
                        await appUser.SendEmailConfirmation(manager);
                    }
                    else
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, $"Error creating Application User {emp.User.UserName}.  Error = {string.Join("|", result.Errors)}"));
                    }
                }
            }


            if (validation != null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, validation));
            }

            try
            {
                if (isNew)
                {
                    db.Employees.Add(emp);
                }
                else
                {
                    db.Entry(emp).State = EntityState.Modified;
                }

                await db.SaveChangesAsync();
            }

            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message));
            }

            var resp = Request.CreateResponse(isNew ? HttpStatusCode.Created : HttpStatusCode.NoContent, new GenericCreateResponse());

            return(resp);
        }