public string Put(BlogEntryModel editBlogEntry) { var success = ""; try { using (WebSiteContext db = new WebSiteContext()) { BlogEntry blogEntry = db.BlogEntries.Where(b => b.Id.ToString() == editBlogEntry.Id).FirstOrDefault(); if (blogEntry == null) { success = "article not found"; } else { blogEntry.Title = editBlogEntry.Title; blogEntry.ImageName = editBlogEntry.ImageName; blogEntry.Summary = editBlogEntry.Summary; blogEntry.Content = editBlogEntry.Content; blogEntry.LastUpdated = DateTime.Now; db.SaveChanges(); success = "ok"; } } } catch (Exception ex) { success = Helpers.ErrorDetails(ex); } return(success); }
public string Post(BlogEntryModel newBlogEntry) { var success = ""; try { BlogEntry blogEntry = new BlogEntry(); blogEntry.BlogId = newBlogEntry.BlogId; blogEntry.Id = Guid.NewGuid().ToString(); blogEntry.Title = newBlogEntry.Title; blogEntry.ImageName = newBlogEntry.ImageName; blogEntry.Summary = newBlogEntry.Summary; blogEntry.Content = newBlogEntry.Content; blogEntry.Created = DateTime.Now; blogEntry.LastUpdated = DateTime.Now; using (WebSiteContext db = new WebSiteContext()) { db.BlogEntries.Add(blogEntry); db.SaveChanges(); success = blogEntry.Id.ToString(); } } catch (Exception ex) { success = Helpers.ErrorDetails(ex); } return(success); }
public IHttpActionResult PostBlogEntries(BlogEntryModel model) { try { _logger.Debug(string.Format("ini process - Post,idUser:{0}", CurrentIdUser)); if (!ModelState.IsValid) { _logger.Debug(string.Format("ini Post - inValid,idUser:{0}", CurrentIdUser)); return(BadRequest(ModelState)); } BlogEntry blogEnntry = AutoMapper.Mapper.Map <BlogEntry>(model); blogEnntry.LastActivityIdUser = CurrentIdUser; blogEnntry.CreationIdUser = CurrentIdUser; blogEnntry.HeaderUrl = Helpers.UrlFriendly(blogEnntry.Header); _blogEntryBL.Insert(blogEnntry); _logger.Debug(string.Format("finish Post - success,idUser:{0}", CurrentIdUser)); return(Ok(new JsonResponse { Success = true, Message = "BlogEntry was Saved successfully", Data = blogEnntry })); } catch (Exception ex) { LogError(ex); return(InternalServerError(ex)); } }
public ActionResult getPersonalFeed(int sectionId) { try { var user = userRep.getYaUserFromYaMail(User.Identity.Name); var blogPosts = new BlogEntryModel(); var posts = blogEntryRepository.GetYaOwnPostsMan(sectionId, user.Id); var categoryList = categoryRepository.GetCategories(sectionId); ViewBag.sectionId = sectionId; foreach (var item in posts) { blogPosts.BlogList.Add(item.MaptoBlogEntryModel()); blogPosts.CategoriesPerBlog.Add(categoryRepository.GetCategoriesByBlogId(item.BId)); } foreach (var item in categoryList) { blogPosts.CategoryList.Add(item.MaptoCategoryModel()); } return(View("Feed", blogPosts)); } catch { return(null); } }
public async Task <ActionResult> Edit([Bind(/*Include = "ID,Title,Content,IsApproved,CreatedOn"*/)] BlogEntryModel item) { if (ModelState.IsValid) { await DocumentDBRepository <BlogEntryModel> .UpdateItemAsync(item.ID, item); return(RedirectToAction("Index")); } return(View(item)); }
public async Task <ActionResult> Delete([Bind(Include = "ID")] BlogEntryModel item) { if (ModelState.IsValid) { await DocumentDBRepository <BlogEntryModel> .DeleteItemAsync(item.ID); return(RedirectToAction("Index")); } return(View(item)); }
public ActionResult Create(BlogEntryModel entry) { if (ModelState.IsValid) { var entity = entry.GetEntity(); entity.EntryCategory = db.BlogCategories.Find(entry.EntryCategory.Id); db.BlogEntries.Add(entity); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(entry)); }
public static BlogEntryModel MaptoBlogEntryModel(this BlogEntries blogEntryModel) { var blogEntryMapped = new BlogEntryModel { BId = blogEntryModel.BId, Title = blogEntryModel.Title, Content = blogEntryModel.Content, Date = blogEntryModel.Date, Sender = blogEntryModel.Sender, Section = blogEntryModel.Section, }; return(blogEntryMapped); }
public static BlogEntries MapToBlogEntity(this BlogEntryModel blogPost) { //Nytt objekt av Profilemodel med NOT NULL data. var blogEntry = new BlogEntries { Title = blogPost.Title, Content = blogPost.Content, Date = blogPost.Date, Sender = blogPost.Sender, Section = blogPost.Section }; return(blogEntry); }
public ActionResult Edit(BlogEntryModel entry) { if (ModelState.IsValid) { var entity = db.BlogEntries.Find(entry.Id); entry.EntryCategory = db.BlogCategories.Find(entry.EntryCategory.Id); entry.MapEntity(entity); db.Entry <BlogEntry>(entity).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } return(View(entry)); }
public async Task <ActionResult> Create([Bind(Include = "Title,Content")] BlogEntryModel item) { if (ModelState.IsValid) { item.ID = string.Empty;// Guid.NewGuid().ToString(); item.CreatedOn = DateTime.Now; item.IsApproved = true; item.ApprovedOn = DateTime.Now; await DocumentDBRepository <BlogEntryModel> .CreateItemAsync(item); return(RedirectToAction("Index")); } return(View(item)); }
public ActionResult Edit(string id) { if (string.IsNullOrEmpty(id)) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } BlogEntryModel item = DocumentDBRepository <BlogEntryModel> .GetItem(d => d.ID.Equals(id)); if (item == null) { return(HttpNotFound()); } return(View(item)); }
public ActionResult Edit(BlogEntryModel model) { if (!ModelState.IsValid) { return(View(model)); } var serviceResult = _blogService.Save(model); if (serviceResult.Succeeded) { return(RedirectToAction("Index", "BlogAdmin")); } ModelState.AddModelError("Title", serviceResult.Errors.Any() ? serviceResult.Errors[0] : "There was an error"); return(View(model)); }
public ActionResult Add(BlogEntryModel model) { if (!ModelState.IsValid) { return(View("Edit", model)); } var serviceResult = _blogService.Save(model); if (serviceResult.Succeeded) { return(RedirectToAction("Show", "BlogAdmin", new { id = model.Title.ToUrlSlug() })); } ModelState.AddModelError("Title", serviceResult.Errors.Any() ? serviceResult.Errors[0] : "There was an error"); return(View("Edit", model)); }
public void TestSaveAddsCorrectTags() { const string slug = "this-is-a-slug"; var mocker = new AutoMock <BlogEntryService>(); mocker.GetMock <IGetCurrentUserName>().Setup(x => x.GetUserName()).Returns("Jon"); mocker.GetMock <IUserService <BlogUser, BlogUserEntity, int> >().Setup(x => x.FindByName("Jon")).Returns(new BlogUser { DisplayName = "Jon Hawkins" }); mocker.GetMock <IBlogRepository>().Setup(x => x.All <TagEntity>()).Returns(new List <TagEntity> { new TagEntity { Id = 1, Name = "c#" }, new TagEntity { Id = 3, Name = "php" }, new TagEntity { Id = 5, Name = "javascript" } }); mocker.GetMock <IBlogRepository>().Setup(x => x.Exists(It.IsAny <Expression <Func <BlogEntryEntity, bool> > >())).Returns(true); mocker.GetMock <IBlogRepository>().Setup(x => x.Single(It.IsAny <Expression <Func <BlogEntryEntity, bool> > >())).Returns(new BlogEntryEntity { Slug = slug }); var blogEntryModel = new BlogEntryModel(); blogEntryModel.Slug = slug; blogEntryModel.Html = "some html"; blogEntryModel.Date = DateTime.Now.ToString("dd/MM/yyyy"); blogEntryModel.TagsString = "c# happy"; var serviceResult = mocker.Object.Save(blogEntryModel); Assert.IsNotNull(serviceResult); mocker.GetMock <IBlogRepository>().Verify(x => x.Save(It.Is <BlogEntryEntity>(b => b.Slug == blogEntryModel.Slug && b.Tags.Count == 2 && b.Tags.Any(t => t.Name == "c#" && t.Id == 1) && b.Tags.Any(t => t.Name == "happy" && t.Id == 0) ), It.IsAny <Expression <Func <BlogEntryEntity, bool> > >())); }
public void sendPost(string title, int section, string content, string categoryIds) { var sender = userRep.getYaUserFromYaMail(User.Identity.Name); if (!string.IsNullOrWhiteSpace(content) || !string.IsNullOrWhiteSpace(title)) { var blogToPost = new BlogEntryModel { Title = title, Section = section, Sender = sender.Id, Content = content, Date = DateTime.Now }; var id = blogRep.AddBlogEntry(blogToPost.MapToBlogEntity()); var test = mjau(categoryIds); //int k; //k = test.Length; for (int s = 0; s < test.Length; s++) { var blog_kat = new Category_Blog { CategoryId = test[s], BlogId = id }; cb_rep.Add(blog_kat); } ; var fileModel = new FileModel { BlogEntry = id, Path = root, Type = null }; fileRep.Add(fileModel.MapToFileEntity()); } }
public void PostBlogEntry(string blogId, string blogText) { var hubContext = GlobalHost.ConnectionManager.GetHubContext <LiveBlogHub>(); // Process the blogText for commands var commandParser = FactoryManager.CommandFactory.GetCommandParser(); var modifiedBlogText = commandParser.Parse(blogText); var blogEntry = new BlogEntryModel { BlogId = blogId, EntryType = "default", Text = modifiedBlogText, TimeStamp = DateTime.Now.ToUniversalTime().ToString("yyyy-MM-dd hh:mm:ss zzz") }; var json = JsonConvert.SerializeObject(blogEntry); hubContext.Clients.All.blogPosted(json); }
public BlogEntryModel GetByTitle(string blogName) { var blogEntry = new BlogEntryModel(); try { using (WebSiteContext db = new WebSiteContext()) { var dbBlogEntry = db.BlogEntries.Where(b => b.Title == blogName).FirstOrDefault(); if (dbBlogEntry != null) { blogEntry.BlogId = dbBlogEntry.BlogId; blogEntry.Title = dbBlogEntry.Title; blogEntry.Summary = dbBlogEntry.Summary; blogEntry.Content = dbBlogEntry.Content; blogEntry.ImageName = dbBlogEntry.ImageName; } } } catch (Exception ex) { blogEntry.Title = Helpers.ErrorDetails(ex); } return(blogEntry); }
private BlogEntryModel MapToModel(BlogEntry entry) { var html = ConvertToMarkDown(entry.Markdown); var summary = ConvertToMarkDown(entry.Summary); var model = new BlogEntryModel { Date = entry.DateCreated.ToShortenedDateString(), Slug = entry.Slug, NewSlug = entry.Slug, Title = entry.Title, Html = html, Summary = summary, Markdown = entry.Markdown, Tags = entry.Tags.Select(t => t.Name).ToList(), IsCodePrettified = entry.IsCodePrettified ?? true, IsPublished = entry.IsPublished }; model.BuildTagStringFromList(); return(model); }
public IHttpActionResult PutBlogEntries(int id, BlogEntryModel model) { try { _logger.Debug(string.Format("ini process - Put,idUser:{0}", CurrentIdUser)); if (id != model.Id) { _logger.Debug(string.Format("ini Put - inValid,idUser:{0}", CurrentIdUser)); return(BadRequest("Invalid ID")); } if (!ModelState.IsValid) { _logger.Debug(string.Format("ini Put - inValid,idUser:{0}", CurrentIdUser)); return(BadRequest(ModelState)); } _logger.Debug(string.Format("ini update ,idUser: {0}, modelId update: {1}", CurrentIdUser, id)); BlogEntry blogentry = AutoMapper.Mapper.Map <BlogEntry>(model); blogentry.LastActivityIdUser = CurrentIdUser; _blogEntryBL.Update(blogentry); _logger.Debug(string.Format("finish Put - success,idUser:{0}", CurrentIdUser)); return(Ok(new JsonResponse { Success = true, Message = "BlogEntry was Saved successfully", Data = blogentry })); } catch (Exception ex) { LogError(ex); return(InternalServerError(ex)); } }
public ActionResult Feed(int sectionId = 2) { try { var blogPosts = new BlogEntryModel(); var posts = blogEntryRepository.GetPosts(sectionId); var categoryList = categoryRepository.GetCategories(sectionId); ViewBag.sectionId = sectionId; foreach (var item in posts) { var item2 = item.MaptoBlogEntryModel(); item2.SenderName = userRep.getYaUserFromYaId(item.Sender).Firstname + ' ' + userRep.getYaUserFromYaId(item.Sender).Lastname; blogPosts.BlogList.Add(item2); blogPosts.CategoriesPerBlog.Add(categoryRepository.GetCategoriesByBlogId(item.BId)); } foreach (var item in categoryList) { blogPosts.CategoryList.Add(item.MaptoCategoryModel()); } return(View(blogPosts)); } catch { return(null); } }
public void PostNewEntry(BlogEntryModel model) { }
public ActionResult Create(BlogEntryModel model, HttpPostedFileBase contentImage, HttpPostedFileBase contentCoverImage, List <string> videoyoutube, string existingTags, string newTags) { BlogEntryRepository objblogentry = new BlogEntryRepository(this.SessionCustom); ContentManagement objcontent = new ContentManagement(this.SessionCustom, HttpContext); try { objcontent.ContentImage = contentImage; objcontent.ContentCoverImage = contentCoverImage; objcontent.CollVideos = videoyoutube; this.SessionCustom.Begin(); model.IContent.LanguageId = CurrentLanguage.LanguageId; objcontent.ContentInsert(model.IContent, 4); objblogentry.Entity = model.BlogEntry; objblogentry.Entity.ExistingTags = !string.Empty.Equals(existingTags) ? existingTags : null; objblogentry.Entity.NewTags = !string.Empty.Equals(newTags) ? newTags : null; if (objblogentry.Entity.ContentId != null) { objblogentry.Update(); this.InsertAudit("Update", this.Module.Name + " -> " + model.IContent.Name); } else { if (!string.IsNullOrEmpty(Request.Form["TempFiles"])) { string[] files = Request.Form["TempFiles"].Split(','); if (files.Length > 0) { if (!Directory.Exists(Path.Combine(Server.MapPath("~"), @"Files\" + objcontent.ObjContent.ContentId + @"\"))) { Directory.CreateDirectory(Path.Combine(Server.MapPath("~"), @"Files\" + objcontent.ObjContent.ContentId + @"\")); } } foreach (var item in files) { string filep = Path.Combine(Server.MapPath("~"), @"Files\Images\" + Path.GetFileName(item)); if (System.IO.File.Exists(filep)) { string filedestin = Path.Combine(Server.MapPath("~"), @"Files\Images\" + Path.GetFileName(item)); System.IO.File.Move(filep, Path.Combine(Server.MapPath("~"), @"Files\" + objcontent.ObjContent.ContentId + @"\" + Path.GetFileName(item))); } } } objblogentry.Entity.ContentId = objcontent.ObjContent.ContentId; objblogentry.Insert(); this.InsertAudit("Insert", this.Module.Name + " -> " + model.IContent.Name); } this.SessionCustom.Commit(); } catch (Exception ex) { SessionCustom.RollBack(); Utils.InsertLog( this.SessionCustom, "Error" + this.Module.Name, ex.Message + " " + ex.StackTrace); } if (Request.Form["GetOut"] == "0") { return(this.RedirectToAction("Index", "Content", new { mod = Module.ModulId })); } else { return(this.RedirectToAction("Detail", "BlogEntry", new { mod = Module.ModulId, id = objblogentry.Entity.ContentId })); } }
public ActionResult Create(BlogEntryModel model, string contentImage, List <string> videoyoutube) { Business.Services.CustomPrincipal currentUserInfo = (Business.Services.CustomPrincipal)User; if (Utils.IsBlogAdmin(currentUserInfo.UserId)) { BlogEntryRepository objblogentry = new BlogEntryRepository(this.SessionCustom); ContentManagement objcontent = new ContentManagement(this.SessionCustom, HttpContext); try { model.IContent.Template = "BlogEntry"; model.IContent.Widget = false; model.IContent.Private = false; model.IContent.Active = true; model.IContent.Image = contentImage; objcontent.CollVideos = videoyoutube; this.SessionCustom.Begin(); model.IContent.LanguageId = 2; objcontent.ContentInsert(model.IContent, 4); objblogentry.Entity = model.BlogEntry; if (objblogentry.Entity.ContentId != null) { objblogentry.Update(); this.InsertAudit("Update", this.Module.Name + " -> " + model.IContent.Name); } else { objblogentry.Entity.ContentId = objcontent.ObjContent.ContentId; objblogentry.Insert(); this.InsertAudit("Insert", this.Module.Name + " -> " + model.IContent.Name); } string serverMap = Server.MapPath("~"); string origin = serverMap + @"\resources\temporal\blog\" + contentImage; if (System.IO.File.Exists(origin)) { if (!System.IO.Directory.Exists(serverMap + @"\files\" + objblogentry.Entity.ContentId)) { System.IO.Directory.CreateDirectory(serverMap + @"\files\" + objblogentry.Entity.ContentId); } System.IO.File.Move(origin, serverMap + @"\files\" + objblogentry.Entity.ContentId + @"\" + contentImage); } this.SessionCustom.Commit(); ViewBag.Result = true; } catch (Exception ex) { SessionCustom.RollBack(); Utils.InsertLog( this.SessionCustom, "Error" + this.Module.Name, ex.Message + " " + ex.StackTrace); ViewBag.Result = false; } return(this.View("index", model)); } return(null); }
public ViewerModel GetEntriesFrom(string blogUrl, int numberOfEntries, int bodyMaxLength) { var accessToken = _spContext.UserAccessTokenForSPHost; if (string.IsNullOrEmpty(accessToken)) { throw new Exception(Viewer.NotAccessTokenError); } using (var clientContext = TokenHelper.GetClientContextWithAccessToken(blogUrl, accessToken)) { if (clientContext == null) { throw new Exception(Viewer.BlogNotFoundError); } var web = clientContext.Web; var list = web.Lists.GetByTitle(Viewer.BlogListTitle); clientContext.Load(list); clientContext.ExecuteQuery(); var viewXml = string.Format("<View><Query><OrderBy><FieldRef Name='PublishedDate' Ascending='False' /></OrderBy></Query><ViewFields><FieldRef Name='Title' /><FieldRef Name='Body' /><FieldRef Name='Author' /><FieldRef Name='PublishedDate' /></ViewFields><QueryOptions /><RowLimit>{0}</RowLimit></View>", numberOfEntries); var query = new CamlQuery { ViewXml = viewXml }; var blogItems = list.GetItems(query); clientContext.Load(blogItems); clientContext.ExecuteQuery(); var entries = new List <BlogEntryModel>(); foreach (var item in blogItems) { var authorUser = item["Author"] as FieldUserValue; var htmlBody = item["Body"] as string; var body = htmlBody.ToTextWithoutHtmlTags(); var firstPartOfBody = body.Length <= bodyMaxLength ? body : body.Substring(0, bodyMaxLength) + "..."; var publishedDate = (DateTime)item["PublishedDate"]; publishedDate = publishedDate.AddHours(1.0); var entry = new BlogEntryModel { Id = item.Id, Title = item["Title"] as string, Content = firstPartOfBody, Author = authorUser.LookupValue, Date = publishedDate.ToString("HH:mm") }; entries.Add(entry); } clientContext.Load(web, w => w.Title); clientContext.ExecuteQuery(); var blogTitle = web.Title; var viewerModel = new ViewerModel { BlogUrl = blogUrl, BlogTitle = blogTitle, BlogEntries = entries }; return(viewerModel); } }
public ServiceResult <string> Save(BlogEntryModel entryModel) { if (entryModel == null) { throw new ArgumentNullException("entryModel"); } entryModel.RebuildTagsFromString(); BlogEntry entry = null; if (!Exists(entryModel.Slug)) { entry = new BlogEntry { Slug = entryModel.Title.ToUrlSlug(), DateCreated = DateTime.Now }; if (Exists(entry.Slug)) { return(ServiceResult <string> .Error("Sorry, a post with that slug already exists.")); } } else { entry = AutoMapper.Mapper.Map <BlogEntryEntity, BlogEntry>(_blogRepository.Single <BlogEntryEntity>(b => b.Slug == entryModel.Slug)); entry.DateCreated = DateTime.ParseExact(entryModel.Date, DateSettings.DateStringFormat(), Thread.CurrentThread.CurrentCulture); var slugChanged = !string.Equals(entryModel.Slug, entryModel.NewSlug, StringComparison.InvariantCultureIgnoreCase) && !string.IsNullOrWhiteSpace(entryModel.NewSlug); if (slugChanged) { if (Exists(entryModel.NewSlug)) { return(ServiceResult <string> .Error("Sorry, a post with that slug already exists.")); } //delete current one as slug is the ID will create / save a new one. Delete(entryModel.Slug); entry.Slug = entryModel.NewSlug.ToLowerInvariant(); } } if (!IsValidSlug(entry.Slug)) { return(ServiceResult <string> .Error("That's not a valid slug. Only letters, numbers and hypens are allowed.")); } entry.Title = entryModel.Title; entry.Markdown = entryModel.Markdown; entry.Summary = CreateSummary(entryModel.Markdown); entry.IsPublished = entryModel.IsPublished; entry.IsCodePrettified = entryModel.IsCodePrettified; entry.Author = _blogUserService.FindByName(_currentUserService.GetUserName()).DisplayName; //update all the tags. var tags = _blogRepository.All <TagEntity>().ToArray(); var distinctTags = entryModel.Tags.Distinct(); var trimmedTags = distinctTags.Select(t => t.Trim().ToLowerInvariant()).ToArray(); var matchedTags = tags.Where(t => trimmedTags.Contains(t.Name.ToLowerInvariant())).ToArray(); var newTags = trimmedTags.Where(t => tags.All(tag => tag.Name.ToLowerInvariant() != t)) .Select(t => new TagEntity { Id = 0, Name = t }).ToArray(); //ensure new tags are added to the list of known tags. foreach (var newTag in newTags) { _blogRepository.Add(newTag); } var actualTags = newTags.Union(matchedTags); var entryEntity = AutoMapper.Mapper.Map <BlogEntry, BlogEntryEntity>(entry); entryEntity.Tags.Clear(); entryEntity.Tags.AddRange(actualTags); _blogRepository.Save(entryEntity, b => b.Slug == entry.Slug); _blogTagService.RemoveUnsedTags(); _blogTagService.UpdateTagCount(); return(ServiceResult <string> .Success(entry.Slug)); }