Ejemplo n.º 1
0
 private void ClearVisitorList(CMSDatabase db)
 {
     foreach (var visitor in db.Visitors)
     {
         db.Visitors.Remove(visitor);
     }
     db.SaveChanges();
 }
Ejemplo n.º 2
0
        // На стороне сервера хранится логин, ключ для входа, ip-адрес, информация о браузере и время последнего действия
        // На стороне клиента, в куках, сохраняем логин и ключ для входа
        public static void AddConnectedUser(CMSDatabase db, User user, HttpContext context)
        {
            ConnectedUser connectedUser = db.ConnectedUsers.FirstOrDefault(cu => cu.UserID == user.ID);

            // Если пользователь уже был залогинен, то обновляем его данные
            // Это сделано, если вдруг пользователь заходит с другого браузера
            // С того же самого браузера, с которого он залогинился, пользователь
            // не попадет в этот блок кода, т.к. его либо сразу пропустит в админку, либо
            // удалится запись из-за длительного бездействия и тогда его данные нужно будет
            // добавить в else блоке
            if (connectedUser != null)
            {
                connectedUser.UserName       = SecurityFunctions.GetMd5Hash(SecurityFunctions.GetMd5Hash(user.Login + SecurityFunctions.GetRandomKey(10, 20)));
                connectedUser.LoginKey       = SecurityFunctions.GetRandomKey(15, 30);
                connectedUser.LastActionTime = DateTime.Now;
                connectedUser.UserAgent      = context.Request.Headers["User-Agent"];
                connectedUser.IPAdress       = context.Connection.RemoteIpAddress.ToString();
                db.SaveChanges();
            }

            else
            {
                connectedUser = new ConnectedUser
                {
                    UserName       = SecurityFunctions.GetMd5Hash(SecurityFunctions.GetMd5Hash(user.Login + SecurityFunctions.GetRandomKey(10, 20))),
                    LoginKey       = SecurityFunctions.GetRandomKey(15, 30),
                    IPAdress       = context.Connection.RemoteIpAddress.ToString(),
                    LastActionTime = DateTime.Now,
                    UserAgent      = context.Request.Headers["User-Agent"],
                    User           = user
                };
                db.ConnectedUsers.Add(connectedUser);
                db.SaveChanges();
            }

            LogManagementFunctions.AddAdminPanelLog(
                db: db,
                context: context,
                info: $"{(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.LoggedIn}. IP: {context.Connection.RemoteIpAddress.ToString()}",
                user: user
                );

            // Использовать вместо userName хэш?
            context.Response.Cookies.Append("userName", connectedUser.UserName);
            context.Response.Cookies.Append("loginKey", connectedUser.LoginKey);
        }
Ejemplo n.º 3
0
        public ImageHandler(string pathToImage, bool itsFullPath, CMSDatabase db, IHostingEnvironment env)
        {
            this.db  = db;
            this.env = env;
            if (pathToImage[pathToImage.Length - 1].Equals('/'))
            {
                return;
            }
            pathToImageFolder = pathToImage.Substring(0, pathToImage.LastIndexOf('/') + 1);
            sourceImageName   = pathToImage.Substring(pathToImageFolder.Length);
            if (!sourceImageName.Contains("."))
            {
                return;
            }
            sourceImageName      = sourceImageName.Substring(0, sourceImageName.LastIndexOf('.'));
            sourceImageExtension = pathToImage.Substring(pathToImageFolder.Length + sourceImageName.Length);
            if ((!sourceImageExtension.Equals(".jpg", StringComparison.OrdinalIgnoreCase) &&
                 !sourceImageExtension.Equals(".jpeg", StringComparison.OrdinalIgnoreCase) &&
                 !sourceImageExtension.Equals(".png", StringComparison.OrdinalIgnoreCase)))
            {
                return;
            }
            if (!itsFullPath)
            {
                if (pathToImageFolder[0].Equals('/'))
                {
                    pathToImageFolder = pathToImageFolder.Substring(1);
                }
                pathToImageFolder = env.GetStorageFolderFullPath() + pathToImageFolder;
            }
            sourceImageFullName  = sourceImageName + sourceImageExtension;
            sourceImageFullPath  = pathToImageFolder + sourceImageFullName;
            isExisted            = File.Exists(sourceImageFullPath);
            sourceImageShortPath = sourceImageFullPath.Substring(env.GetStorageFolderFullPath().Length).Insert(0, "/");
            // Если изображения не существует, то удаляем зависимые изображения, если таковые имеются и информацию из БД
            if (!isExisted)
            {
                // Удаляем информацию об изображении из БД
                Image image = db.Images.FirstOrDefault(img => img.ShortPathHash == OtherFunctions.GetHashFromString(sourceImageShortPath) &&
                                                       img.ShortPath.Equals(sourceImageShortPath, StringComparison.Ordinal));
                if (image != null)
                {
                    db.Images.Remove(image);
                    db.SaveChanges();
                }

                ImagesManagementFunctions.DeleteDependentImages(pathToImageFolder, sourceImageFullName);
            }
            else
            {
                GetSourceImageInfo();
            }
        }
Ejemplo n.º 4
0
    private static void SetDeafaultUserType(CMSDatabase db)
    {
        UserType userType = db.UserTypes.AsNoTracking().FirstOrDefault(ut => ut.AccessLevel == AccessLevel.VeryHigh);

        if (userType == null)
        {
            db.UserTypes.Add(new UserType {
                Name = "Admin", AccessLevel = AccessLevel.VeryHigh
            });
            db.SaveChanges();
        }
    }
Ejemplo n.º 5
0
        // Сравниваем данные в кукисах и хедерах с данными на сервере.
        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);
        }
Ejemplo n.º 6
0
        public static void DeleteTemplate(CMSDatabase db, int?itemID, HttpContext context, out bool successfullyDeleted)
        {
            if (!itemID.HasValue)
            {
                successfullyDeleted = false;
                return;
            }
            Template template = db.Templates.FirstOrDefault(t => t.ID == itemID);

            if (template == null)
            {
                successfullyDeleted = false;
                return;
            }
            IHostingEnvironment env   = context.RequestServices.GetRequiredService <IHostingEnvironment>();
            string pathToTemplateFile = $"{env.GetTemplatesFolderFullPath()}{template.Name}.cshtml";

            if (File.Exists(pathToTemplateFile))
            {
                File.Delete(pathToTemplateFile);
            }

            // Удаляем ссылку на шаблон у страниц, которые использовали его
            var usualPages    = db.UsualPages.Where(up => up.TemplateId == template.ID).ToList();
            var categoryPages = db.CategoryPages.Where(cp => cp.TemplateId == template.ID).ToList();
            var productPages  = db.ProductPages.Where(pp => pp.TemplateId == template.ID).ToList();

            foreach (var up in usualPages)
            {
                up.Template = null;
            }
            foreach (var cp in categoryPages)
            {
                cp.Template = null;
            }
            foreach (var pp in productPages)
            {
                pp.Template = null;
            }

            db.Templates.Remove(template);
            db.SaveChanges();
            successfullyDeleted = true;
            LogManagementFunctions.AddAdminPanelLog(
                db: db,
                context: context,
                info: $"{template.Name} (ID-{template.ID.ToString()}): {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.TemplateDeleted}"
                );
        }
        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();
            }
        }
Ejemplo n.º 8
0
 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();
 }
Ejemplo n.º 9
0
        public static void EditRedirection(CMSDatabase db, int?itemID, RedirectionModel model, HttpContext context, out bool successfullyCompleted)
        {
            if (string.IsNullOrEmpty(model.RedirectionPath) || string.IsNullOrEmpty(model.RequestPath) || !itemID.HasValue ||
                model.RequestPath.Equals(model.RedirectionPath, StringComparison.OrdinalIgnoreCase))
            {
                successfullyCompleted = false;
                return;
            }
            Redirection redirection = db.Redirections.FirstOrDefault(r => r.ID == itemID.Value);

            if (redirection == null)
            {
                successfullyCompleted = false;
                return;
            }
            string oldRequestPath     = redirection.RequestPath;
            string oldRedirectionPath = redirection.RedirectionPath;

            model.RequestPath     = GetCorrectUrlPath(model.RequestPath);
            model.RedirectionPath = GetCorrectUrlPath(model.RedirectionPath);
            if (model.RequestPath.Equals(model.RedirectionPath, StringComparison.Ordinal))
            {
                successfullyCompleted = false;
                return;
            }
            Redirection match = db.Redirections.FirstOrDefault(r => r.ID != itemID.Value && r.RequestPathHash == OtherFunctions.GetHashFromString(model.RequestPath) &&
                                                               r.RequestPath.Equals(model.RequestPath, StringComparison.Ordinal) && r.RedirectionPath.Equals(model.RedirectionPath, StringComparison.Ordinal));

            if (match != null)
            {
                successfullyCompleted = false;
                return;
            }
            redirection.RequestPath     = model.RequestPath;
            redirection.RequestPathHash = OtherFunctions.GetHashFromString(model.RequestPath);
            redirection.RedirectionPath = model.RedirectionPath;
            db.SaveChanges();
            successfullyCompleted = true;

            LogManagementFunctions.AddAdminPanelLog(
                db: db,
                context: context,
                info: $"{oldRequestPath} -> {oldRedirectionPath}: {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.RedirectionEditedTo} {redirection.RequestPath} -> {redirection.RedirectionPath}"
                );
        }
Ejemplo n.º 10
0
        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}"
                );
        }
Ejemplo n.º 11
0
 public static void AddAdminPanelLog(CMSDatabase db, HttpContext context, string info, User user = null)
 {
     if (user == null)
     {
         user = context.Items["User"] as User;
     }
     if (user == null)
     {
         return;
     }
     db.AdminPanelLogs.Add(new AdminPanelLog
     {
         Info = info,
         Time = DateTime.Now,
         User = user
     });
     db.SaveChanges();
 }
Ejemplo n.º 12
0
        public static void Exit(CMSDatabase db, User user, HttpContext context, out int statusCode)
        {
            if (user == null)
            {
                statusCode = 404;
                return;
            }
            ConnectedUser connectedUser = db.ConnectedUsers.FirstOrDefault(cu => cu.UserID == user.ID);

            if (connectedUser == null)
            {
                statusCode = 404;
                return;
            }
            db.ConnectedUsers.Remove(connectedUser);
            db.SaveChanges();
            statusCode = 200;
        }
        public static void EditUserData(CMSDatabase db, UserModel model, HttpContext context, out int statusCode)
        {
            if (!model.ID.HasValue ||
                !CorrectLogin(model.Login) ||
                (!string.IsNullOrEmpty(model.NewPassword) && !CorrectPassword(model.NewPassword)) ||
                model.IdleTime < 10 || model.IdleTime > 10080
                )
            {
                statusCode = 422;
                return;
            }
            User editableUser = db.Users.FirstOrDefault(u => u.ID == model.ID.Value);

            if (editableUser == null)
            {
                statusCode = 404;
                return;
            }
            else if (editableUser != context.Items["User"] as User || !editableUser.Password.Equals(SecurityFunctions.GetPasswordHash(model.CurrentPassword)))
            {
                statusCode = 403;
                return;
            }
            else if (!editableUser.Login.Equals(model.Login, StringComparison.Ordinal) && db.Users.FirstOrDefault(u => u.Login.Equals(model.Login, StringComparison.Ordinal)) != null)
            {
                statusCode = 409;
                return;
            }
            editableUser.Login = model.Login;
            if (!string.IsNullOrEmpty(model.NewPassword))
            {
                editableUser.Password = SecurityFunctions.GetPasswordHash(model.NewPassword);
            }
            editableUser.IdleTime = model.IdleTime;
            editableUser.Email    = model.Email;
            db.SaveChanges();
            statusCode = 200;

            LogManagementFunctions.AddAdminPanelLog(
                db: db,
                context: context,
                info: $"{(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.UserDataEdited}"
                );
        }
Ejemplo n.º 14
0
        public static void AddTemplate(CMSDatabase db, TemplateModel model, HttpContext context, out bool successfullyCompleted)
        {
            Template template = TemplatesManagementFunctions.TemplateModelToITemplate <Template>(model, context);

            if (template == null)
            {
                successfullyCompleted = false;
                return;
            }
            IHostingEnvironment env = context.RequestServices.GetService <IHostingEnvironment>();

            if (template.Name.Equals("_ViewImports", System.StringComparison.OrdinalIgnoreCase))
            {
                template.Name = "view_imports";
            }
            template.TemplatePath = env.GetTemplatesFolderShortPath();
            TemplatesManagementFunctions.SetUniqueITemplateName(db, template);
            template.TemplatePath += $"{template.Name}.cshtml";
            string cshtmlContent = TemplatesManagementFunctions.SourceToCSHTML(
                db: db,
                source: template.TemplateSource,
                modelType: "Page",
                env: env,
                skipChunkName: null
                );

            TemplatesManagementFunctions.WriteCshtmlContentToFile(
                pathToTemplatesFolder: env.GetTemplatesFolderFullPath(),
                templateName: template.Name,
                chstmlContent: cshtmlContent
                );
            db.Templates.Add(template);
            db.SaveChanges();
            model.ID = template.ID;
            successfullyCompleted = true;

            LogManagementFunctions.AddAdminPanelLog(
                db: db,
                context: context,
                info: $"{template.Name} (ID-{template.ID.ToString()}): {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.TemplateAdded}"
                );
        }
Ejemplo n.º 15
0
        public static void AddSynonymForString(CMSDatabase db, SynonymForStringModel model, HttpContext context, out bool successfullyCompleted)
        {
            if (!string.IsNullOrEmpty(model.String) && !string.IsNullOrEmpty(model.Synonym))
            {
                SynonymForString match = db.SynonymsForStrings.AsNoTracking()
                                         .FirstOrDefault(s => (s.String.Equals(model.String, StringComparison.InvariantCultureIgnoreCase) && s.Synonym.Equals(model.Synonym, StringComparison.InvariantCultureIgnoreCase)) ||
                                                         (s.String.Equals(model.Synonym, StringComparison.InvariantCultureIgnoreCase) && s.Synonym.Equals(model.String, StringComparison.InvariantCultureIgnoreCase)));
                if (match != null)
                {
                    successfullyCompleted = false;
                    return;
                }

                SynonymForString synonymForString = new SynonymForString {
                    String = model.String, Synonym = model.Synonym
                };
                db.SynonymsForStrings.Add(synonymForString);
                try
                {
                    db.SaveChanges();
                }
                catch (DbUpdateException)
                {
                    successfullyCompleted = false;
                    return;
                }
                successfullyCompleted = true;


                LogManagementFunctions.AddAdminPanelLog(
                    db: db,
                    context: context,
                    info: $"{synonymForString.String} -> {synonymForString.Synonym}: {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.SynonymForStringAdded}"
                    );
            }
            else
            {
                successfullyCompleted = false;
            }
        }
Ejemplo n.º 16
0
        public static void AddPage(CMSDatabase db, PageModel model, HttpContext context, out bool successfullyCompleted)
        {
            Page page = PagesManagementFunctions.PageModelToPage(db, model, context);

            if (page == null)
            {
                successfullyCompleted = false;
                return;
            }
            db.Add(page);
            db.SaveChanges();
            model.ID = page.ID;
            successfullyCompleted = true;

            LogManagementFunctions.AddAdminPanelLog(
                db: db,
                context: context,
                info: $"{page.PageName} (ID-{page.ID.ToString()}): " +
                (page is UsualPage ? (context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.PageAdded
                : (context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.CategoryAdded)
                );
        }
Ejemplo n.º 17
0
        public static void AddUser(CMSDatabase db, UserModel model, HttpContext context, out int statusCode)
        {
            if (!CorrectLogin(model.Login) || !CorrectPassword(model.NewPassword) || !model.UserTypeId.HasValue ||
                db.UserTypes.FirstOrDefault(ut => ut.ID == model.UserTypeId.Value) == null)
            {
                statusCode = 422;
                return;
            }
            if (db.Users.AsNoTracking().FirstOrDefault(u => u.Login.Equals(model.Login, StringComparison.Ordinal)) != null)
            {
                statusCode = 409;
                return;
            }
            User user = new User
            {
                Login      = model.Login,
                Password   = SecurityFunctions.GetPasswordHash(model.NewPassword),
                IdleTime   = 10,
                UserTypeID = model.UserTypeId.Value
            };

            try
            {
                db.Users.Add(user);
            }
            catch (DbUpdateException)
            {
                statusCode = 409;
                return;
            }
            db.SaveChanges();
            statusCode = 201;

            LogManagementFunctions.AddAdminPanelLog(
                db: db,
                context: context,
                info: $"{user.Login} (ID-{user.ID.ToString()}): {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.UserAdded}"
                );
        }
Ejemplo n.º 18
0
        public static void AddUserType(CMSDatabase db, UserTypeModel model, HttpContext context, out bool successfullyCompleted)
        {
            if (string.IsNullOrEmpty(model.Name) || !model.AccessLevel.HasValue || !Enum.IsDefined(typeof(AccessLevel), model.AccessLevel.Value))
            {
                successfullyCompleted = false;
                return;
            }
            UserType userType = new UserType
            {
                Name        = model.Name,
                AccessLevel = model.AccessLevel.Value
            };

            db.UserTypes.Add(userType);
            db.SaveChanges();
            successfullyCompleted = true;

            LogManagementFunctions.AddAdminPanelLog(
                db: db,
                context: context,
                info: $"{userType.Name} ({userType.AccessLevel.ToString()}): {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.UserTypeAdded}"
                );
        }
Ejemplo n.º 19
0
        public static void EditChunk(CMSDatabase db, int?itemID, TemplateModel model, HttpContext context, out bool successfullyCompleted)
        {
            if (!itemID.HasValue || model == null)
            {
                successfullyCompleted = false;
                return;
            }
            Chunk editableChunk = db.Chunks.AsNoTracking().FirstOrDefault(t => t.ID == itemID);

            if (editableChunk == null)
            {
                successfullyCompleted = false;
                return;
            }
            Chunk editedChunk = TemplatesManagementFunctions.TemplateModelToITemplate <Chunk>(model, context);

            if (editedChunk == null)
            {
                successfullyCompleted = false;
                return;
            }
            if (editedChunk.Name.Equals("_ViewImports", StringComparison.OrdinalIgnoreCase))
            {
                editedChunk.Name = "view_imports";
            }
            IHostingEnvironment env = context.RequestServices.GetService <IHostingEnvironment>();

            editedChunk.ID           = itemID.Value;
            editedChunk.TemplatePath = env.GetChunksFolderShortPath();
            TemplatesManagementFunctions.SetUniqueITemplateName(db, editedChunk);
            editedChunk.TemplatePath += $"{editedChunk.Name}.cshtml";
            db.Chunks.Update(editedChunk);
            db.SaveChanges();
            successfullyCompleted = true;
            LogManagementFunctions.AddAdminPanelLog(
                db: db,
                context: context,
                info: $"{editableChunk.Name} (ID-{editableChunk.ID.ToString()}): {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.ChunkEdited}"
                );

            // Изменяем cshtml файл, если изменилось имя шаблона и/или код шаблона
            bool changedName           = !editedChunk.Name.Equals(editableChunk.Name, StringComparison.Ordinal);
            bool changedTemplateSource = !editedChunk.TemplateSource.Equals(editableChunk.TemplateSource, StringComparison.Ordinal);

            if (changedName && changedTemplateSource)
            {
                string pathToOldFileName = $"{env.GetChunksFolderFullPath()}{editableChunk.Name}.cshtml";
                if (File.Exists(pathToOldFileName))
                {
                    File.Delete(pathToOldFileName);
                }
                string cshtmlContent = TemplatesManagementFunctions.SourceToCSHTML(
                    db: db,
                    source: editedChunk.TemplateSource,
                    modelType: "Page",
                    env: env,
                    skipChunkName: editedChunk.Name
                    );
                TemplatesManagementFunctions.WriteCshtmlContentToFile(env.GetChunksFolderFullPath(), editedChunk.Name, cshtmlContent);
            }
            else if (changedName)
            {
                string pathToOldFileName = $"{env.GetChunksFolderFullPath()}{editableChunk.Name}.cshtml";
                if (File.Exists(pathToOldFileName))
                {
                    File.Move(pathToOldFileName, $"{env.GetChunksFolderFullPath()}{editedChunk.Name}.cshtml");
                }
                else
                {
                    string cshtmlContent = TemplatesManagementFunctions.SourceToCSHTML(
                        db: db,
                        source: editedChunk.TemplateSource,
                        modelType: "Page",
                        env: env,
                        skipChunkName: editedChunk.Name
                        );
                    TemplatesManagementFunctions.WriteCshtmlContentToFile(env.GetChunksFolderFullPath(), editedChunk.Name, cshtmlContent);
                }
            }
            else if (changedTemplateSource)
            {
                string cshtmlContent = TemplatesManagementFunctions.SourceToCSHTML(
                    db: db,
                    source: editedChunk.TemplateSource,
                    modelType: "Page",
                    env: env,
                    skipChunkName: editedChunk.Name
                    );
                TemplatesManagementFunctions.WriteCshtmlContentToFile(env.GetChunksFolderFullPath(), editedChunk.Name, cshtmlContent);
            }

            // Если изменилось название чанка, то получаем список шаблонов и чанков, которые использовали или теперь используют данный чанк
            // и делаем их перерендер
            if (changedName)
            {
                var templates = db.Templates.AsNoTracking()
                                .Where(t => t.TemplateSource.Contains($"[#{editableChunk.Name}]") || t.TemplateSource.Contains($"[#{editedChunk.Name}]"))
                                .ToList();
                var chunks = db.Chunks.AsNoTracking()
                             .Where(tc => tc.ID != itemID.Value &&
                                    (tc.TemplateSource.Contains($"[#{editableChunk.Name}]") || tc.TemplateSource.Contains($"[#{editedChunk.Name}]")))
                             .ToList();
                var renderTask = Task.Run(() =>
                {
                    foreach (var t in templates)
                    {
                        string cshtmlContent = TemplatesManagementFunctions.SourceToCSHTML(
                            db: db,
                            source: t.TemplateSource,
                            modelType: "Page",
                            env: env,
                            skipChunkName: null
                            );
                        TemplatesManagementFunctions.WriteCshtmlContentToFile(env.GetTemplatesFolderFullPath(), t.Name, cshtmlContent);
                    }
                });
                foreach (var c in chunks)
                {
                    string cshtmlContent = TemplatesManagementFunctions.SourceToCSHTML(
                        db: db,
                        source: c.TemplateSource,
                        modelType: "Page",
                        env: env,
                        skipChunkName: c.Name
                        );
                    TemplatesManagementFunctions.WriteCshtmlContentToFile(env.GetChunksFolderFullPath(), c.Name, cshtmlContent);
                }

                string productBlockFileContent = OtherFunctions.GetFileContent(env.GetProductBlockTemplateFullPath());
                if (changedName && productBlockFileContent.Contains($"[#{editableChunk.Name}]"))
                {
                    string[] additions =
                    {
                        "@using Treynessen.Functions;",
                        "@using Treynessen.Database.Entities;",
                        "@addTagHelper Treynessen.TagHelpers.ImageTagHelper, StoreCMS"
                    };
                    string productBlockCshtmlTemplate = TemplatesManagementFunctions.SourceToCSHTML(
                        db: db,
                        source: productBlockFileContent,
                        modelType: "ProductPage",
                        env: env,
                        skipChunkName: null,
                        additions: additions
                        );
                    using (StreamWriter writer = new StreamWriter(env.GetProductBlockCshtmlFullPath()))
                    {
                        writer.Write(productBlockCshtmlTemplate);
                    }
                }

                renderTask.Wait();
            }
        }
Ejemplo n.º 20
0
        public static void EditPage(CMSDatabase db, Model model, HttpContext context, out bool successfullyCompleted)
        {
            if (!model.itemID.HasValue || model.PageModel == null || !model.PageType.HasValue)
            {
                successfullyCompleted = false;
                return;
            }
            model.PageModel.PageType = model.PageType;
            bool isMainPage = false;

            model.PageModel.IsMainPage = false;
            Page editablePage = null;

            switch (model.PageModel.PageType)
            {
            case PageType.Usual:
                editablePage = db.UsualPages.AsNoTracking().FirstOrDefault(up => up.ID == model.itemID);
                if (editablePage == null)
                {
                    successfullyCompleted = false;
                    return;
                }
                model.PageModel.ID = editablePage.ID;
                isMainPage         = editablePage.RequestPath.Equals("/", StringComparison.Ordinal);
                break;

            case PageType.Category:
                editablePage = db.CategoryPages.AsNoTracking().FirstOrDefault(cp => cp.ID == model.itemID);
                if (editablePage == null)
                {
                    successfullyCompleted = false;
                    return;
                }
                model.PageModel.ID = editablePage.ID;
                break;

            default:
                successfullyCompleted = false;
                return;
            }
            model.PageModel.PageType = model.PageModel.PageType.Value;
            Page editedPage = PagesManagementFunctions.PageModelToPage(db, model.PageModel, context);

            if (editedPage != null)
            {
                if (editedPage is UsualPage up)
                {
                    if (isMainPage)
                    {
                        up.Alias           = "index";
                        up.RequestPath     = "/";
                        up.RequestPathHash = OtherFunctions.GetHashFromString(up.RequestPath);
                        up.PreviousPage    = null;
                    }
                    // Если родителем страницы является сама страница или зависимая страница, то возвращаем сообщение об ошибке
                    if (up.PreviousPage != null && PagesManagementFunctions.GetDependentPageIDs(db, up).Contains(up.PreviousPage.ID))
                    {
                        successfullyCompleted = false;
                        return;
                    }
                }
                else if (editedPage is CategoryPage cp)
                {
                    cp.ProductsCount         = (editablePage as CategoryPage).ProductsCount;
                    cp.LastProductTemplateID = (editablePage as CategoryPage).LastProductTemplateID;
                }
            }
            else
            {
                successfullyCompleted = false;
                return;
            }
            db.Update(editedPage);

            // Обновляем все зависимые страницы, если изменилось имя страницы и/или url страницы
            if (!editablePage.PageName.Equals(editedPage.PageName, StringComparison.InvariantCulture) ||
                !editablePage.RequestPath.Equals(editedPage.RequestPath, StringComparison.Ordinal))
            {
                if (editedPage is UsualPage)
                {
                    List <UsualPage>    usualPages    = db.UsualPages.Where(p => p.PreviousPageID == editedPage.ID).ToList();
                    List <CategoryPage> categoryPages = db.CategoryPages.Where(p => p.PreviousPageID == editedPage.ID).ToList();
                    foreach (var u_page in usualPages)
                    {
                        RefreshPageAndDependencies(db, u_page);
                    }
                    foreach (var c_page in categoryPages)
                    {
                        RefreshPageAndDependencies(db, c_page);
                    }
                }
                if (editedPage is CategoryPage)
                {
                    List <ProductPage> productPages = db.ProductPages.Where(p => p.PreviousPageID == editedPage.ID).ToList();
                    foreach (var p_page in productPages)
                    {
                        RefreshPageAndDependencies(db, p_page);
                    }
                }
            }
            db.SaveChanges();
            successfullyCompleted = true;

            LogManagementFunctions.AddAdminPanelLog(
                db: db,
                context: context,
                info: $"{editablePage.PageName} (ID-{editablePage.ID.ToString()}): " +
                (editablePage is UsualPage ? (context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.PageEdited
                : (context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.CategoryEdited)
                );
        }
Ejemplo n.º 21
0
        public static void AddChunk(CMSDatabase db, TemplateModel model, HttpContext context, out bool successfullyCompleted)
        {
            Chunk chunk = TemplatesManagementFunctions.TemplateModelToITemplate <Chunk>(model, context);

            if (chunk == null)
            {
                successfullyCompleted = false;
                return;
            }
            IHostingEnvironment env = context.RequestServices.GetService <IHostingEnvironment>();

            if (chunk.Name.Equals("_ViewImports", System.StringComparison.OrdinalIgnoreCase))
            {
                chunk.Name = "view_imports";
            }
            chunk.TemplatePath = env.GetChunksFolderShortPath();
            TemplatesManagementFunctions.SetUniqueITemplateName(db, chunk);
            chunk.TemplatePath += $"{chunk.Name}.cshtml";
            string cshtmlContent = TemplatesManagementFunctions.SourceToCSHTML(
                db: db,
                source: chunk.TemplateSource,
                modelType: "Page",
                env: env,
                skipChunkName: chunk.Name
                );

            TemplatesManagementFunctions.WriteCshtmlContentToFile(
                pathToTemplatesFolder: env.GetChunksFolderFullPath(),
                templateName: chunk.Name,
                chstmlContent: cshtmlContent
                );
            db.Chunks.Add(chunk);
            db.SaveChanges();
            model.ID = chunk.ID;
            successfullyCompleted = true;
            LogManagementFunctions.AddAdminPanelLog(
                db: db,
                context: context,
                info: $"{chunk.Name} (ID-{chunk.ID.ToString()}): {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.ChunkAdded}"
                );

            // Получаем список шаблонов и чанков, которые содержат данный чанк
            var templates = db.Templates.AsNoTracking().Where(t => t.TemplateSource.Contains($"[#{chunk.Name}]")).ToList();
            var chunks    = db.Chunks.AsNoTracking().Where(tc => tc.ID != chunk.ID && (tc.TemplateSource.Contains($"[#{chunk.Name}]"))).ToList();
            // Делаем рендер, содержащих данный чанк, шаблонов и чанков
            var renderTask = Task.Run(() =>
            {
                foreach (var t in templates)
                {
                    string _cshtmlContent = TemplatesManagementFunctions.SourceToCSHTML(
                        db: db,
                        source: t.TemplateSource,
                        modelType: "Page",
                        env: env,
                        skipChunkName: null
                        );
                    TemplatesManagementFunctions.WriteCshtmlContentToFile(env.GetTemplatesFolderFullPath(), t.Name, _cshtmlContent);
                }
            });

            foreach (var c in chunks)
            {
                string _cshtmlContent = TemplatesManagementFunctions.SourceToCSHTML(
                    db: db,
                    source: c.TemplateSource,
                    modelType: "Page",
                    env: env,
                    skipChunkName: c.Name
                    );
                TemplatesManagementFunctions.WriteCshtmlContentToFile(env.GetChunksFolderFullPath(), c.Name, _cshtmlContent);
            }

            // Если шаблон блока товара содержит текущий чанк, то делаем его перерендер
            string productBlockFileContent = OtherFunctions.GetFileContent(env.GetProductBlockTemplateFullPath());

            if (productBlockFileContent.Contains($"[#{chunk.Name}]"))
            {
                string[] additions =
                {
                    "@using Treynessen.Functions;",
                    "@using Treynessen.Database.Entities;",
                    "@addTagHelper Treynessen.TagHelpers.ImageTagHelper, StoreCMS"
                };
                string productBlockCshtmlTemplate = TemplatesManagementFunctions.SourceToCSHTML(
                    db: db,
                    source: productBlockFileContent,
                    modelType: "ProductPage",
                    env: env,
                    skipChunkName: null,
                    additions: additions
                    );
                using (StreamWriter writer = new StreamWriter(env.GetProductBlockCshtmlFullPath()))
                {
                    writer.Write(productBlockCshtmlTemplate);
                }
            }
            renderTask.Wait();
        }
Ejemplo n.º 22
0
        public static void DeletePage(CMSDatabase db, PageType?pageType, int?itemID, HttpContext context, out bool successfullyDeleted)
        {
            if (!pageType.HasValue || !itemID.HasValue)
            {
                successfullyDeleted = false;
                return;
            }
            Page page = null;

            switch (pageType)
            {
            case PageType.Usual:
                page = db.UsualPages.FirstOrDefault(p => p.ID == itemID);
                break;

            case PageType.Category:
                page = db.CategoryPages.FirstOrDefault(p => p.ID == itemID);
                break;

            default:
                successfullyDeleted = false;
                return;
            }
            if (page == null)
            {
                successfullyDeleted = false;
                return;
            }
            if (page is 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();
                db.UsualPages.Remove(up);
                db.SaveChanges();
                // Обновляем полученные зависимые страницы
                foreach (var u_page in usualPages)
                {
                    u_page.PreviousPageID = up.PreviousPageID;
                    RefreshPageAndDependencies(db, u_page);
                }
                foreach (var c_page in categoryPages)
                {
                    c_page.PreviousPageID = up.PreviousPageID;
                    RefreshPageAndDependencies(db, c_page);
                }
            }
            else if (page is CategoryPage cp)
            {
                IHostingEnvironment env = context.RequestServices.GetRequiredService <IHostingEnvironment>();
                cp.ProductPages = db.ProductPages.Where(pp => pp.PreviousPageID == cp.ID).ToList();
                foreach (var p in cp.ProductPages)
                {
                    string[] images = ImagesManagementFunctions.GetProductImageUrls(p, 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);
                        }
                    }
                    string pathToImages = $"{env.GetProductsImagesFolderFullPath()}{p.ID}/";
                    if (Directory.Exists(pathToImages))
                    {
                        Directory.Delete(pathToImages, true);
                    }
                }
                db.Remove(page);
            }
            db.SaveChanges();
            successfullyDeleted = true;

            LogManagementFunctions.AddAdminPanelLog(
                db: db,
                context: context,
                info: $"{page.PageName} (ID-{page.ID.ToString()}): " +
                (page is UsualPage ? (context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.PageDeleted
                : (context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.CategoryDeleted)
                );
        }
        public static void UploadProductImageToServer(CMSDatabase db, IFormFile file, int?itemID, HttpContext context, out bool successfullyUploaded)
        {
            successfullyUploaded = true;
            if (!itemID.HasValue || file == null)
            {
                successfullyUploaded = false;
                return;
            }
            ProductPage product = db.ProductPages.AsNoTracking().FirstOrDefault(pp => pp.ID == itemID);

            if (product == null)
            {
                successfullyUploaded = false;
                return;
            }
            IHostingEnvironment env = context.RequestServices.GetRequiredService <IHostingEnvironment>();
            string imagesPath       = $"{env.GetProductsImagesFolderFullPath()}{product.ID}/";

            Directory.CreateDirectory(imagesPath);
            string fullImageName = FileManagerManagementFunctions.GetUniqueFileOrFolderName(imagesPath, product.Alias, ".jpg");
            string pathToFile    = $"{imagesPath}{fullImageName}";

            using (Stream stream = file.OpenReadStream())
            {
                try
                {
                    using (Image <Rgba32> source = SixLabors.ImageSharp.Image.Load(stream))
                    {
                        // Если остались зависимости от предыдущего изображения, то удаляем их
                        DeleteDependentImages(imagesPath, fullImageName);
                        // Добавляем или изменяем информацию в БД
                        string shortPathToImage       = pathToFile.Substring(env.GetStorageFolderFullPath().Length).Insert(0, "/");
                        Database.Entities.Image image = db.Images.FirstOrDefault(img => img.ShortPathHash == OtherFunctions.GetHashFromString(shortPathToImage) &&
                                                                                 img.ShortPath.Equals(shortPathToImage, StringComparison.Ordinal));
                        if (image == null)
                        {
                            image = new Database.Entities.Image
                            {
                                ShortPath     = shortPathToImage,
                                ShortPathHash = OtherFunctions.GetHashFromString(shortPathToImage),
                                FullName      = shortPathToImage.Substring(shortPathToImage.LastIndexOf('/') + 1),
                                Width         = (uint)source.Width,
                                Height        = (uint)source.Height
                            };
                            db.Images.Add(image);
                        }
                        else // Если вдруг каким-то образом информация об изображении не была удалена из БД
                        {
                            image.Width  = (uint)source.Width;
                            image.Height = (uint)source.Height;
                        }
                        db.SaveChanges();
                        source.Save(pathToFile);
                        LogManagementFunctions.AddAdminPanelLog(
                            db: db,
                            context: context,
                            info: $"{product.PageName} (ID-{product.ID.ToString()}): {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.ProductImageUploaded}"
                            );
                    }
                }
                catch (NotSupportedException) { successfullyUploaded = false; }
            }
        }
Ejemplo n.º 24
0
        public static void EditTemplate(CMSDatabase db, int?itemID, TemplateModel model, HttpContext context, out bool successfullyCompleted)
        {
            if (!itemID.HasValue || model == null || string.IsNullOrEmpty(model.Name))
            {
                successfullyCompleted = false;
                return;
            }
            Template editableTemplate = db.Templates.AsNoTracking().FirstOrDefault(t => t.ID == itemID);

            if (editableTemplate == null)
            {
                successfullyCompleted = false;
                return;
            }
            Template editedTemplate = TemplatesManagementFunctions.TemplateModelToITemplate <Template>(model, context);

            if (editedTemplate == null)
            {
                successfullyCompleted = false;
                return;
            }
            if (editedTemplate.Name.Equals("_ViewImports", StringComparison.OrdinalIgnoreCase))
            {
                editedTemplate.Name = "view_imports";
            }
            IHostingEnvironment env = context.RequestServices.GetService <IHostingEnvironment>();

            editedTemplate.ID           = itemID.Value;
            editedTemplate.TemplatePath = env.GetTemplatesFolderShortPath();
            TemplatesManagementFunctions.SetUniqueITemplateName(db, editedTemplate);
            editedTemplate.TemplatePath += $"{editedTemplate.Name}.cshtml";
            db.Templates.Update(editedTemplate);
            db.SaveChanges();
            successfullyCompleted = true;
            LogManagementFunctions.AddAdminPanelLog(
                db: db,
                context: context,
                info: $"{editableTemplate.Name} (ID-{editableTemplate.ID.ToString()}): {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.TemplateEdited}"
                );

            // Изменяем cshtml файл, если изменилось имя шаблона и/или код шаблона
            bool changedName           = !editedTemplate.Name.Equals(editableTemplate.Name, StringComparison.Ordinal);
            bool changedTemplateSource = !editedTemplate.TemplateSource.Equals(editableTemplate.TemplateSource, StringComparison.InvariantCulture);

            if (changedName && changedTemplateSource)
            {
                string pathToOldFileName = $"{env.GetTemplatesFolderFullPath()}{editableTemplate.Name}.cshtml";
                if (File.Exists(pathToOldFileName))
                {
                    File.Delete(pathToOldFileName);
                }
                string cshtmlContent = TemplatesManagementFunctions.SourceToCSHTML(
                    db: db,
                    source: editedTemplate.TemplateSource,
                    modelType: "Page",
                    env: env,
                    skipChunkName: null
                    );
                TemplatesManagementFunctions.WriteCshtmlContentToFile(env.GetTemplatesFolderFullPath(), editedTemplate.Name, cshtmlContent);
            }
            else if (changedName)
            {
                string pathToOldFileName = $"{env.GetTemplatesFolderFullPath()}{editableTemplate.Name}.cshtml";
                if (File.Exists(pathToOldFileName))
                {
                    File.Move(pathToOldFileName, $"{env.GetTemplatesFolderFullPath()}{editedTemplate.Name}.cshtml");
                }
                else
                {
                    string cshtmlContent = TemplatesManagementFunctions.SourceToCSHTML(
                        db: db,
                        source: editedTemplate.TemplateSource,
                        modelType: "Page",
                        env: env,
                        skipChunkName: null
                        );
                    TemplatesManagementFunctions.WriteCshtmlContentToFile(env.GetTemplatesFolderFullPath(), editedTemplate.Name, cshtmlContent);
                }
            }
            else if (changedTemplateSource)
            {
                string cshtmlContent = TemplatesManagementFunctions.SourceToCSHTML(
                    db: db,
                    source: editedTemplate.TemplateSource,
                    modelType: "Page",
                    env: env,
                    skipChunkName: null
                    );
                TemplatesManagementFunctions.WriteCshtmlContentToFile(env.GetTemplatesFolderFullPath(), editedTemplate.Name, cshtmlContent);
            }
        }
Ejemplo n.º 25
0
        public static void DeleteChunk(CMSDatabase db, int?itemID, HttpContext context, out bool successfullyDeleted)
        {
            if (!itemID.HasValue)
            {
                successfullyDeleted = false;
                return;
            }
            Chunk chunk = db.Chunks.FirstOrDefault(t => t.ID == itemID);

            if (chunk == null)
            {
                successfullyDeleted = false;
                return;
            }
            IHostingEnvironment env = context.RequestServices.GetRequiredService <IHostingEnvironment>();
            string pathToChunkFile  = $"{env.GetChunksFolderFullPath()}{chunk.Name}.cshtml";

            if (File.Exists(pathToChunkFile))
            {
                File.Delete(pathToChunkFile);
            }
            db.Chunks.Remove(chunk);
            db.SaveChanges();
            successfullyDeleted = true;
            LogManagementFunctions.AddAdminPanelLog(
                db: db,
                context: context,
                info: $"{chunk.Name} (ID-{chunk.ID.ToString()}): {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.ChunkDeleted}"
                );

            // Получаем список чанков и шаблонов, использующих данный чанк и делаем перерендер
            var templates  = db.Templates.AsNoTracking().Where(t => t.TemplateSource.Contains($"[#{chunk.Name}]")).ToList();
            var chunks     = db.Chunks.AsNoTracking().Where(tc => tc.TemplateSource.Contains($"[#{chunk.Name}]")).ToList();
            var renderTask = Task.Run(() =>
            {
                foreach (var t in templates)
                {
                    string _cshtmlContent = TemplatesManagementFunctions.SourceToCSHTML(
                        db: db,
                        source: t.TemplateSource,
                        modelType: "Page",
                        env: env,
                        skipChunkName: null
                        );
                    TemplatesManagementFunctions.WriteCshtmlContentToFile(env.GetTemplatesFolderFullPath(), t.Name, _cshtmlContent);
                }
            });

            foreach (var c in chunks)
            {
                string _cshtmlContent = TemplatesManagementFunctions.SourceToCSHTML(
                    db: db,
                    source: c.TemplateSource,
                    modelType: "Page",
                    env: env,
                    skipChunkName: c.Name
                    );
                TemplatesManagementFunctions.WriteCshtmlContentToFile(env.GetChunksFolderFullPath(), c.Name, _cshtmlContent);
            }

            string productBlockFileContent = OtherFunctions.GetFileContent(env.GetProductBlockTemplateFullPath());

            if (productBlockFileContent.Contains($"[#{chunk.Name}]"))
            {
                string[] additions =
                {
                    "@using Treynessen.Functions;",
                    "@using Treynessen.Database.Entities;",
                    "@addTagHelper Treynessen.TagHelpers.ImageTagHelper, StoreCMS"
                };
                string productBlockCshtmlTemplate = TemplatesManagementFunctions.SourceToCSHTML(
                    db: db,
                    source: productBlockFileContent,
                    modelType: "ProductPage",
                    env: env,
                    skipChunkName: null,
                    additions: additions
                    );
                using (StreamWriter writer = new StreamWriter(env.GetProductBlockCshtmlFullPath()))
                {
                    writer.Write(productBlockCshtmlTemplate);
                }
            }

            renderTask.Wait();
        }
Ejemplo n.º 26
0
        public static void EditProduct(CMSDatabase db, PageModel model, int?productID, HttpContext context, out bool successfullyCompleted)
        {
            if (model == null || !productID.HasValue)
            {
                successfullyCompleted = false;
                return;
            }
            model.PageType = PageType.Product;
            ProductPage editableProduct = db.ProductPages.AsNoTracking().FirstOrDefault(pp => pp.ID == productID.Value);

            if (editableProduct == null)
            {
                successfullyCompleted = false;
                return;
            }
            model.ID             = editableProduct.ID;
            model.PreviousPageID = editableProduct.PreviousPageID;
            ProductPage editedProduct = PagesManagementFunctions.PageModelToPage(db, model, context) as ProductPage;

            if (editedProduct == null)
            {
                successfullyCompleted = false;
                return;
            }
            editedProduct.PreviousPage.LastProductTemplate = editedProduct.Template;
            db.ProductPages.Update(editedProduct);
            db.SaveChanges();

            // Изменяем имена изображений продукта, если изменился псевдоним страницы
            if (!editableProduct.Alias.Equals(editedProduct.Alias, StringComparison.Ordinal))
            {
                IHostingEnvironment env = context.RequestServices.GetRequiredService <IHostingEnvironment>();
                string pathToImages     = $"{env.GetProductsImagesFolderFullPath()}{editedProduct.ID}/";
                if (Directory.Exists(pathToImages))
                {
                    string   oldName        = editableProduct.Alias;
                    string   newName        = editedProduct.Alias;
                    Regex    imageChecker   = new Regex($"{oldName}(_\\d+)?.jpg$");
                    string[] oldImagesNames = Directory.GetFiles(pathToImages, $"*{oldName}*.jpg");
                    string[] imagePaths     = (from img in oldImagesNames
                                               where imageChecker.IsMatch(img)
                                               select img).ToArray();
                    // Можно было бы заменить разом имена всем изображениям через перебор в цикле, но
                    // проблема в том, что путь до папки с изображениями может содержать старое название
                    // изображения. В итоге замена имени через File.Move(старый_путь, старый_путь.Replace(oldName, newName))
                    // может привести к переносу изображений в другую директорию.
                    LinkedList <KeyValuePair <string, string> > renameErrors = new LinkedList <KeyValuePair <string, string> >();
                    for (int i = 0; i < imagePaths.Length; ++i)
                    {
                        string oldImageName = imagePaths[i].Substring(pathToImages.Length, imagePaths[i].Length - pathToImages.Length - 4);
                        string newImageName = oldImageName.Replace(oldName, newName);
                        try
                        {
                            ImagesManagementFunctions.RenameImageAndDependencies(
                                db: db,
                                env: env,
                                pathToImages: pathToImages,
                                oldImageName: oldImageName,
                                newImageName: newImageName,
                                imageExtension: ".jpg",
                                saveChangesInDB: false
                                );
                        }
                        catch (IOException)
                        {
                            // Добавляем все ошибки переименования в список для второй попытки. Например, старое название было
                            // "Название" и мы переименовали страницу на "Название_2", но у товара было несколько картинок,
                            // соответственно при ренейминге будет попытка присвоить первой картинке название Название_2, что приведет
                            // к ошибке, т.к. картинка с таким названием уже существует. Поэтому после первого прохода сделаем второй,
                            // что поможет избежать этих ошибок переименования
                            renameErrors.AddLast(new KeyValuePair <string, string>(oldImageName, newImageName));
                        }
                    }
                    if (renameErrors.Count > 0)
                    {
                        foreach (var e in renameErrors)
                        {
                            ImagesManagementFunctions.RenameImageAndDependencies(
                                db: db,
                                env: env,
                                pathToImages: pathToImages,
                                oldImageName: e.Key,
                                newImageName: e.Value,
                                imageExtension: ".jpg",
                                saveChangesInDB: false
                                );
                        }
                    }
                    db.SaveChanges();
                }
            }
            successfullyCompleted = true;

            LogManagementFunctions.AddAdminPanelLog(
                db: db,
                context: context,
                info: $"{editableProduct.PageName} (ID-{editableProduct.ID.ToString()}): {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.ProductEdited}"
                );
        }