예제 #1
0
        // PUT api/Category/5
        public HttpResponseMessage PutCategory(int id, Category category)
        {
            if (!ModelState.IsValid)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }

            if (id != category.Id)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest));
            }

            db.Entry(category).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, ex));
            }

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
        public static void DeleteUser(string userId)
        {
            using (var db = new EntitiesContext())
            {
                var user   = db.AspNetUsers.SingleOrDefault(x => x.Id == userId);
                var places = db.Places.Where(x => x.IdPartner == userId).ToList();
                foreach (var place in places)
                {
                    PlacesManager.DeletePlace(place.IdPlace);
                }

                var reviews = db.PlacesReviews.Where(x => x.IdUser == userId).ToList();
                foreach (var review in reviews)
                {
                    db.PlacesReviews.Remove(review);
                }

                var searches = db.UserSearchHistories.Where(x => x.IdUser == userId).ToList();
                foreach (var search in searches)
                {
                    db.UserSearchHistories.Remove(search);
                }

                var userprofile = db.UserProfiles.Where(x => x.IdUser == userId).SingleOrDefault();
                if (userprofile != null)
                {
                    db.UserProfiles.Remove(userprofile);
                    db.SaveChanges();
                }

                db.AspNetUsers.Remove(user);
                db.SaveChanges();
            }
        }
        public ActionResult Create([Bind(Include = "EmpId,Name,Designation,DepartmentId")] Employee employee)
        {
            if (ModelState.IsValid)
            {
                db.Employees.Add(employee);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.DepartmentId = new SelectList(db.Departments, "DepartmentId", "Description", employee.DepartmentId);
            return(View(employee));
        }
예제 #4
0
        public async Task <bool> SendMail(Message email, string token, EmailType type)
        {
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");
                string json = JsonConvert.SerializeObject(new { message = email });

                var response = await client.PostAsync(
                    $"https://graph.microsoft.com/v1.0/me/sendMail",
                    new StringContent(json, Encoding.UTF8, "application/json")
                    );

                var result = response.StatusCode == HttpStatusCode.Accepted;

                // Zaznamenám email, ať už se poslání pomohlo či ne.
                var log = new EmailLog()
                {
                    To        = email.ToRecipients[0].EmailAddress.Address,
                    From      = this.user.Email ?? this.user.UserName,
                    Type      = type,
                    Subject   = email.Subject,
                    Content   = email.Body.Content,
                    RentingId = email.RentingId,
                    Sent      = result,
                    Error     = result ? null : response.ReasonPhrase,
                };

                context.EmailLog.Add(log);
                context.SaveChanges();

                return(result);
            }
        }
        public void EditPage(PageContentModel pageContentModel)
        {
            if (pageContentModel == null)
            {
                throw new ValidationException("Страница не найдена", "");
            }

            var url = FriendlyUrls.GetFriendlyUrl(!string.IsNullOrEmpty(pageContentModel.Url) ? pageContentModel.Url : pageContentModel.Header);

            if (!HasUrl(url, pageContentModel.Id))
            {
                throw new ValidationException("Такой url уже существует.", "");
            }

            var pageContentEssence = new PageContentEssence {
                Id            = pageContentModel.Id,
                Header        = pageContentModel.Header,
                Url           = url,
                IsPublished   = pageContentModel.IsPublished,
                SeoID         = pageContentModel.SeoID,
                HtmlContentID = pageContentModel.HtmlContentID
            };

            using (EntitiesContext context = new EntitiesContext()) {
                context.Entry(pageContentEssence).State = EntityState.Modified;

                context.SaveChanges();
            }
        }
        public void Delete(int id)
        {
            MenuItemManager menuItemManager = new MenuItemManager();

            try {
                using (EntitiesContext context = new EntitiesContext()) {
                    var item     = context.PageContentEssences.Find(id);
                    var allMenus = menuItemManager.GetAll();
                    foreach (var menu in allMenus)
                    {
                        if (menu.PageID == item.Id)
                        {
                            throw new ValidationException("Страницу нельзя удалить", "");
                        }
                    }

                    if (item != null)
                    {
                        context.PageContentEssences.Remove(item);

                        context.SaveChanges();
                    }
                }
            }
            catch (ValidationException ex) {
                throw new ValidationException(ex.Message, ex.Property);
            }
        }
예제 #7
0
        public void EditMenu(MenuModel menuModel)
        {
            if (menuModel == null)
            {
                throw new ValidationException("Меню отсутствует", "");
            }

            if (HasUniqueCode(menuModel.Code, menuModel.Id))
            {
                var menu = new MenuEssence {
                    Id        = menuModel.Id,
                    Code      = menuModel.Code,
                    TitleMenu = menuModel.TitleMenu
                };

                using (EntitiesContext context = new EntitiesContext()) {
                    context.Entry(menu).State = EntityState.Modified;

                    context.SaveChanges();
                }
            }
            else
            {
                throw new ValidationException("Меню с таким кодом уже существует.", "");
            }
        }
예제 #8
0
        public void SaveMenu(MenuModel menuModel)
        {
            if (menuModel == null)
            {
                throw new ValidationException("Меню отсутствует", "");
            }

            if (HasUniqueCode(menuModel.Code, menuModel.Id))
            {
                var menu = new MenuEssence {
                    Code      = menuModel.Code,
                    TitleMenu = menuModel.TitleMenu
                };

                using (EntitiesContext context = new EntitiesContext()) {
                    context.MenuEssences.Add(menu);

                    context.SaveChanges();
                }
            }
            else
            {
                throw new ValidationException("Меню с таким кодом уже существует.", "");
            }
        }
        public void CreatePage(PageContentModel pageContentModel)
        {
            if (pageContentModel == null)
            {
                throw new ValidationException("Пустая страница", "");
            }

            var url = FriendlyUrls.GetFriendlyUrl(!string.IsNullOrEmpty(pageContentModel.Url) ? pageContentModel.Url : pageContentModel.Header);

            if (!HasUrl(url, pageContentModel.Id))
            {
                throw new ValidationException("Такой url уже существует.", "");
            }

            var pageContentEssence = new PageContentEssence {
                Header      = pageContentModel.Header,
                Url         = url,
                IsPublished = pageContentModel.IsPublished,
                HtmlContent = new HtmlContentEssence {
                    HtmlContent = pageContentModel.HtmlContentModel.HtmlContent,
                    UniqueCode  = pageContentModel.HtmlContentModel.UniqueCode
                },
                PageSeo = new PageSeoEssence {
                    Title        = pageContentModel.PageSeoModel.Title,
                    KeyWords     = pageContentModel.PageSeoModel.KeyWords,
                    Descriptions = pageContentModel.PageSeoModel.Descriptions
                }
            };

            using (EntitiesContext context = new EntitiesContext()) {
                context.PageContentEssences.Add(pageContentEssence);

                context.SaveChanges();
            }
        }
예제 #10
0
        public async Task <JsonResult> CreateCharacter(ModelCreateCharacterView model)
        {
            if (ModelState.IsValid)
            {
                string imagePath = Library.UploadFile(model.Image, _hostingEnvironment);

                Character character = new Character();
                character.CategoryId  = model.CategoryId;
                character.Content     = model.Content;
                character.Description = model.Description;
                character.Name        = model.Name;
                character.ImagePath   = imagePath;
                var user = await _userManager.GetUserAsync(User);


                if (user != null)
                {
                    character.UserId = user.Id;
                    _dbContext.Characters.Add(character);
                    _dbContext.SaveChanges();
                }
                else
                {
                    return(Json(new { status = "fail", message = "Create character fail" }));
                }

                return(Json(new { status = "success", message = "Create character success" }));
            }
            else
            {
                var listError = ModelState.Select(x => x.Value).ToList();
                return(Json(new { status = "fail", message = "Create character fail", listError = listError }));
            }
        }
예제 #11
0
        private void ReadDataFile()
        {
            string path           = PathHelper.AbsolutePath(DataFile.Name);
            int    lastLine       = DataFile.LastLine;
            var    currentStatus  = StatusHelper.Processing;
            var    hasBeenStopped = false;

            try {
                using (EntitiesContext _context = (new EntityObjectContext()).GetContext()) {
                    DataFile     df   = _context.Files.First(x => x.Id == DataFile.Id);
                    StreamReader file = new StreamReader(path);
                    string       line;
                    int          counter = 0;
                    while ((line = file.ReadLine()) != null)
                    {
                        if (_shouldStop)
                        {
                            hasBeenStopped = true;
                            break;
                        }
                        if (counter >= lastLine)
                        {
                            InsertLine(line, df, _context);
                            lastLine++;
                            UpdateLastLineAndStatus(df, _context, lastLine);
                            _context.SaveChanges();
                        }
                        counter++;
                    }

                    /*foreach (string line in File.ReadAllLines(path).Skip(lastLine)) {
                     *  InsertLine(line, df, _context);
                     *  lastLine++;
                     *  UpdateLastLineAndStatus(df, _context, lastLine);
                     *  _context.SaveChanges();
                     * }*/
                }
                if (!hasBeenStopped)
                {
                    currentStatus = StatusHelper.Finished;
                }
                else
                {
                    currentStatus = StatusHelper.Waiting;
                }
            } catch (OutOfMemoryException e) {
                currentStatus = StatusHelper.OutOfMemory;
                Console.WriteLine(e);
            } catch (Exception e) {
                currentStatus = StatusHelper.Waiting;
                Console.WriteLine(e);
            }
            using (EntitiesContext _context = (new EntityObjectContext()).GetContext()) {
                DataFile df = _context.Files.First(x => x.Id == DataFile.Id);
                UpdateLastLineAndStatus(df, _context, lastLine, currentStatus);
                _context.SaveChanges();
            }
            _shouldStop = true;
        }
예제 #12
0
 public Task DeleteInputOutput(InputOutputEntity oOutput)
 {
     using (var db = new EntitiesContext())
     {
         db.InOuts.Remove(oOutput);
         return(Task.FromResult(db.SaveChanges()));
     }
 }
예제 #13
0
 public Task DeleteWhereHouse(WhereHouseEntity owhereHouse)
 {
     using (var db = new EntitiesContext())
     {
         db.WhereHouses.Remove(owhereHouse);
         return(Task.FromResult(db.SaveChanges()));
     }
 }
예제 #14
0
 public Task UpdateWherehouse(WhereHouseEntity oWarehouse)
 {
     using (var db = new EntitiesContext())
     {
         db.WhereHouses.Update(oWarehouse);
         return(Task.FromResult(db.SaveChanges()));
     }
 }
예제 #15
0
 public static void AddPlace(Place place)
 {
     using (var db = new EntitiesContext())
     {
         db.Places.Add(place);
         db.SaveChanges();
     }
 }
예제 #16
0
 public static void AddPlacePhoto(PlacesPhoto photo)
 {
     using (var db = new EntitiesContext())
     {
         db.PlacesPhotos.Add(photo);
         db.SaveChanges();
     }
 }
예제 #17
0
 public Task UpdateProduct(ProductEntity oProduct)
 {
     using (var db = new EntitiesContext())
     {
         db.Products.Update(oProduct);
         return(Task.FromResult(db.SaveChanges()));
     }
 }
예제 #18
0
 public Task UpdateCategory(CategoryEntity oCategory)
 {
     using (var db = new EntitiesContext())
     {
         db.Categories.Update(oCategory);
         return(Task.FromResult(db.SaveChanges()));
     }
 }
예제 #19
0
 public static void DeleteUserProfile(string userId)
 {
     using (var db = new EntitiesContext())
     {
         var profile = db.UserProfiles.Where(x => x.IdUser == userId).SingleOrDefault();
         db.UserProfiles.Remove(profile);
         db.SaveChanges();
     }
 }
예제 #20
0
 public Task CreateProduct(ProductEntity oProduct)
 {
     using (var db = new EntitiesContext())
     {
         oProduct.CategoryEntity = oProduct.CategoryEntity == null ? null : db.Categories.Find(oProduct.CategoryEntity.Id);
         db.Products.Add(oProduct);
         return(Task.FromResult(db.SaveChanges()));
     }
 }
예제 #21
0
 private void ChangeState(StatusHelper status)
 {
     using (EntitiesContext _context = (new EntityObjectContext()).GetContext()) {
         DataFile df = _context.Files.First(x => x.Id == DataFile.Id);
         df.Status = (int)status;
         _context.Entry(df).State = EntityState.Modified;
         _context.SaveChanges();
     }
 }
예제 #22
0
        public int Add(T entity)
        {
            DbSet.Add(entity);
            EntitiesContext.SaveChanges();

            var generatedId = entity.Id;

            return(generatedId);
        }
예제 #23
0
        public TOut RunAction(TIn dataIn)             //#C
        {
            var result = _actionClass.Action(dataIn); //#D

            if (!HasErrors)                           //#E
            {
                _context.SaveChanges();               //#E
            }
            return(result);                           //#F
        }
예제 #24
0
        public Task DeleteStorage(StorageEntity oStorage)
        {
            oStorage.LasUpdate = DateTime.Now;

            using (var db = new EntitiesContext())
            {
                db.Storages.Remove(oStorage);
                return(Task.FromResult(db.SaveChanges()));
            }
        }
    public MethodUpdateString(EntityClass1 entityClass1Object)
    {
        entityClass1Object.CustomString1 = "UPDATED";
        dbContext.EntityClass1.Add(entityClass1Object);
        var entity2 = new EntityClass2();

        entity2.EntityClass1Id = entityClass1Object.Id;
        dbContext.EntityClass2.Add(entity2);
        dbContext.SaveChanges();
    }
예제 #26
0
        private static int AddCutomers(EntitiesContext context, string dataDirectory)
        {
            var numCustomers = context.Customers.Count();

            if (numCustomers == 0)
            {
                //the database is emply so we fill it from a json file
                var customers = CustomerJsonLoader.LoadCustomers(Path.Combine(dataDirectory, SeedFileSubDirectory),
                                                                 SeedCustomerDataSearchName).ToList();
                context.Customers.AddRange(customers);
                context.SaveChanges();
                //We add this separately so that it has the highest Id. That will make it appear at the top of the default list
                context.Customers.Add(SpecialCustomer.CreateSpetialCustomer());
                context.SaveChanges();
                numCustomers = customers.Count + 1;
            }

            return(numCustomers);
        }
예제 #27
0
 public Task CreateStorage(StorageEntity oStorage)
 {
     using (var db = new EntitiesContext())
     {
         oStorage.Product    = oStorage.Product == null ? null : db.Products.Find(oStorage.Product.Id);
         oStorage.WhereHouse = oStorage.WhereHouse == null ? null : db.WhereHouses.Find(oStorage.WhereHouse.Id);
         db.Storages.Add(oStorage);
         return(Task.FromResult(db.SaveChanges()));
     }
 }
예제 #28
0
        public void GrabMeetupData()
        {
            var provider = EventsFactory.Instance.EventsProviders["meetup"];
            var events   = provider.Source.GetTopEvents(DateTime.Now, DateTime.Now.AddDays(15), Locations.Vancouver);

            using (var dbContext = new EntitiesContext())
            {
                events.ForEach(e => dbContext.Events.Add(e));
                dbContext.SaveChanges();
            }
        }
        public bool IsPublishPage(int?id)
        {
            using (EntitiesContext context = new EntitiesContext()) {
                var item = context.PageContentEssences.Find(id);
                item.IsPublished = !item.IsPublished;

                context.SaveChanges();

                return(item.IsPublished);
            }
        }
예제 #30
0
 public static void SetRequestedTrue(string userId)
 {
     using (var db = new EntitiesContext())
     {
         var profile = db.UserProfiles.Where(x => x.IdUser == userId).SingleOrDefault();
         if (profile != null)
         {
             profile.RequestedAcces = true;
             db.SaveChanges();
         }
         else
         {
             var myProfile = new UserProfile {
                 IdUser = userId, RequestedAcces = true, IdCity = 1, City = "Iasi", MinPrice = 0, MaxPrice = 100, MinRating = 1
             };
             db.UserProfiles.Add(myProfile);
             db.SaveChanges();
         }
     }
 }
        private void ProcessPackageEdits(IEnumerable<PackageEdit> editsForThisPackage, EntitiesContext entitiesContext)
        {
            // List of Work to do:
            // 1) Backup old blob, if the original has not been backed up yet
            // 2) Downloads blob, create new NUPKG locally
            // 3) Upload blob
            // 4) Update the database
            PackageEdit edit = editsForThisPackage.OrderByDescending(pe => pe.Timestamp).First();

            var blobClient = StorageAccount.CreateCloudBlobClient();
            var packagesContainer = Util.GetPackagesBlobContainer(blobClient);

            var latestPackageFileName = Util.GetPackageFileName(edit.Package.PackageRegistration.Id, edit.Package.Version);
            var originalPackageFileName = Util.GetBackupOfOriginalPackageFileName(edit.Package.PackageRegistration.Id, edit.Package.Version);

            var originalPackageBackupBlob = packagesContainer.GetBlockBlobReference(originalPackageFileName);
            var latestPackageBlob = packagesContainer.GetBlockBlobReference(latestPackageFileName);

            var edits = new List<Action<ManifestMetadata>>
            { 
                (m) => { m.Authors = edit.Authors; },
                (m) => { m.Copyright = edit.Copyright; },
                (m) => { m.Description = edit.Description; },
                (m) => { m.IconUrl = edit.IconUrl; },
                (m) => { m.LicenseUrl = edit.LicenseUrl; },
                (m) => { m.ProjectUrl = edit.ProjectUrl; },
                (m) => { m.ReleaseNotes = edit.ReleaseNotes; },
                (m) => { m.RequireLicenseAcceptance = edit.RequiresLicenseAcceptance; },
                (m) => { m.Summary = edit.Summary; },
                (m) => { m.Title = edit.Title; },
                (m) => { m.Tags = edit.Tags; },
            };

            Log.Info(
                "Processing Edit Key={0}, PackageId={1}, Version={2}",
                edit.Key,
                edit.Package.PackageRegistration.Id,
                edit.Package.Version);
            
            if (!WhatIf)
            {
                edit.TriedCount += 1;
                int nr = entitiesContext.SaveChanges();
                if (nr != 1)
                {
                    throw new ApplicationException(
                        String.Format("Something went terribly wrong, only one entity should be updated but actually {0} entities were updated", nr));
                }
            }

            ArchiveOriginalPackageBlob(originalPackageBackupBlob, latestPackageBlob);
            using (var readWriteStream = new MemoryStream())
            {
                // Download to memory
                CloudBlockBlob downloadSourceBlob = WhatIf ? latestPackageBlob : originalPackageBackupBlob;
                Log.Info("Downloading original package blob to memory {0}", downloadSourceBlob.Name);
                downloadSourceBlob.DownloadToStream(readWriteStream);

                // Rewrite in memory
                Log.Info("Rewriting nupkg package in memory", downloadSourceBlob.Name);
                NupkgRewriter.RewriteNupkgManifest(readWriteStream, edits);

                // Get updated hash code, and file size
                Log.Info("Computing updated hash code of memory stream");
                var newPackageFileSize = readWriteStream.Length;
                var hashAlgorithm = HashAlgorithm.Create("SHA512");
                byte[] hashBytes = hashAlgorithm.ComputeHash(readWriteStream.GetBuffer());
                var newHash = Convert.ToBase64String(hashBytes);

                if (!WhatIf)
                {
                    // Snapshot the blob
                    var blobSnapshot = latestPackageBlob.CreateSnapshot();

                    // Start Transaction: Complete the edit in the gallery DB.
                    // Use explicit SQL transactions instead of EF operation-grouping 
                    // so that we can manually roll the transaction back on a blob related failure.
                    ObjectContext objectContext = (entitiesContext as IObjectContextAdapter).ObjectContext;
                    ((objectContext.Connection) as EntityConnection).Open(); // must open in order to begin transaction
                    using (EntityTransaction transaction = ((objectContext.Connection) as EntityConnection).BeginTransaction())
                    {
                        edit.Apply(hashAlgorithm: "SHA512", hash: newHash, packageFileSize: newPackageFileSize);

                        // Add to transaction: delete all the pending edits of this package.
                        foreach (var eachEdit in editsForThisPackage)
                        {
                            entitiesContext.DeleteOnCommit(eachEdit);
                        }

                        entitiesContext.SaveChanges(); // (transaction is still not committed, but do some EF legwork up-front of modifying the blob)
                        try
                        {
                            // Reupload blob
                            Log.Info("Uploading blob from memory {0}", latestPackageBlob.Name);
                            readWriteStream.Position = 0;
                            latestPackageBlob.UploadFromStream(readWriteStream);
                        }
                        catch (Exception e)
                        {
                            // Uploading the updated nupkg failed.
                            // Rollback the transaction, which restores the Edit to PackageEdits so it can be attempted again.
                            Log.Error("(error) - package edit blob update failed. Rolling back the DB transaction.");
                            Log.ErrorException("(exception", e);
                            Log.Error("(note) - blob snapshot URL = " + blobSnapshot.Uri);
                            transaction.Rollback();
                            return;
                        }

                        try
                        {
                            transaction.Commit();
                        }
                        catch (Exception e)
                        {
                            // Commit changes to DB failed.
                            // Since our blob update wasn't part of the transaction (and doesn't AFAIK have a 'commit()' operator we can utilize for the type of blobs we are using)
                            // try, (single attempt) to roll back the blob update by restoring the previous snapshot.
                            Log.Error("(error) - package edit DB update failed. Trying to roll back the blob to its previous snapshot.");
                            Log.ErrorException("(exception", e);
                            Log.Error("(note) - blob snapshot URL = " + blobSnapshot.Uri);
                            try
                            {
                                latestPackageBlob.StartCopyFromBlob(blobSnapshot);
                            }
                            catch (Exception e2)
                            {
                                // In this case it may not be the end of the world - the package metadata mismatches the edit now, 
                                // but there's still an edit in the queue, waiting to be rerun and put everything back in synch.
                                Log.Error("(error) - rolling back the package blob to its previous snapshot failed.");
                                Log.ErrorException("(exception", e2);
                                Log.Error("(note) - blob snapshot URL = " + blobSnapshot.Uri);
                            }
                        }
                    }
                }
            }
        }
        private void ProcessPackageEdits(int packageKey, IEnumerable<PackageEdit> editsToDelete)
        {
            // Create a fresh entities context so that we work in isolation
            var entitiesContext = new EntitiesContext(ConnectionString.ConnectionString, readOnly: false);

            // Get the most recent edit for this package
            var edit = entitiesContext.Set<PackageEdit>()
                .Where(pe => pe.PackageKey == packageKey && pe.TriedCount < 3)
                .Include(pe => pe.Package)
                .Include(pe => pe.Package.PackageRegistration)
                .Include(pe => pe.User)
                .OrderByDescending(pe => pe.Timestamp)
                .First();

            // List of Work to do:
            // 1) Backup old blob, if the original has not been backed up yet
            // 2) Downloads blob, create new NUPKG locally
            // 3) Upload blob
            // 4) Update the database
            var blobClient = StorageAccount.CreateCloudBlobClient();
            var packagesContainer = Util.GetPackagesBlobContainer(blobClient);

            var latestPackageFileName = Util.GetPackageFileName(edit.Package.PackageRegistration.Id, edit.Package.Version);
            var originalPackageFileName = Util.GetBackupOfOriginalPackageFileName(edit.Package.PackageRegistration.Id, edit.Package.Version);

            var originalPackageBackupBlob = packagesContainer.GetBlockBlobReference(originalPackageFileName);
            var latestPackageBlob = packagesContainer.GetBlockBlobReference(latestPackageFileName);

            var edits = new List<Action<ManifestEdit>>
            {
                (m) => { m.Authors = edit.Authors; },
                (m) => { m.Copyright = edit.Copyright; },
                (m) => { m.Description = edit.Description; },
                (m) => { m.IconUrl = edit.IconUrl; },
                (m) => { m.LicenseUrl = edit.LicenseUrl; },
                (m) => { m.ProjectUrl = edit.ProjectUrl; },
                (m) => { m.ReleaseNotes = edit.ReleaseNotes; },
                (m) => { m.RequireLicenseAcceptance = edit.RequiresLicenseAcceptance; },
                (m) => { m.Summary = edit.Summary; },
                (m) => { m.Title = edit.Title; },
                (m) => { m.Tags = edit.Tags; },
            };

            Log.Info(
                "Processing Edit Key={0}, PackageId={1}, Version={2}, User={3}",
                edit.Key,
                edit.Package.PackageRegistration.Id,
                edit.Package.Version,
                edit.User.Username);

            if (!WhatIf)
            {
                edit.TriedCount += 1;
                int nr = entitiesContext.SaveChanges();
                if (nr != 1)
                {
                    throw new Exception(
                        $"Something went terribly wrong, only one entity should be updated but actually {nr} entities were updated");
                }
            }

            try
            {
                ArchiveOriginalPackageBlob(originalPackageBackupBlob, latestPackageBlob);
                using (var readWriteStream = new MemoryStream())
                {
                    // Download to memory
                    CloudBlockBlob downloadSourceBlob = WhatIf ? latestPackageBlob : originalPackageBackupBlob;
                    Log.Info("Downloading original package blob to memory {0}", downloadSourceBlob.Name);
                    downloadSourceBlob.DownloadToStream(readWriteStream);

                    // Rewrite in memory
                    Log.Info("Rewriting nupkg package in memory", downloadSourceBlob.Name);
                    NupkgRewriter.RewriteNupkgManifest(readWriteStream, edits);

                    // Get updated hash code, and file size
                    Log.Info("Computing updated hash code of memory stream");
                    var newPackageFileSize = readWriteStream.Length;
                    var hashAlgorithm = HashAlgorithm.Create("SHA512");
                    byte[] hashBytes = hashAlgorithm.ComputeHash(readWriteStream.GetBuffer());
                    var newHash = Convert.ToBase64String(hashBytes);

                    if (!WhatIf)
                    {
                        // Snapshot the blob
                        var blobSnapshot = latestPackageBlob.CreateSnapshot();

                        // Build up the changes in the entities context
                        edit.Apply(hashAlgorithm: "SHA512", hash: newHash, packageFileSize: newPackageFileSize);
                        foreach (var eachEdit in editsToDelete)
                        {
                            entitiesContext.DeleteOnCommit(eachEdit);
                        }

                        // Upload the blob before doing SaveChanges(). If blob update fails, we won't do SaveChanges() and the edit can be retried.
                        // If SaveChanges() fails we can undo the blob upload.
                        try
                        {
                            Log.Info("Uploading blob from memory {0}", latestPackageBlob.Name);
                            readWriteStream.Position = 0;
                            latestPackageBlob.UploadFromStream(readWriteStream);
                        }
                        catch (Exception e)
                        {
                            Log.Error("(error) - package edit blob update failed.");
                            Log.ErrorException("(exception)", e);
                            Log.Error("(note) - blob snapshot URL = " + blobSnapshot.Uri);
                            throw; // To handler block that will record error in DB
                        }

                        try
                        {
                            // SaveChanges tries to commit changes to DB
                            entitiesContext.SaveChanges();
                        }
                        catch (Exception e)
                        {
                            // Commit changes to DB probably failed.
                            // Since our blob update wasn't part of the transaction (and doesn't AFAIK have a 'commit()' operator we can utilize for the type of blobs we are using)
                            // try, (single attempt) to roll back the blob update by restoring the previous snapshot.
                            Log.Error("(error) - package edit DB update failed. Trying to roll back the blob to its previous snapshot.");
                            Log.ErrorException("(exception)", e);
                            Log.Error("(note) - blob snapshot URL = " + blobSnapshot.Uri);
                            try
                            {
                                latestPackageBlob.StartCopyFromBlob(blobSnapshot);
                            }
                            catch (Exception e2)
                            {
                                // If blob rollback fails it is not be the end of the world
                                // - the package metadata mismatches the edit now,
                                // but there should still an edit in the queue, waiting to be rerun and put everything back in synch.
                                Log.Error("(error) - rolling back the package blob to its previous snapshot failed.");
                                Log.ErrorException("(exception)", e2);
                                Log.Error("(note) - blob snapshot URL = " + blobSnapshot.Uri);
                            }

                            throw; // To handler block that will record error in DB
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (!WhatIf)
                {
                    try
                    {
                        Log.Info("Storing the error on package edit with key {0}", edit.Key);

                        // Try to record the error into the PackageEdit database record
                        // so that we can actually diagnose failures.
                        // This must be done on a fresh context to ensure no conflicts.
                        var errorContext = new EntitiesContext(ConnectionString.ConnectionString, readOnly: false);
                        var errorEdit = errorContext.Set<PackageEdit>().Where(pe => pe.Key == edit.Key).FirstOrDefault();

                        if (errorEdit != null)
                        {
                            errorEdit.LastError = $"{e.GetType()} : {e}";
                            errorContext.SaveChanges();
                        }
                        else
                        {
                            Log.Info("The package edit with key {0} couldn't be found. It was likely canceled and deleted.", edit.Key);
                        }
                    }
                    catch (Exception errorException)
                    {
                        Log.ErrorException("(error) - couldn't save the last error on the edit that was being applied.", errorException);
                    }
                }
            }
        }