Example #1
0
        public ActionResult Edit(ImageEditorViewModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    DefaultContext db   = new DefaultContext();
                    var            Item = db.Galleries.Include("Files").Where(x => x.Id == model.Id).FirstOrDefault();
                    if (model.FileImage != null)
                    {
                        var path = Server.MapPath("~/Uploads/");
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }
                        var File = Item.Files.Where(x => x.IsDefault == true).FirstOrDefault();
                        model.FileImage.SaveAs(path + Path.GetFileName(model.FileImage.FileName));
                        File.FilePath        = "/Uploads/" + Path.GetFileName(model.FileImage.FileName);
                        db.Entry(File).State = System.Data.Entity.EntityState.Modified;
                    }
                    Item.Title           = model.Caption;
                    db.Entry(Item).State = System.Data.Entity.EntityState.Modified;

                    db.SaveChanges();

                    return(RedirectToAction("Index"));
                }

                return(View(model));
            }
            catch (Exception ex)
            {
                return(RedirectToAction("Index"));
            }
        }
        public ActionResult EditSeller(UpdateSellerViewModel model)
        {
            if (ModelState.IsValid)
            {
                var profile = dbContext.Profiles
                              .Where(p => p.Id == currentUserProvider.UserId)
                              .FirstOrDefault();

                if (profile == null)
                {
                    return(NotFound());
                }

                profile.Extend(model);
                if (profile.Contact == null)
                {
                    profile.Contact = new PrevilegedContact()
                    {
                        FirstName = model.ContactFirstName,
                        LastName  = model.ContactLastName,
                        Phone     = model.ContactPhone
                    };
                }

                dbContext.Entry <Vacation24.Models.Profile>(profile).State = EntityState.Modified;
                dbContext.SaveChanges();

                return(RedirectToAction("Edit", "Profile"));
            }

            return(View("Edit", model));
        }
Example #3
0
        public ActionResult Update(Service service)
        {
            int serviceId;

            try
            {
                if (service.Id == 0)
                {
                    dbContext.Services.Add(service);
                }
                else
                {
                    dbContext.Entry <Service>(service).State = EntityState.Modified;
                }
                dbContext.SaveChanges();

                serviceId = service.Id;
            }
            catch (Exception e)
            {
                return(Json(new ResultViewModel()
                {
                    Message = "Wystąpił błąd: " + e.Message,
                    Status = (int)ResultStatus.Error
                }));
            }

            return(Json(new ResultViewModel()
            {
                Status = (int)ResultStatus.Success,
                Message = serviceId.ToString()
            }));
        }
Example #4
0
        public IActionResult Update(int id, [FromBody] SupplierViewModel formData)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(new ApiBadRequestResponse(ModelState)));
                }

                var objSupp = dg.Supplier.Where(x => x.SupplierId == id).FirstOrDefault();

                if (objSupp == null)
                {
                    return(NotFound(new ApiResponse(404, "No record found")));
                }

                objSupp.FirstName = formData.FirstName;
                objSupp.LastName  = formData.LastName;
                objSupp.Email     = formData.Email;
                objSupp.Mobile    = formData.Mobile;
                objSupp.Address   = formData.Address;
                objSupp.IsActive  = formData.IsActive;

                dg.Entry(objSupp).State = EntityState.Modified;
                dg.SaveChanges();

                return(Ok(new ApiResponse(200, "Record has been updated")));
            }
            catch (Exception sf)
            {
                throw new ApiExceptionResponse(sf);
            }
        }
Example #5
0
        /// <summary>
        /// Update a register async
        /// </summary>
        /// <param name="entity"></param>
        /// <returns>register updated</returns>
        public virtual async Task <TEntity> UpdateAsync(TEntity entity)
        {
            _dbSet.Update(entity);
            _context.Entry(entity).Property(a => a.Enable).IsModified       = false;
            _context.Entry(entity).Property(a => a.Removed).IsModified      = false;
            _context.Entry(entity).Property(a => a.CreationDate).IsModified = false;
            _context.Entry(entity).Property(a => a.CreatedById).IsModified  = false;
            await SaveChangesAsync();

            return(entity);
        }
Example #6
0
        public void ActivateObjects(string userId)
        {
            var places = context.Places.Where(p => p.OwnerId == userId).ToList();

            foreach (var place in places)
            {
                place.IsPaid = true;
                context.Entry(place).State = EntityState.Modified;
            }
            context.SaveChanges();
        }
Example #7
0
        public T GetSingle <T>(object id) where T : class
        {
            var entity = Set <T>().Find(id);

            if (entity != null)
            {
                Context.Entry(entity).State = EntityState.Detached;
            }

            return(entity);
        }
        public async Task <IActionResult> PutDetailCommande(int id, DetailCommande detailCommande)
        {
            if (id != detailCommande.Id)
            {
                return(BadRequest());
            }

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

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

            return(NoContent());
        }
        public async Task UploadTemplate(DefaultContext context, string name, User user, Stream stream, long length, Action <double> callback = null)
        {
            await context.Database.BeginTransactionAsync();

            var hypervisor = await context.Hypervisors.FirstOrDefaultAsync();

            context.Entry(user).State = EntityState.Unchanged;
            var vmTemplate = new VmTemplate
            {
                Name         = name,
                Owner        = user,
                IsCoreRouter = false,
            };

            context.Add(vmTemplate);
            await context.SaveChangesAsync();

            var templateId = await UploadVmTemplate(
                name, stream, length, hypervisor, vmTemplate, callback);

            var primaryHypervisorNode = await ProxmoxManager.GetPrimaryHypervisorNode(hypervisor);

            vmTemplate.HypervisorVmTemplates = new List <HypervisorVmTemplate>
            {
                new HypervisorVmTemplate
                {
                    HypervisorNode = primaryHypervisorNode,
                    TemplateVmId   = templateId
                }
            };
            await context.SaveChangesAsync();

            context.Database.CommitTransaction();
        }
Example #10
0
        public async Task <IActionResult> PutCustomer(int id, Customer customer)
        {
            if (id != customer.Id)
            {
                return(BadRequest());
            }

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

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

            return(NoContent());
        }
Example #11
0
        public async Task <IActionResult> PutBook(int id, Book book)
        {
            if (id != book.Id)
            {
                return(BadRequest());
            }

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

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

            return(NoContent());
        }
Example #12
0
        void Update(DefaultContext _context, BaseEntity existingEntity, BaseEntity model)
        {
            var entry = _context.Entry(existingEntity);

            entry.CurrentValues.SetValues(model);
            entry.State = EntityState.Modified;
        }
Example #13
0
        public static ResponseViewModel ChangePassword(ChangePasswordViewModel model)
        {
            var result = new ResponseViewModel();

            try
            {
                var user = db.Users.Find(model.Id);
                if (user == null)
                {
                    result.Message = "User not found";
                }
                else
                {
                    if (user.PasswordHashed != model.HashedOldPassword)
                    {
                        result.Message = "Your old password did not match";
                    }
                    else
                    {
                        user.PasswordHashed  = model.HashedNewPassword;
                        db.Entry(user).State = System.Data.Entity.EntityState.Modified;
                        db.SaveChanges();

                        result.Status  = true;
                        result.Message = "Password changed successfully";
                    }
                }
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return(result);
        }
Example #14
0
 public void Update(string id, Country entity)
 {
     try
     {
         Country obj = FindById(id);
         if (obj != null)
         {
             if (entity.CountryCode == obj.CountryCode)
             {
                 entity.ModificationDate      = DateTimeOffset.Now;
                 _context.Entry(entity).State = EntityState.Modified;
                 _context.SaveChanges();
             }
             else
             {
                 throw new NonEqualObjectException();
             }
         }
         else
         {
             throw new NonObjectFoundException();
         }
     }
     catch (Exception ex)
     {
         AppLogger.Error(ex.Message, ex);
         throw;
     }
 }
Example #15
0
        public IActionResult Update(int id, [FromBody] PurchaseViewModel formdata)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(new ApiBadRequestResponse(ModelState)));
                }

                var objpurchase = ctx.Purchase.Where(x => x.PurchaseId == id).FirstOrDefault();

                if (objpurchase == null)
                {
                    return(NotFound(new ApiResponse(404, "No record found")));
                }

                objpurchase.Name        = formdata.Name;
                objpurchase.Description = formdata.Description;
                objpurchase.CostPrice   = formdata.CostPrice;
                objpurchase.TaxId       = formdata.TaxId;
                objpurchase.Price       = formdata.Price;
                objpurchase.IsCommited  = formdata.IsCommited;

                ctx.Entry(objpurchase).State = EntityState.Modified;
                ctx.SaveChanges();

                return(Ok(new ApiResponse(200, "Record has updated")));
            }
            catch (Exception fg)
            {
                throw new ApiExceptionResponse(fg);
            }
        }
        public static ResponseViewModel AssignStudent(Guid StudentId, Guid ClassId)
        {
            var result = new ResponseViewModel();

            try
            {
                var student = db.Students.Find(StudentId);
                if (student != null)
                {
                    student.ClassId         = ClassId;
                    db.Entry(student).State = System.Data.Entity.EntityState.Modified;
                    db.SaveChanges();
                    result.Status  = true;
                    result.Message = "Assigned";
                }
                else
                {
                    result.Message = "Student not found";
                }
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return(result);
        }
Example #17
0
        public T Update(T oldEntity, T newEntity)
        {
            var entry = _dbContext.Entry(oldEntity);

            entry.CurrentValues.SetValues(newEntity);
            return(entry.Entity);
        }
Example #18
0
        // 參考: https://blog.johnwu.cc/article/ironman-day24-asp-net-core-entity-framework-core.html
        public void Update(T entity)
        {
            // 先用Id取資料再做更新
            var dbEntity = this.FindById(entity.Id);

            if (dbEntity != null)
            {
                context.Entry(dbEntity).CurrentValues.SetValues(entity);
                UpdateChildren(dbEntity, entity);

                context.SaveChanges();
            }
            else
            {
                throw new KeyNotFoundException("entity: " + entity + " Key: " + entity.Id + " Not Found!");
            }
        }
Example #19
0
        public async Task <ActionResult> Edit([Bind(Include = "id,VPBISerialNumber,VPISerialNumber,VPBIMonitoringPointNumber,VPBIAffiliatedOrganization,VPBIBelongToTheRegion,VPBIPlatform,VPBILongitude,VPBILatitude,VersionNo,TransactionID,CreateBy,CreateOn,UpdateBy,UpdateOn,DataLevel,Latitude,Longitude,IsDeleted,Polyline,Polygon")] VideoPointInformation videoPointBitInformation)
        {
            if (ModelState.IsValid)
            {
                db.Entry(videoPointBitInformation).State = System.Data.Entity.EntityState.Modified;
                await db.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
            return(View(videoPointBitInformation));
        }
Example #20
0
        public ActionResult Save(SetVideo video)
        {
            if (dbContext.Places.Any(p => p.Id == video.postId))
            {
                var videoEntity = dbContext.Videos.FirstOrDefault(v => v.PlaceId == video.postId);
                var embededUrl  = string.Empty;

                try{
                    embededUrl = prepareEmbedUrl(video.url);
                }catch (Exception e) {
                    return(Json(new ResultViewModel()
                    {
                        Status = (int)ResultStatus.Success,
                        Message = e.Message
                    }));
                }

                //Add new entity or replace url in existing
                if (videoEntity == null)
                {
                    dbContext.Videos.Add(new Video()
                    {
                        PlaceId     = video.postId,
                        EmbedUrl    = embededUrl,
                        OriginalUrl = video.url
                    });
                }
                else
                {
                    videoEntity.EmbedUrl    = embededUrl;
                    videoEntity.OriginalUrl = video.url;
                    dbContext.Entry <Video>(videoEntity).State = EntityState.Modified;
                }

                dbContext.SaveChanges();

                return(Json(new ResultViewModel()
                {
                    Status = (int)ResultStatus.Success,
                    Message = embededUrl
                }));
            }

            return(Json(new ResultViewModel()
            {
                Status = (int)ResultStatus.Error,
                Message = "Błąd krytyczny: Nie znaleziono obiektu."
            }));
        }
Example #21
0
        public IActionResult updateUsers(Usuario user)
        {
            try
            {
                db.Entry(user).State = EntityState.Modified;
                db.SaveChanges();
            }
            catch
            {
                // I'll think about a more meaningful error later
                return(StatusCode(500));
            }

            return(Ok());
        }
Example #22
0
 public void AddSaveNomenclature(Nomenclature nomenclature)
 {
     if (nomenclature.Id == 0)
     {
         db.Goods.Add(nomenclature);
     }
     else
     {
         db.Entry(nomenclature).State = System.Data.Entity.EntityState.Modified;
     }
     try
     {
         db.SaveChanges();
     }
     catch { }
 }
Example #23
0
        public ActionResult Edit(NewsViewModel model)
        {
            var dbEntry = dbContext.News.Find(model.Id);

            if (dbEntry == null)
            {
                throw new Exception("Unknown entry requested.");
            }

            dbEntry.Extend(model);

            dbContext.Entry <News>(dbEntry).State = EntityState.Modified;
            dbContext.SaveChanges();

            return(View(dbEntry));
        }
Example #24
0
        /// <summary>
        /// Supprime un ennemi
        /// </summary>
        /// <param name="id">Identifiant de l'ennemi à supprimer</param>
        public async Task <bool> DeleteById(Guid id)
        {
            bool result = false;

            var heroToDelete = await _context.Enemies
                               .AsNoTracking()
                               .FirstOrDefaultAsync(m => m.Id == id);

            if (heroToDelete != null)
            {
                _context.Entry(heroToDelete).State = EntityState.Deleted;
                await _context.SaveChangesAsync();

                result = true;
            }

            return(result);
        }
Example #25
0
        /// <summary>
        /// Delete et sauvegarde un évènement
        /// </summary>
        /// <param name="id">Identifiant de l'évènement à supprimer</param>
        public async Task <bool> DeleteById(int id)
        {
            bool result = false;

            var eventToDelete = await _context.StoryEvents
                                .AsNoTracking()
                                .FirstOrDefaultAsync(s => s.Id == id);

            if (eventToDelete != null)
            {
                _context.Entry(eventToDelete).State = EntityState.Deleted;
                await _context.SaveChangesAsync();

                result = true;
            }

            return(result);
        }
Example #26
0
        /// <summary>
        /// Supprime un objet
        /// </summary>
        /// <param name="id">Identifiant de l'objet à supprimer</param>
        public async Task <bool> DeleteById(int id)
        {
            bool result = false;

            var itemToDelete = await _context.ItemsOnGame
                               .AsNoTracking()
                               .FirstOrDefaultAsync(m => m.Id == id);

            if (itemToDelete != null)
            {
                _context.Entry(itemToDelete).State = EntityState.Deleted;
                await _context.SaveChangesAsync();

                result = true;
            }

            return(result);
        }
Example #27
0
        public ActionResult Delete(int Id)
        {
            DefaultContext db   = new DefaultContext();
            var            Item = db.Galleries.Include("Files").Where(x => x.Id == Id).FirstOrDefault();

            if (Item != null)
            {
                if (Item.Files != null)
                {
                    foreach (var File in Item.Files)
                    {
                        System.IO.File.Delete(Server.MapPath("/") + "/" + File.FilePath);
                    }
                    db.WebFiles.RemoveRange(Item.Files);
                }
                db.Entry(Item).State = System.Data.Entity.EntityState.Deleted;
                db.SaveChanges();
            }

            return(RedirectToAction("Index"));
        }
Example #28
0
        public async Task <T> UpdateAsync(T obj)
        {
            try
            {
                var current = await DbSet.SingleOrDefaultAsync(x => x.Id == obj.Id);

                if (current == null)
                {
                    return(null);
                }

                obj.CreatedIn = current.CreatedIn;
                obj.UpdatedIn = current.UpdatedIn;

                Db.Entry(current).CurrentValues.SetValues(obj);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(obj);
        }
Example #29
0
        public async Task <IHttpActionResult> PutHardDisk(int?id, HardDisk HardDisk)
        {
            if (!id.HasValue)
            {
                return(BadRequest("Не указан Id"));
            }
            if (HardDisk == null)
            {
                return(BadRequest("Отсутствует тело элемента"));
            }
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != HardDisk.Id)
            {
                return(BadRequest());
            }

            _db.Entry(HardDisk).State = EntityState.Modified;

            try
            {
                await _db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!HardDiskExists(id.Value))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Example #30
0
        public void AddSaveOrder(Order order)
        {
            if (order.Id == 0)
            {
                db.Orders.Add(order);
            }
            else
            {
                db.Entry(order).State = System.Data.Entity.EntityState.Modified;
            }

            try
            {
                db.SaveChanges();
                AddSaveSale(order);
                if (order.IsClose)
                {
                    GenerateXml(order);
                }
                db.SaveChanges();
            }
            catch (Exception ex) { }
        }