public static void RenameImageAndDependencies(CMSDatabase db, IHostingEnvironment env, string pathToImages, string oldImageName, string newImageName, string imageExtension, bool saveChangesInDB = true) { if (string.IsNullOrEmpty(pathToImages) || string.IsNullOrEmpty(oldImageName) || string.IsNullOrEmpty(newImageName) || !Directory.Exists(pathToImages)) { return; } if (!pathToImages[pathToImages.Length - 1].Equals('/')) { pathToImages = pathToImages.Insert(pathToImages.Length, "/"); } string[] images = Directory.GetFiles(pathToImages, $"*{oldImageName}*{imageExtension}"); Regex regex = new Regex($"{oldImageName}(_\\d+x\\d+)?(_q\\d{{1,3}})?{imageExtension}$"); images = (from img in images where regex.IsMatch(img) select img).ToArray(); foreach (var img in images) { string fileEnding = img.Substring(pathToImages.Length + oldImageName.Length); File.Move(img, $"{pathToImages}{newImageName}{fileEnding}"); } string shortPathToOldImage = pathToImages.Substring(env.GetStorageFolderFullPath().Length).Insert(0, "/") + oldImageName + imageExtension; string shortPathToNewImage = pathToImages.Substring(env.GetStorageFolderFullPath().Length).Insert(0, "/") + newImageName + imageExtension; // Изменяем данные в БД // Если в БД есть неудаленная информация, то удаляем её Image image = db.Images.FirstOrDefault(img => img.ShortPathHash == OtherFunctions.GetHashFromString(shortPathToNewImage) && img.ShortPath.Equals(shortPathToNewImage, StringComparison.Ordinal)); if (image != null && db.Entry(image).State != EntityState.Modified) { db.Remove(image); } image = db.Images.FirstOrDefault(img => img.ShortPathHash == OtherFunctions.GetHashFromString(shortPathToOldImage) && img.ShortPath.Equals(shortPathToOldImage, StringComparison.Ordinal)); if (image != null) { if (db.Entry(image).State == EntityState.Deleted) { db.Entry(image).State = EntityState.Modified; } image.ShortPath = shortPathToNewImage; image.ShortPathHash = OtherFunctions.GetHashFromString(shortPathToNewImage); image.FullName = shortPathToNewImage.Substring(shortPathToNewImage.LastIndexOf('/') + 1); } if (saveChangesInDB) { db.SaveChanges(); } }
private void TransferLogsFromDbToFiles(CMSDatabase db, Microsoft.AspNetCore.Hosting.IHostingEnvironment env) { foreach (var user in db.Users.ToArray()) { db.Entry(user).Collection(u => u.AdminPanelLogs).Load(); user.AdminPanelLogs.Reverse(); LogManagementFunctions.UserLogsToLogFile(user, DateTime.Now, env.GetLogsFolderFullPath()); db.Entry(user).State = EntityState.Detached; foreach (var log in user.AdminPanelLogs) { db.AdminPanelLogs.Remove(log); } } db.SaveChanges(); }
// Сравниваем данные в кукисах и хедерах с данными на сервере. public static User CheckCookies(CMSDatabase db, HttpContext context) { string userName = context.Request.Cookies["userName"]; if (string.IsNullOrEmpty(userName)) { return(null); } ConnectedUser connectedUser = db.ConnectedUsers.FirstOrDefault( cu => cu.UserName.Equals(userName, StringComparison.Ordinal) // loginKey - это случайно сгенерированный в методе SecurityFunctions.GetRandomKey ключ && cu.LoginKey.Equals(context.Request.Cookies["loginKey"], StringComparison.Ordinal) // Проверка ip-адреса && cu.IPAdress.Equals(context.Connection.RemoteIpAddress.ToString(), StringComparison.Ordinal) && cu.UserAgent.Equals(context.Request.Headers["User-Agent"], StringComparison.Ordinal) ); if (connectedUser == null) { return(null); } db.Entry(connectedUser).Reference(cu => cu.User).Load(); if ((DateTime.Now - connectedUser.LastActionTime).TotalMinutes > connectedUser.User.IdleTime) { db.ConnectedUsers.Remove(connectedUser); db.SaveChanges(); return(null); } connectedUser.LastActionTime = DateTime.Now; db.Update(connectedUser); db.SaveChanges(); db.Entry(connectedUser.User).Reference(u => u.UserType).Load(); return(connectedUser.User); }
public static LinkedList <int> GetDependentPageIDs(CMSDatabase db, UsualPage page, LinkedList <int> idList = null) { if (idList == null) { idList = new LinkedList <int>(); } UsualPage[] usualPages = usualPages = db.UsualPages.Where(up => up.PreviousPageID.HasValue && up.PreviousPageID == page.ID).ToArray(); foreach (var up in usualPages) { GetDependentPageIDs(db, up, idList); } idList.AddLast(page.ID); db.Entry(page).State = EntityState.Detached; return(idList); }
public static void DeleteProduct(CMSDatabase db, int?productID, HttpContext context, out bool successfullyDeleted) { if (!productID.HasValue) { successfullyDeleted = false; return; } ProductPage product = db.ProductPages.FirstOrDefault(pp => pp.ID == productID.Value); if (product == null) { successfullyDeleted = false; return; } IHostingEnvironment env = context.RequestServices.GetRequiredService <IHostingEnvironment>(); string pathToImages = $"{env.GetProductsImagesFolderFullPath()}{product.ID}/"; // Удаляем данные об изображениях из БД string[] images = ImagesManagementFunctions.GetProductImageUrls(product, env); for (int i = 0; i < images.Length; ++i) { Image image = db.Images.FirstOrDefault(img => img.ShortPathHash == OtherFunctions.GetHashFromString(images[i]) && img.ShortPath.Equals(images[i], StringComparison.Ordinal)); if (image != null) { db.Images.Remove(image); } } db.Entry(product).Reference(pp => pp.PreviousPage).Load(); --product.PreviousPage.ProductsCount; db.ProductPages.Remove(product); db.SaveChanges(); // Удаляем папку с изображениями товара if (Directory.Exists(pathToImages)) { Directory.Delete(pathToImages, true); } successfullyDeleted = true; LogManagementFunctions.AddAdminPanelLog( db: db, context: context, info: $"{product.PageName} (ID-{product.ID.ToString()}): {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.ProductDeleted}" ); }
private static LinkedList <Chunk> GetChunks(CMSDatabase db, string source, string currentChunkName = null) { LinkedList <Chunk> chunks = new LinkedList <Chunk>(); int pointer = 0; while (pointer != -1) { pointer = GetNextChunk(pointer, source, out string chunkName); if (!string.IsNullOrEmpty(chunkName) && !chunkName.Equals(currentChunkName, StringComparison.Ordinal)) { Chunk chunk = db.Chunks.FirstOrDefaultAsync(tc => tc.Name.Equals(chunkName, StringComparison.Ordinal)).Result; if (chunk != null) { db.Entry(chunk).State = EntityState.Detached; chunks.AddLast(chunk); } } } return(chunks); }
// ЭТОТ МЕТОД НЕ СОХРАНЯЕТ ИЗМЕНЕНИЯ, ТОЛЬКО ВНОСИТ ИХ // После изменения или удаления страницы-родителя, необходимо изменить все страницы, наследующиеся от // этой родительской страницы. public static void RefreshPageAndDependencies(CMSDatabase db, Page page) { switch (page) { case UsualPage up: db.Entry(up).Reference(p => p.PreviousPage).LoadAsync().Wait(); if (up.PreviousPage == null && up.Alias.Equals("index", StringComparison.Ordinal)) { up.Alias = "ind"; } if (up.PreviousPage == null || up.PreviousPage.RequestPath.Equals("/", StringComparison.Ordinal)) { up.RequestPath = $"/{up.Alias}"; } else { up.RequestPath = $"{up.PreviousPage.RequestPath}/{up.Alias}"; } up.BreadcrumbsHtml = PagesManagementFunctions.GetBreadcrumbsHTML(up); break; case CategoryPage cp: db.Entry(cp).Reference(p => p.PreviousPage).LoadAsync().Wait(); if (cp.PreviousPage == null && cp.Alias.Equals("index", StringComparison.Ordinal)) { cp.Alias = "ind"; } if (cp.PreviousPage == null || cp.PreviousPage.RequestPath.Equals("/", StringComparison.Ordinal)) { cp.RequestPath = $"/{cp.Alias}"; } else { cp.RequestPath = $"{cp.PreviousPage.RequestPath}/{cp.Alias}"; } cp.BreadcrumbsHtml = PagesManagementFunctions.GetBreadcrumbsHTML(cp); break; case ProductPage pp: db.Entry(pp).Reference(p => p.PreviousPage).LoadAsync().Wait(); pp.RequestPath = $"{pp.PreviousPage.RequestPath}/{pp.Alias}"; pp.BreadcrumbsHtml = PagesManagementFunctions.GetBreadcrumbsHTML(pp); break; } PagesManagementFunctions.SetUniqueAliasName(db, page); page.RequestPathHash = OtherFunctions.GetHashFromString(page.RequestPath); switch (page) { case UsualPage up: List <UsualPage> usualPages = db.UsualPages.Where(p => p.PreviousPageID == up.ID).ToList(); List <CategoryPage> categoryPages = db.CategoryPages.Where(p => p.PreviousPageID == up.ID).ToList(); foreach (var u_page in usualPages) { RefreshPageAndDependencies(db, u_page); } foreach (var c_page in categoryPages) { RefreshPageAndDependencies(db, c_page); } break; case CategoryPage cp: List <ProductPage> productPages = db.ProductPages.Where(p => p.PreviousPageID == cp.ID).ToList(); foreach (var p_page in productPages) { RefreshPageAndDependencies(db, p_page); } break; } }