/// <summary> /// Read a content. /// </summary> /// <param name="contentId">Id of a content to read.</param> /// <returns>Content representation.</returns> public ContentEditViewModel Read(int contentId) { GuardNotDisposed(); var content = _dataDbContext.Content.Include(c => c.Translations).FirstOrDefault(x => x.Id == contentId); if (content != null) { var vm = new ContentEditViewModel(content); // Build missing translations var missingTranslations = from x in Enum.GetValues(typeof(LanguageDefinition)).Cast <LanguageDefinition>() where !vm.Translations.Select(t => t.Version).Contains(x) select new TranslationEditViewModel(new Translation()) { ContentId = vm.Id, Version = x }; vm.Translations = vm.Translations.Concat(missingTranslations).ToList(); return(vm); } else { return(null); } }
public ActionResult Preview(ContentEditViewModel editModel) { Content content = null; if (editModel.ContentId != null) { content = _entities.Contents .Include(c => c.Urls) .FirstOrDefault(c => c.Id == editModel.ContentId); } if (content == null) { content = new Content(); } editModel.UpdateContent(content); content.CompileLess(); content.Parse(); var model = new ContentPreviewViewModel { Title = content.Title, ContentId = editModel.ContentId ?? 0, Contents = content.ParsedContent, Stylesheet = content.StylesheetCss, Teaser = content.Teaser }; return View("~/Areas/mitarbeit/Views/Content/Preview.cshtml", model); }
public async Task <IActionResult> Edit(int cid, int type) { var VM = new ContentEditViewModel(); VM.Type = type; VM.content = new Project3.Data.Models.Contents(); VM.selectedmetas = new List <Project3.Data.Models.Metas>(); if (cid > 0) { VM.content = await cms.GetByCidAsync(cid); VM.selectedmetas = await cms.GetMetasAsync(cid); VM.files = await fms.GetFilesByCidAsync(cid); VM.Type = VM.content.type; } else { VM.files = await fms.GetFilesAsync(); } VM.metas = await mms.GetMetasAsync(-1); return(View(VM)); }
public ActionResult Edit(int id) { var model = db.contents.Find(id); if (model == null) { return(HttpNotFound()); } var viewModel = new ContentEditViewModel(); viewModel.ContentId = model.ContentId; viewModel.PageId = model.PageId; viewModel.Title = model.Title; viewModel.Subtitle = model.Subtitle; viewModel.ImageUrl = model.ImageUrl; viewModel.Content = model.Content1; viewModel.IsPublished = model.IsPublished ? "A" : "I"; var pages = db.pages.Select(x => new { Text = x.PageName, Value = x.PageId }).ToList(); pages.Insert(0, null); ViewBag.PageId = new SelectList(pages, "Value", "Text", viewModel.PageId); return(View(viewModel)); }
public ActionResult Contact() { ViewBag.Title = "Kontakt"; var viewModel = new ContentEditViewModel { IsUserAuthenticated = Session["UserCredentials"] != null, Content = _context.SiteContents.First(siteContent => siteContent.SiteContentId == 1).Content }; return(View(viewModel)); }
public void ReturnsContentEditor(ContentEditViewModel content, Type expectedResultType) { var fakeId = -1; var fakeContentRepository = new Mock <IContentEditorRepository>(); fakeContentRepository.Setup(x => x.Read(fakeId)).Returns(content); var subject = new ContentsController(fakeContentRepository.Object); var actionResult = subject.Edit(fakeId); Assert.IsType(expectedResultType, actionResult); }
public IActionResult Create(ContentEditViewModel content) { if (ModelState.IsValid) { using (_contentEditorRepository) { _contentEditorRepository.Create(content); } return(RedirectToAction(nameof(Index))); } return(View(content)); }
public void CreatesContent() { var fakeContent = new ContentEditViewModel(); var fakeContentRepository = new Mock <IContentEditorRepository>(); fakeContentRepository.Setup(x => x.Create(fakeContent)).Returns(fakeContent); var subject = new ContentsController(fakeContentRepository.Object); var actionResult = subject.Create(fakeContent); fakeContentRepository.Verify(x => x.Create(fakeContent)); Assert.IsType(typeof(RedirectToActionResult), actionResult); }
public IActionResult Edit(ContentEditViewModel content) { if (ModelState.IsValid) { using (_contentEditorRepository) { _contentEditorRepository.Update(content); } return(RedirectToAction(nameof(Edit), new { id = content.Id })); } return(View(content)); }
public void ConfirmsContentRemoval() { var fakeContent = new ContentEditViewModel { Id = -1 }; var fakeContentRepository = new Mock <IContentEditorRepository>(); fakeContentRepository.Setup(x => x.Read(fakeContent.Id)).Returns(fakeContent); var subject = new ContentsController(fakeContentRepository.Object); var actionResult = subject.Delete(fakeContent.Id); Assert.IsType(typeof(ViewResult), actionResult); }
public void DeletesContent() { var fakeContent = new ContentEditViewModel { Id = -1 }; var fakeContentRepository = new Mock <IContentEditorRepository>(); fakeContentRepository.Setup(x => x.Delete(fakeContent.Id)); var subject = new ContentsController(fakeContentRepository.Object); var actionResult = subject.DeleteConfirmed(fakeContent.Id); Assert.IsType(typeof(RedirectToActionResult), actionResult); }
public ActionResult ContactEditMode() { if (Session["UserCredentials"] == null) { return(RedirectToAction("Contact")); } ViewBag.Title = "Edycja zakładki kontakt"; var viewModel = new ContentEditViewModel { Content = _context.SiteContents.First(siteContent => siteContent.SiteContentId == 1).Content }; return(View(viewModel)); }
/// <summary> /// Create <see cref="ContentEditViewModel"/> representation in DB. /// </summary> /// <param name="contentEditViewModel">Content representation to store in DB.</param> /// <returns>Updated content representation.</returns> public ContentEditViewModel Create(ContentEditViewModel contentEditViewModel) { GuardNotDisposed(); var content = _dataDbContext.Content.Add(new Content { InternalCaption = contentEditViewModel.InternalCaption }); _dataDbContext.SaveChanges(); var entity = content.Entity; return(new ContentEditViewModel(entity)); }
public ContentEditViewModel GetEdit(ApiCall call) { Guid FolderId = GetFolderId(call); if (FolderId == default(Guid)) { return(null); } ContentEditViewModel model = new ContentEditViewModel(); model.FolderId = FolderId; model.Properties = GetProperties(call, FolderId).OrderBy(o => o.Order).ToList(); model.Categories = GetCategoryInfo(call, FolderId, call.ObjectId, call.Context.Culture); model.Embedded = Sites.Helper.ContentHelper.GetEmbedContents(call.WebSite.SiteDb(), FolderId, call.ObjectId, call.Context.Culture); return(model); }
/// <summary> /// Update a content. /// </summary> /// <param name="contentEditViewModel">Content to update.</param> /// <returns>Updated content.</returns> public ContentEditViewModel Update(ContentEditViewModel contentEditViewModel) { GuardNotDisposed(); var content = _dataDbContext.Content.Include(c => c.Translations) .Single(x => x.Id == contentEditViewModel.Id); var updateTime = DateTime.UtcNow; content.InternalCaption = contentEditViewModel.InternalCaption; var newTranslations = from x in contentEditViewModel.Translations where x.Id == default(int) let translation = (new Translation()).UpdateFromViewModel(x) select translation; var updatedOldData = from x in contentEditViewModel.Translations where x.Id != default(int) select x; var translationsAndChanges = from translation in content.Translations join changes in updatedOldData on translation.Id equals changes.Id select new { translation, changes }; // Update existing translations foreach (var translationAndChange in translationsAndChanges) { translationAndChange.translation.UpdateFromViewModel(translationAndChange.changes); translationAndChange.translation.UpdatedAt = updateTime; } // Add new translations foreach (var newTranslation in newTranslations) { newTranslation.UpdatedAt = updateTime; content.Translations.Add(newTranslation); } _dataDbContext.Content.Update(content); _dataDbContext.SaveChanges(); return(contentEditViewModel); }
/// <summary> /// Create new Content /// </summary> /// <returns></returns> public ActionResult Edit(int? contentId) { var content = _entities.Contents.FirstOrDefault(c => c.Id == contentId); if (content == null) { return RedirectToRoute("ContentIndex"); } if (content.EditPermission != null && !User.IsInRole(content.EditPermission.Name)) { return RedirectToRoute("ContentIndex"); } var model = ContentEditViewModel.FromContent(content); model.Categories = _entities.ContentCategories.OrderBy(c => c.OrderingPosition); model.IsContentAdministrator = User.IsInRole("artikel-administrator"); // Remove status options the user cannot use var statusOptions = Enum.GetValues(typeof(ContentStatus)) .OfType<ContentStatus>(); if (!model.IsContentAdministrator) { statusOptions = content.Status == ContentStatus.Published ? statusOptions.Where(e => e == ContentStatus.Published) : statusOptions.Where(e => e != ContentStatus.Published); } model.ContentStatusList = statusOptions.Select(e => new SelectListItem { Text = e.GetDisplayName(), Value = ((int)e).ToString() }); model.ContentPermissionList = _entities.Roles .Where(r => r.Metapermission.Name == "mitarbeiter") .Select(r => new SelectListItem { Text = r.FriendlyName, Value = r.Id.ToString() }); return View("~/Areas/mitarbeit/Views/Content/Edit.cshtml", model); }
public ActionResult ContactEditMode(ContentEditViewModel model) { if (model.Content == null) { model.Content = _context.SiteContents.First(sc => sc.SiteContentId == 1).Content; model.ErrorMessage = "Treść nie może być pusta"; return(View(model)); } if (model.Content.Length > 2000) { model.ErrorMessage = "Wprowadzona treść jest za długa!"; return(View(model)); } var siteContent = _context.SiteContents.First(sC => sC.SiteContentId == 1); siteContent.Content = model.Content; _context.SaveChanges(); return(RedirectToAction("Contact")); }
public ActionResult Edit(ContentEditViewModel viewModel) { var pages = db.pages.Select(x => new { Text = x.PageName, Value = x.PageId }).ToList(); pages.Insert(0, null); ViewBag.PageId = new SelectList(pages, "Value", "Text", viewModel.PageId); if (ModelState.IsValid) { var model = db.contents.Find(viewModel.ContentId); if (model == null) { return(HttpNotFound()); } var titleUrl = viewModel.Title.Trim().ToLower().Replace(' ', '-'); // Upload Image // var imageUri = !String.IsNullOrEmpty(viewModel.ImageUrl) && !viewModel.ImageUrl.Contains("https://") ? new ImageUploader().AzureBlobUpload(viewModel.ImageUrl.Replace("data:image/png;base64,", ""), titleUrl + ".png") : viewModel.ImageUrl.Contains("https://") ? viewModel.ImageUrl : null; model.PageId = viewModel.PageId; model.Title = viewModel.Title; model.Subtitle = viewModel.Subtitle; model.ImageUrl = imageUri; model.Content1 = viewModel.Content; model.IsPublished = viewModel.IsPublished == "A"; model.LastUpdatedBy = User.Identity.Name; model.LastUpdatedDate = DateTime.Now; db.SaveChanges(); return(RedirectToAction("index")); } return(View(viewModel)); }
/// <summary> /// Create new Content /// </summary> /// <returns></returns> public ActionResult New() { var model = new ContentEditViewModel { Categories = _entities.ContentCategories.OrderBy(c => c.OrderingPosition), IsContentAdministrator = User.IsInRole("artikel-administrator"), ContentStatusList = Enum.GetValues(typeof(ContentStatus)) .OfType<ContentStatus>() .Where(e => e != ContentStatus.Published) .Select(e => new SelectListItem { Text = e.GetDisplayName(), Value = ((int)e).ToString() }), ContentPermissionList = _entities.Roles .Where(r => r.Metapermission.Name == "mitarbeiter") .Select(r => new SelectListItem { Text = r.FriendlyName, Value = r.Id.ToString() }) }; return View("~/Areas/mitarbeit/Views/Content/Edit.cshtml", model); }
public ActionResult Edit(ContentEditViewModel model) { Content content = null; if (ModelState.IsValid) { ContentVersion latestVersion = null; if (model.ContentId == null) { // Create a new Content Object if there is none var c = new Content { Version = 1, EditPermissionId = null, Published = DateTime.MinValue, PublishedByUserId = null, Created = DateTime.Now, AuthorUserId = User.Identity.GetUserId<int>(), UnparsedContent = "", StylesheetCss = "" }; content = _entities.Contents.Add(c); var v = new ContentVersion { ContentId = content.Id, UserId = content.AuthorUserId, UnparsedContent = "", StylesheetCode = "", Title = "", Description = "", Teaser = "", Notes = "" }; latestVersion = _entities.ContentVersions.Add(v); _entities.SaveChanges(); model.ContentId = content.Id; var url = new ContentUrl { Url = String.Format("inhalt/{0}", content.Id), ContentId = content.Id, Type = UrlType.System, Enabled = true }; _entities.ContentUrls.Add(url); content.DefaultUrl = url; } else { // Try to find the existing content object var result = _entities.Contents .Include("EditPermission") .Include("Boilerplates") .Include("BoilerplatesUsed") .Where(c => c.Id == model.ContentId); if (result.Any()) { content = result.First(); if (content.EditPermission != null && !User.IsInRole(content.EditPermission.Name)) { return RedirectToRoute("ContentIndex"); } } else { return RedirectToRoute("ContentIndex"); } } if (User.IsInRole("artikel-administrator")) { if (model.Status == ContentStatus.Published && content.Status != ContentStatus.Published) { // Publish the content content.Published = DateTime.Now; content.PublishedByUserId = User.Identity.GetUserId<int>(); } else if (model.Status != ContentStatus.Published && content.Status == ContentStatus.Published) { // Unpublish the content content.Published = DateTime.MinValue; content.PublishedByUserId = null; } var permission = _entities.Roles.FirstOrDefault(r => r.Id == model.PermissionId); if (permission != null && permission.Metapermission.Name == "mitarbeiter") { content.EditPermissionId = model.PermissionId; } if (string.IsNullOrEmpty(model.Url) && model.Status == ContentStatus.Published) { if (model.Type == ContentType.News) { // Default url is /news/-/1234 model.Url = "-"; } } if (!string.IsNullOrEmpty(model.Url)) { model.Url = model.Url.Trim('/'); if (model.Type == ContentType.News && !Regex.IsMatch(model.Url, @"news/[a-zA-Z0-9_\-/]+/\d+")) { model.Url = String.Format("news/{0}/{1}", model.Url, content.Id); } if (content.DefaultUrl == null || content.DefaultUrl.Url != model.Url) { var duplicates = _entities.ContentUrls .Where(u => u.Url == model.Url); if (!duplicates.Any() || duplicates.First().Enabled == false) { _entities.ContentUrls.RemoveRange(duplicates); var url = new ContentUrl { ContentId = content.Id, Enabled = true, Type = UrlType.Default, Url = model.Url }; if (content.DefaultUrl != null && content.DefaultUrl.Type == UrlType.Default) { content.DefaultUrl.Type = UrlType.Alternative; } content.DefaultUrl = _entities.ContentUrls.Add(url); } else { ModelState.AddModelError("Url", "Die gewählte URL existiert bereits."); } } } } else { // Normal editors cannot change these options model.HomePageOptions = content.HomePageOptions; model.PermissionId = content.EditPermissionId; model.Url = content.DefaultUrl.Url; // Normal editors cannot un-publish content if (model.Status != ContentStatus.Published && content.Status == ContentStatus.Published) { model.Status = content.Status; } } // Update Database Fields model.UpdateContent(content); content.Updated = DateTime.Now; int userId; if (content.Version > 0) { latestVersion = latestVersion ?? _entities.ContentVersions.Where(v => v.ContentId == content.Id).OrderByDescending(v => v.Updated).First(); userId = latestVersion.UserId; } else { userId = content.AuthorUserId; } try { content.CompileLess(); } catch (ArgumentException) { ViewBag.Error = "Dein artikelspezifischer CSS-Code enthält Fehler und wurde daher nicht in den Artikel übernommen (aber in der Datenbank gespeichert)."; } content.Parse(); // Calculate Changes int updateCharsDeleted = 0; int updateCharsInserted = 0; double updateMagnificance = 0; if (latestVersion != null) { var dmp = new diff_match_patch(); var diffs = dmp.diff_main(latestVersion.UnparsedContent ?? "", model.UnparsedContent ?? ""); foreach (var diffItem in diffs.Where(diffItem => diffItem.text.Trim().Length != 0)) { switch (diffItem.operation) { case Operation.DELETE: { updateCharsDeleted += diffItem.text.Length; break; } case Operation.INSERT: { updateCharsInserted += diffItem.text.Length; break; } } } updateMagnificance = Math.Min(updateCharsInserted * 0.9 / Math.Max(1, latestVersion.UnparsedContent.Length) + updateCharsDeleted * 0.1 / Math.Max(1, latestVersion.UnparsedContent.Length), 1); updateMagnificance = Math.Min(1, Math.Tan(updateMagnificance)); } // If the user was not the one who updated last we have to create a new version if (userId != User.Identity.GetUserId<int>()) { content.Version++; latestVersion = new ContentVersion { ContentId = content.Id, Title = content.Title, Version = content.Version, UnparsedContent = content.UnparsedContent, ParsedContent = content.ParsedContent, Description = content.Description, StylesheetCss = content.StylesheetCss, StylesheetCode = content.StylesheetCode, Teaser = content.Teaser, UserId = User.Identity.GetUserId<int>(), Note = content.Notes, Updated = DateTime.Now, UpdateMagnificance = updateMagnificance, UpdateCharsChanged = updateCharsInserted, UpdateCharsDeleted = updateCharsDeleted }; _entities.ContentVersions.Add(latestVersion); } else { if (latestVersion != null) { model.UpdateContentVersion(latestVersion); latestVersion.Version = content.Version; latestVersion.ParsedContent = content.ParsedContent; latestVersion.StylesheetCss = content.StylesheetCss; latestVersion.Updated = DateTime.Now; latestVersion.UpdateMagnificance = updateMagnificance; latestVersion.UpdateCharsChanged = updateCharsInserted; latestVersion.UpdateCharsDeleted = updateCharsDeleted; } } // Save all Changes _entities.SaveChanges(); } model.Saved = ModelState.IsValid; model.Categories = model.Categories ?? _entities.ContentCategories.OrderBy(c => c.OrderingPosition); model.IsContentAdministrator = User.IsInRole("artikel-administrator"); // Remove status options the user cannot use var statusOptions = Enum.GetValues(typeof(ContentStatus)) .OfType<ContentStatus>(); if (content != null) { if (!model.IsContentAdministrator) { statusOptions = content.Status == ContentStatus.Published ? statusOptions.Where(e => e == ContentStatus.Published) : statusOptions.Where(e => e != ContentStatus.Published); } } else { statusOptions = statusOptions.Where(e => e != ContentStatus.Published); } model.ContentStatusList = statusOptions.Select(e => new SelectListItem { Text = e.GetDisplayName(), Value = ((int)e).ToString() }); model.ContentPermissionList = _entities.Roles .Where(r => r.Metapermission.Name == "mitarbeiter") .Select(r => new SelectListItem { Text = r.FriendlyName, Value = r.Id.ToString() }); return View("~/Areas/mitarbeit/Views/Content/Edit.cshtml", model); }
public ActionResult New(ContentEditViewModel model) { return Edit(model); }