public ActionResult Show(string path)
        {
            var m = new StaticView();
            m.Path = path;

            return View("Show", m);
        }
Example #2
0
        public async Task <IActionResult> RemoveView(int Id)
        {
            StaticView view = db.StaticViews.FirstOrDefault(x => x.Id == Id);

            if (view == null)
            {
                HttpContext.Items["ErrorMessage"] = "Данная статическая страница не найдена.";
                return(RedirectToAction("Index"));
            }

            _logger.LogDebug("RemoveView action started! Try to remove static view = {@view}", view);

            FileInfo file = new FileInfo(view.Path);

            if (file.Exists)
            {
                file.Delete();
            }

            db.StaticViews.Remove(view);
            await db.SaveChangesAsync();

            _logger.LogDebug("Successfully remove static view");

            HttpContext.Items["SuccessMessage"] = "Статическая страница успешно удалена.";
            return(RedirectToAction("Index"));
        }
Example #3
0
        public ActionResult Show(string path)
        {
            var m = new StaticView();

            m.Path = path;

            return(View("Show", m));
        }
Example #4
0
        public async Task <IActionResult> GetView(string route)
        {
            if (route[0] == '/')
            {
                route.Remove(0, 1);
            }

            StaticView view = await db.StaticViews.FirstOrDefaultAsync(x => x.Route == route);

            if (view == null)
            {
                _logger.LogWarning("Not found static page with route = {route}", route);
                return(NotFound("Страница не найдена."));
            }


            return(View(viewName: view.Path));
        }
Example #5
0
        public async Task <IActionResult> Create(CreateStaticViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            string routeEnd = model.Route.Split('/').Last();

            if (string.IsNullOrWhiteSpace(routeEnd))
            {
                ModelState.AddModelError("Route", "Не указано имя файла. (Имя файла = последнее слово маршрута не считая \"/\").");
                return(View(model));
            }

            FileInfo staticView = new FileInfo(_environment.ContentRootPath + $"/Generic/{model.Route}.cshtml");

            if (staticView.Exists)
            {
                ModelState.AddModelError("Route", "Данный файл уже существует.");
                return(View(model));
            }

            _logger.LogDebug("Create static view method started with model = {@model}", model);

            _logger.LogDebug("Calculate path");
            string[] dirs = model.Route.Split('/');
            if (dirs.Length > 1)
            {
                string fullPath = _environment.ContentRootPath + "/Generic/";
                for (int i = 0; i < dirs.Length - 1; i++)
                {
                    fullPath += (dirs[i] + "/");
                    if (!Directory.Exists(fullPath))
                    {
                        Directory.CreateDirectory(fullPath);
                    }
                }
                _logger.LogTrace("Path of new view = {fullpath}", fullPath);
            }


            if (WriteToFile(model.Content, staticView.FullName))
            {
                StaticView view = new StaticView
                {
                    Name  = model.Name,
                    Route = model.Route,
                    Path  = $"/Generic/{model.Route}.cshtml"
                };

                _logger.LogDebug("Try to create static page with params = {@view}", view);
                await db.StaticViews.AddAsync(view);

                await db.SaveChangesAsync();

                _logger.LogDebug("Create static view action success!");
                HttpContext.Items["SuccessMessage"] = "Создание статической страницы успешно завершено!";
            }
            else
            {
                HttpContext.Items["ErrorMessage"] = "Не удалось создать файл статической страницы, проверьте ваши права доступа";
            }

            return(RedirectToAction("Index"));
        }
Example #6
0
        public async Task <IActionResult> Edit(EditStaticViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            string routeEnd = model.Route.Split('/').Last();

            if (string.IsNullOrWhiteSpace(routeEnd))
            {
                ModelState.AddModelError("Route", "Не указано имя файла. (Имя файла = последнее слово маршрута не считая \"/\").");
                return(View(model));
            }

            StaticView view = db.StaticViews.FirstOrDefault(x => x.Id == model.Id);

            if (view == null)
            {
                _logger.LogDebug("Cannot find static view with id = {id}", model.Id);
                HttpContext.Items["ErrorMessage"] = "Указанная, для редактирования, статическая страница не найдена";
                return(RedirectToAction("Index"));
            }

            _logger.LogDebug("Edit static view action started with model = {@model}", model);

            _logger.LogDebug("Check new file location");
            FileInfo staticView = new FileInfo(_environment.ContentRootPath + $"/Generic/{model.Route}.cshtml");

            if (view.Path != $"/Generic/{model.Route}.html")
            {
                if (staticView.Exists)
                {
                    ModelState.AddModelError("Route", "Данный файл уже существует и не может быть переписан");
                    return(View(model));
                }

                _logger.LogDebug("Old and new location doesn't match. Create new file");
                string[] dirs = model.Route.Split('/');
                if (dirs.Length > 1)
                {
                    string fullPath = _environment.ContentRootPath + "/Generic/";
                    for (int i = 0; i < dirs.Length - 1; i++)
                    {
                        fullPath += (dirs[i] + "/");
                        if (!Directory.Exists(fullPath))
                        {
                            Directory.CreateDirectory(fullPath);
                        }
                    }
                }

                staticView.Create();

                _logger.LogDebug("Delete old file");
                FileInfo oldView = new FileInfo(view.Path);
                if (oldView.Exists)
                {
                    oldView.Delete();
                }
            }


            _logger.LogDebug("Try to write new content to the file");
            if (WriteToFile(model.Content, staticView.FullName))
            {
                view.Name  = model.Name;
                view.Path  = $"/Generic/{model.Route}.cshtml";
                view.Route = model.Route;
                _logger.LogDebug("Success writing to file. Update the view");
                db.StaticViews.Update(view);
                await db.SaveChangesAsync();

                _logger.LogDebug("Successfull update the static view");
                HttpContext.Items["SuccessMessage"] = "Обновление статичной страницы успешно!";
            }
            else
            {
                HttpContext.Items["ErrorMessage"] = "Не удалось создать файл статической страницы, проверьте ваши права доступа";
            }

            return(RedirectToAction("Index"));
        }