コード例 #1
0
ファイル: DeleteUser.cs プロジェクト: Treynessen/StoreCMS
        public static void DeleteUser(CMSDatabase db, int?userID, HttpContext context, out int statusCode)
        {
            if (!userID.HasValue || userID.Value == 1)
            {
                statusCode = 404;
                return;
            }
            User user = db.Users.FirstOrDefault(u => u.ID == userID.Value);

            if (user == null)
            {
                statusCode = 404;
                return;
            }
            if (user == context.Items["User"])
            {
                context.Items["User"] = null;
            }
            db.Remove(user);
            db.SaveChanges();
            statusCode = 200;

            LogManagementFunctions.AddAdminPanelLog(
                db: db,
                context: context,
                info: $"{user.Login} (ID-{user.ID.ToString()}): {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.UserDeleted}"
                );
        }
コード例 #2
0
ファイル: EditUserType.cs プロジェクト: Treynessen/StoreCMS
        public static void EditUserType(CMSDatabase db, int?itemID, UserTypeModel model, HttpContext context, out bool successfullyCompleted)
        {
            if (string.IsNullOrEmpty(model.Name) || !model.AccessLevel.HasValue || !itemID.HasValue || !Enum.IsDefined(typeof(AccessLevel), model.AccessLevel.Value))
            {
                successfullyCompleted = false;
                return;
            }
            UserType userType = db.UserTypes.FirstOrDefault(ut => ut.ID == itemID.Value);

            if (userType == null || (userType.ID == 1 && model.AccessLevel.Value != userType.AccessLevel))
            {
                successfullyCompleted = false;
                return;
            }
            string      oldName        = userType.Name;
            AccessLevel oldAccessLevel = userType.AccessLevel;

            userType.Name        = model.Name;
            userType.AccessLevel = model.AccessLevel.Value;
            db.SaveChanges();
            successfullyCompleted = true;

            LogManagementFunctions.AddAdminPanelLog(
                db: db,
                context: context,
                info: $"{oldName} ({oldAccessLevel.ToString()}) -> {userType.Name} ({userType.AccessLevel.ToString()}): {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.UserTypeEdited}"
                );
        }
コード例 #3
0
        public static void DeleteRedirection(CMSDatabase db, int?itemID, HttpContext context, out bool successfullyCompleted)
        {
            if (itemID.HasValue)
            {
                Redirection redirection = db.Redirections.FirstOrDefault(r => r.ID == itemID);
                if (redirection == null)
                {
                    successfullyCompleted = false;
                    return;
                }
                db.Remove(redirection);
                db.SaveChanges();
                successfullyCompleted = true;

                LogManagementFunctions.AddAdminPanelLog(
                    db: db,
                    context: context,
                    info: $"{redirection.RequestPath} -> {redirection.RedirectionPath}: {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.RedirectionDeleted}"
                    );
            }
            else
            {
                successfullyCompleted = false;
            }
        }
コード例 #4
0
        public static void EditSynonymForString(CMSDatabase db, int?itemID, SynonymForStringModel model, HttpContext context, out bool successfullyCompleted)
        {
            if (itemID.HasValue && !string.IsNullOrEmpty(model.String) && !string.IsNullOrEmpty(model.Synonym) && !model.String.Equals(model.Synonym, StringComparison.InvariantCultureIgnoreCase))
            {
                SynonymForString match = db.SynonymsForStrings.AsNoTracking()
                                         .FirstOrDefault(s => s.ID != itemID.Value &&
                                                         (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 = db.SynonymsForStrings.FirstOrDefault(s => s.ID == itemID);
                string           oldString        = synonymForString.String;
                string           oldSynonym       = synonymForString.Synonym;
                synonymForString.String  = model.String;
                synonymForString.Synonym = model.Synonym;
                db.SaveChanges();
                successfullyCompleted = true;

                LogManagementFunctions.AddAdminPanelLog(
                    db: db,
                    context: context,
                    info: $"{synonymForString.String} -> {synonymForString.Synonym}: " +
                    $"{(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.SynonymForStringEditedTo} {oldString} -> {oldSynonym}"
                    );
            }
            else
            {
                successfullyCompleted = false;
            }
        }
コード例 #5
0
ファイル: DeleteUserType.cs プロジェクト: Treynessen/StoreCMS
        public static void DeleteUserType(CMSDatabase db, int?itemID, HttpContext context, out bool successfullyCompleted)
        {
            if (!itemID.HasValue || itemID.Value == 1)
            {
                successfullyCompleted = false;
                return;
            }
            UserType userType = db.UserTypes.FirstOrDefault(ut => ut.ID == itemID.Value);

            if (userType == null)
            {
                successfullyCompleted = false;
                return;
            }
            if (userType == (context.Items["User"] as User).UserType)
            {
                context.Items["User"] = null;
            }
            db.UserTypes.Remove(userType);
            db.SaveChanges();
            successfullyCompleted = true;

            LogManagementFunctions.AddAdminPanelLog(
                db: db,
                context: context,
                info: $"{userType.Name} ({userType.AccessLevel.ToString()}): {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.UserTypeDeleted}"
                );
        }
コード例 #6
0
        public static void EditUser(CMSDatabase db, int?userID, UserModel model, HttpContext context, out int statusCode)
        {
            if (!userID.HasValue || !model.UserTypeId.HasValue ||
                db.UserTypes.AsNoTracking().FirstOrDefault(ut => ut.ID == model.UserTypeId.Value) == null
                )
            {
                statusCode = 422;
                return;
            }
            if (userID.Value == 1)
            {
                statusCode = 200;
                return;
            }
            User editableUser = db.Users.FirstOrDefault(u => u.ID == userID.Value);

            if (editableUser == null)
            {
                statusCode = 404;
                return;
            }
            editableUser.UserTypeID = model.UserTypeId.Value;
            db.SaveChanges();
            statusCode = 200;

            LogManagementFunctions.AddAdminPanelLog(
                db: db,
                context: context,
                info: $"{editableUser.Login} (ID-{editableUser.ID.ToString()}): {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.UserEdited}"
                );
        }
コード例 #7
0
        public static void DeleteSynonymForString(CMSDatabase db, int?itemID, HttpContext context, out bool successfullyCompleted)
        {
            if (itemID.HasValue)
            {
                SynonymForString synonymForString = db.SynonymsForStrings.FirstOrDefault(s => s.ID == itemID);
                if (synonymForString == null)
                {
                    successfullyCompleted = false;
                    return;
                }
                db.Remove(synonymForString);
                db.SaveChanges();
                successfullyCompleted = true;

                LogManagementFunctions.AddAdminPanelLog(
                    db: db,
                    context: context,
                    info: $"{synonymForString.String} -> {synonymForString.Synonym}: {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.SynonymForStringDeleted}"
                    );
            }
            else
            {
                successfullyCompleted = false;
            }
        }
コード例 #8
0
        public static void AddProduct(CMSDatabase db, PageModel model, int?previousPageID, HttpContext context, out bool successfullyCompleted)
        {
            if (model == null)
            {
                successfullyCompleted = false;
                return;
            }
            model.PageType       = PageType.Product;
            model.PreviousPageID = previousPageID;
            ProductPage productPage = PagesManagementFunctions.PageModelToPage(db, model, context) as ProductPage;

            if (productPage == null)
            {
                successfullyCompleted = false;
                return;
            }
            ++productPage.PreviousPage.ProductsCount;
            productPage.PreviousPage.LastProductTemplate = productPage.Template;
            db.ProductPages.Add(productPage);
            db.SaveChanges();
            model.ID = productPage.ID;
            successfullyCompleted = true;

            LogManagementFunctions.AddAdminPanelLog(
                db: db,
                context: context,
                info: $"{productPage.PageName} (ID-{productPage.ID.ToString()}): {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.ProductAdded}"
                );
        }
コード例 #9
0
        public static void EditScriptFile(CMSDatabase db, string path, StyleModel model, HttpContext context, out string redirectPath, out bool successfullyCompleted)
        {
            Regex regex = new Regex(@"^((\w|-|_)+)(>(\w|-|_)+)*\.js$");

            if (!regex.IsMatch(path))
            {
                successfullyCompleted = false;
                redirectPath          = string.Empty;
                return;
            }
            IHostingEnvironment env   = context.RequestServices.GetService <IHostingEnvironment>();
            string scriptFileFullName = path.Substring(path.LastIndexOf('>') + 1);

            path = path.Substring(0, path.Length - scriptFileFullName.Length);
            if (!string.IsNullOrEmpty(path))
            {
                path = path.Replace('>', '/');
                if (!path[path.Length - 1].Equals('/'))
                {
                    path = path.Insert(path.Length, "/");
                }
            }
            path = $"{env.GetStorageFolderFullPath()}{path}";
            string pathToFile = path + scriptFileFullName;

            if (!File.Exists(pathToFile) || !HasAccessToFolder(path, env))
            {
                successfullyCompleted = false;
                redirectPath          = string.Empty;
                return;
            }
            model.FileName = OtherFunctions.GetCorrectName(model.FileName, context);
            if (string.IsNullOrEmpty(model.FileName))
            {
                successfullyCompleted = false;
                redirectPath          = string.Empty;
                return;
            }
            string oldScriptFileName  = scriptFileFullName.Substring(0, scriptFileFullName.Length - 3);
            string scriptFileFullPath = $"{path}{model.FileName}.js";

            if (!oldScriptFileName.Equals(model.FileName, StringComparison.Ordinal))
            {
                File.Move($"{pathToFile}", scriptFileFullPath);
            }
            using (StreamWriter writer = new StreamWriter(scriptFileFullPath))
            {
                writer.Write(model.FileContent);
            }
            successfullyCompleted = true;
            redirectPath          = scriptFileFullPath.Substring(env.GetStorageFolderFullPath().Length).Replace('/', '>');

            LogManagementFunctions.AddAdminPanelLog(
                db: db,
                context: context,
                info: $"{pathToFile.Substring(env.GetStorageFolderFullPath().Length - 1)}{(!oldScriptFileName.Equals(model.FileName, StringComparison.Ordinal) ? $" -> {scriptFileFullPath.Substring(env.GetStorageFolderFullPath().Length - 1)}" : string.Empty)}: " +
                $"{(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.FileEdited}"
                );
        }
コード例 #10
0
ファイル: DeleteTemplate.cs プロジェクト: Treynessen/StoreCMS
        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}"
                );
        }
コード例 #11
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);
        }
コード例 #12
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}"
                );
        }
コード例 #13
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}"
                );
        }
コード例 #14
0
ファイル: CreateFolder.cs プロジェクト: Treynessen/StoreCMS
        public static void CreateFolder(CMSDatabase db, string path, string folderName, HttpContext context, out bool successfullyCreated)
        {
            IHostingEnvironment env = context.RequestServices.GetService <IHostingEnvironment>();

            if (string.IsNullOrEmpty(path))
            {
                path = env.GetStorageFolderFullPath();
            }
            else
            {
                Regex regex = new Regex(@"^((\w|-|_)+)(>(\w|-|_)+)*$");
                if (!regex.IsMatch(path))
                {
                    successfullyCreated = false;
                    return;
                }
                path = path.Replace('>', '/');
                if (!path[path.Length - 1].Equals('/'))
                {
                    path = path.Insert(path.Length, "/");
                }
                path = $"{env.GetStorageFolderFullPath()}{path}";
            }
            if (!Directory.Exists(path) || !HasAccessToFolder(path, env))
            {
                successfullyCreated = false;
                return;
            }
            folderName = OtherFunctions.GetCorrectName(folderName, context);
            if (string.IsNullOrEmpty(folderName))
            {
                successfullyCreated = false;
                return;
            }
            folderName = GetUniqueFileOrFolderName(path, folderName);
            Directory.CreateDirectory($"{path}{folderName}");
            successfullyCreated = true;

            LogManagementFunctions.AddAdminPanelLog(
                db: db,
                context: context,
                info: $"{folderName}: {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.FolderCreatedIn} {path.Substring(env.GetStorageFolderFullPath().Length - 1)}"
                );
        }
コード例 #15
0
        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}"
                );
        }
コード例 #16
0
ファイル: EditSettings.cs プロジェクト: Treynessen/StoreCMS
        public IActionResult EditSettings(CMSDatabase db, SettingsModel model, HttpContext context)
        {
            ConfigurationHandler configurationHandler = context.RequestServices.GetRequiredService <ConfigurationHandler>();

            configurationHandler.ChangeConfigFile(model);
            if (!string.IsNullOrEmpty(model.ProductBlockTemplate))
            {
                IHostingEnvironment env = context.RequestServices.GetRequiredService <IHostingEnvironment>();
                string pathToTemplate   = env.GetProductBlockTemplateFullPath();
                string oldTemplate      = OtherFunctions.GetFileContent(pathToTemplate);
                if (!model.ProductBlockTemplate.Equals(oldTemplate, StringComparison.Ordinal))
                {
                    using (StreamWriter writer = new StreamWriter(pathToTemplate))
                    {
                        writer.Write(model.ProductBlockTemplate);
                    }
                    string[] additions =
                    {
                        "@using Treynessen.Functions;",
                        "@using Treynessen.Database.Entities;",
                        "@addTagHelper Treynessen.TagHelpers.ImageTagHelper, StoreCMS"
                    };
                    string cshtmlTemplate = TemplatesManagementFunctions.SourceToCSHTML(
                        db: db,
                        source: model.ProductBlockTemplate,
                        modelType: "ProductPage",
                        env: env,
                        skipChunkName: null,
                        additions: additions
                        );
                    using (StreamWriter writer = new StreamWriter(env.GetProductBlockCshtmlFullPath()))
                    {
                        writer.Write(cshtmlTemplate);
                    }
                }
            }
            LogManagementFunctions.AddAdminPanelLog(
                db: db,
                context: context,
                info: (context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.SettingsEdited
                );
            return(StatusCode(200));
        }
コード例 #17
0
ファイル: AddTemplate.cs プロジェクト: Treynessen/StoreCMS
        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}"
                );
        }
コード例 #18
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;
            }
        }
コード例 #19
0
ファイル: AddPage.cs プロジェクト: Treynessen/StoreCMS
        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)
                );
        }
コード例 #20
0
ファイル: AddUser.cs プロジェクト: Treynessen/StoreCMS
        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}"
                );
        }
コード例 #21
0
ファイル: AddUserType.cs プロジェクト: Treynessen/StoreCMS
        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}"
                );
        }
コード例 #22
0
 public static bool IsValidLoginFormData(CMSDatabase db, LoginFormModel data, HttpContext context, out User user)
 {
     if (string.IsNullOrEmpty(data.Login) || string.IsNullOrEmpty(data.Password))
     {
         user = null;
         return(false);
     }
     user = db.Users.FirstOrDefault(u => u.Login.Equals(data.Login, StringComparison.Ordinal));
     if (user == null)
     {
         return(false);
     }
     if (!user.Password.Equals(GetPasswordHash(data.Password), StringComparison.Ordinal))
     {
         LogManagementFunctions.AddAdminPanelLog(
             db: db,
             context: context,
             info: $"{(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.FailedLoginAttempt}. IP: {context.Connection.RemoteIpAddress.ToString()}",
             user: user
             );
         return(false);
     }
     return(true);
 }
コード例 #23
0
ファイル: DeletePage.cs プロジェクト: Treynessen/StoreCMS
        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)
                );
        }
コード例 #24
0
ファイル: EditTemplate.cs プロジェクト: Treynessen/StoreCMS
        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);
            }
        }
コード例 #25
0
ファイル: EditProduct.cs プロジェクト: Treynessen/StoreCMS
        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}"
                );
        }
コード例 #26
0
ファイル: EditChunk.cs プロジェクト: Treynessen/StoreCMS
        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();
            }
        }
コード例 #27
0
        public static void UploadFileToServer(CMSDatabase db, string path, IFormFile file, HttpContext context, out bool successfulUpload)
        {
            IHostingEnvironment env = context.RequestServices.GetService <IHostingEnvironment>();

            if (string.IsNullOrEmpty(path))
            {
                path = env.GetStorageFolderFullPath();
            }
            else
            {
                Regex regex = new Regex(@"^((\w|-|_)+)(>(\w|-|_)+)*$");
                if (!regex.IsMatch(path))
                {
                    successfulUpload = false;
                    return;
                }
                path = path.Replace('>', '/');
                if (!path[path.Length - 1].Equals('/'))
                {
                    path = path.Insert(path.Length, "/");
                }
                path = $"{env.GetStorageFolderFullPath()}{path}";
            }
            if (!Directory.Exists(path) || !HasAccessToFolder(path, env))
            {
                successfulUpload = false;
                return;
            }
            int pointIndex = file.FileName.LastIndexOf('.');

            if (pointIndex == -1)
            {
                successfulUpload = false;
                return;
            }
            string fileExtension       = file.FileName.Substring(pointIndex).ToLower();
            bool   itsCorrectExtension = false;

            foreach (var typeOfExtension in typesOfExtensions)
            {
                if (fileExtension.Equals(typeOfExtension.Key, StringComparison.Ordinal))
                {
                    itsCorrectExtension = true;
                    break;
                }
            }
            if (!itsCorrectExtension)
            {
                successfulUpload = false;
                return;
            }
            string fileName = file.FileName.Substring(0, pointIndex);

            fileName = OtherFunctions.GetCorrectName(fileName, context);
            if (string.IsNullOrEmpty(fileName))
            {
                fileName = "uploaded_file";
            }
            fileName = GetUniqueFileOrFolderName(path, fileName, fileExtension);
            using (FileStream fs = new FileStream($"{path}{fileName}", FileMode.Create))
            {
                file.CopyTo(fs);
            }
            successfulUpload = true;

            LogManagementFunctions.AddAdminPanelLog(
                db: db,
                context: context,
                info: $"{fileName}: {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.FileUploadedTo} {path.Substring(env.GetStorageFolderFullPath().Length - 1)}"
                );
        }
コード例 #28
0
ファイル: AddChunk.cs プロジェクト: Treynessen/StoreCMS
        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();
        }
コード例 #29
0
ファイル: DeleteChunk.cs プロジェクト: Treynessen/StoreCMS
        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();
        }
コード例 #30
0
        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; }
            }
        }