public void PostTapped(object sender, ItemTappedEventArgs e) { NewsPost selected = e.Item as NewsPost; var page = new NewsPostPage(selected); News.Content = page.Content; }
//public ActionResult Create([Bind(Include = "NPId,Title,NewsDesc,CompanyCompId", Exclude = " IsVisible, NewsDate")] NewsPost newsPost) public ActionResult Create(FormCollection form) { //if (ModelState.IsValid) //{ // newsPost.NewsDate = (DateTime.Now.Date).ToString(); // newsPost.IsVisible = "T"; // db.NewsPosts.Add(newsPost); // db.SaveChanges(); // return RedirectToAction("Index"); //} //ViewBag.CompanyCompId = new SelectList(db.Companies, "CompId", "CompName", newsPost.CompanyCompId); //return View(newsPost); ViewData["company"] = GetCompany(); ViewData["postingdate"] = DateTime.Now.Date; string jobtitle = form["newstitle"].ToString(); string company = form["company"].ToString(); DateTime postingdate = Convert.ToDateTime(form["postingdate"]); string description = form["newsdesciption"].ToString(); int companyid = (from Company in db.Companies where Company.CompName.Contains(company) select Company.CompId).SingleOrDefault(); NewsPost news = new NewsPost() { Title = jobtitle, NewsDate = postingdate.ToString(), NewsDesc = description, IsVisible = "true", CompanyCompId = companyid }; db.NewsPosts.Add(news); db.SaveChanges(); return(View()); }
[HttpDelete("{id}")] // Kan slette alt, eller kun et objekt basert på id public async void Delete(int id) { NewsPost newsPostToDelete = await _context.NewsPost.FirstAsync(newsPost => newsPost.Id == id); _context.NewsPost.Remove(newsPostToDelete); await _context.SaveChangesAsync(); }
public async Task <IHttpActionResult> PutNewsPost(int id, NewsPost newsPost) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != newsPost.Id) { return(BadRequest()); } db.Entry(newsPost).State = EntityState.Modified; try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!NewsPostExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public async Task <NewsPost> Put(NewsPost updateNewsPost) { _context.Update(updateNewsPost); await _context.SaveChangesAsync(); return(updateNewsPost); }
public async Task <ActionResult> Put(int id, [FromBody] NewsPost value) { if (value == null || value.Id != id) { return(BadRequest()); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } try { await newsServece.UpdateAsync(value) .ConfigureAwait(true); } catch (DbUpdateConcurrencyException) { bool newsPostExists = await newsServece.AnyAsync(id) .ConfigureAwait(true); if (!newsPostExists) { return(NotFound()); } else { throw; } } return(NoContent()); }
public NewsPostAdminView(NewsPost newsPost, string authorName, int commentsCount) : base(newsPost, commentsCount) { EditDate = newsPost.EditDate; AuthorId = newsPost.AuthorId; AuthorName = authorName; IsVisible = newsPost.IsVisible; }
public async Task <IActionResult> Edit(int id, [Bind("Id,Title,AuthorId,Content,Date")] NewsPostEditViewModel newsPost) { if (id != newsPost.Id) { return(NotFound()); } if (ModelState.IsValid) { try { NewsPost result = _context.Posts.FirstOrDefault(p => p.Id == newsPost.Id); _context.Update(result); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!NewsPostExists(newsPost.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction("Index", "News", new { area = "" })); } ViewData["AuthorId"] = new SelectList(_context.Users, "Id", "UserName", newsPost.AuthorId); return(View(newsPost)); }
public async Task <IActionResult> Edit(int id, [Bind("Id,PublicationDate,Article,Text,AuthorId")] NewsPost newsPost) { if (id != newsPost.Id) { return(NotFound()); } if (ModelState.IsValid) { try { dbContext.Update(newsPost); await dbContext.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!NewsPostExists(newsPost.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } ViewData["AuthorId"] = new SelectList(dbContext.Users, "Id", "UserName", newsPost.AuthorId); return(View(newsPost)); }
public async Task <IActionResult> Create(string groupid) { User user = await _userManager.GetUserAsync(User); Group group = await _context.Groups.FindAsync(groupid); if (group == null) { return(await RedirectBack($"Error: Could not find group {groupid}")); } if (!await PressPass.HasPressPass(group, _context)) { return(await RedirectBack($"Error: Group does not have a press pass!")); } if (!await group.HasPermissionAsync(user, "news")) { return(await RedirectBack($"Error: You do not have permission!")); } NewsPost post = new NewsPost() { PostID = Guid.NewGuid().ToString(), GroupID = groupid, AuthorID = user.Id }; return(View(post)); }
public JsonResult ApprovePost(int?Id) { try { using (NewsPortalEntities portalEntities = new NewsPortalEntities()) { var currentUser = (ClaimsPrincipal)Thread.CurrentPrincipal; var UserId = currentUser.Claims.Where(x => x.Type == ClaimTypes.PrimarySid).Select(c => c.Value).SingleOrDefault(); NewsPost newsPost = portalEntities.NewsPosts.Where(x => x.Id == Id).FirstOrDefault(); newsPost.IsReviewed = true; newsPost.ReviewedBy = int.Parse(UserId);; portalEntities.NewsPosts.Attach(newsPost); portalEntities.Entry(newsPost).State = EntityState.Modified; portalEntities.SaveChanges(); string category = newsType.GetByID(x => x.Id == newsPost.CategoryId).NewsType; var webadrs = ConfigurationManager.AppSettings["webid"]; Task.Factory.StartNew(() => new apiPlugin().pagePublish(newsPost.OdiaTitle, (webadrs + "/News/" + category + "/" + newsPost.PostedYear + "/" + newsPost.PostedMonth + "/" + Id + "/" + newsPost.SlugUrl))); } Task.Factory.StartNew(() => new NewsOprations().UpdateData()); return(Json(new { msg = "Post Approved Successfully" }, JsonRequestBehavior.AllowGet)); } catch (Exception ex) { Log.Error(ex.ToString()); } return(Json(new { msg = "Post Approve Unsucessful" }, JsonRequestBehavior.AllowGet)); }
public static void Main() { TeamWorkAPI teamWorkAPI = new TeamWorkAPI(new APISettings(File.ReadAllText("apikey.txt"))); ListLatestArticlesResponse response = teamWorkAPI.News.ListLatestArticles(); foreach (NewsPost post in response.News) { Console.WriteLine($"{post.Title} (@{post.CreatedAtInfo.Date})"); Console.WriteLine(post.Hash); } Console.WriteLine("\n=== Getting a news post ===\n"); //Get a news article NewsPost newsPost = teamWorkAPI.News.GetSpecificArticle("a60761dd5cf0ad6922fecb1ef0e3250d"); Console.WriteLine(newsPost.Title); Console.WriteLine("\n=== Getting a YouTuber ===\n"); //Get a YouTuber YouTuber[] youTuber = teamWorkAPI.Creators.GetYoutuber("76561198072335402"); foreach (YouTuber item in youTuber) { Console.WriteLine($"{item.Name} ({item.YouTubeAccount})"); } Console.ReadKey(); }
//public ActionResult Create([Bind(Include = "NPId,Title,NewsDesc,CompanyCompId", Exclude = " IsVisible, NewsDate")] NewsPost newsPost) public ActionResult Create(FormCollection form) { ViewData["company"] = GetCompany(); ViewData["postingdate"] = DateTime.Now.Date; string newstitle = form["newstitle"].ToString(); string postnews = form["shownews"].ToString(); string company = form["company"].ToString(); DateTime postingdate = Convert.ToDateTime(form["postingdate"]); string description = form["newsdesciption"].ToString(); string verifyDisplay = "false"; int companyid = (from Company in db.Companies where Company.CompName.Contains(company) select Company.CompId).SingleOrDefault(); if (postnews.Contains("true")) { verifyDisplay = "true"; } NewsPost news = new NewsPost() { Title = newstitle, NewsDate = postingdate.ToString(), NewsDesc = description, IsVisible = verifyDisplay, CompanyCompId = companyid }; db.NewsPosts.Add(news); db.SaveChanges(); return(View()); }
public async Task <NewsPost> Post(NewsPost newNewsPost) { _context.NewsPost.Add(newNewsPost); await _context.SaveChangesAsync(); // Lagrer endringen i Databasen return(newNewsPost); // Kan returnere hva som helst feks String/Int eller Status Code feks 201 Created }
public async Task <IHttpActionResult> SetupData() { try { var user = db.Users.First(x => x.Email.Equals("*****@*****.**")); var post = new NewsPost { Body = "nvad jashjavh biaev ", //Id = 1, NewsDate = DateTime.Now, NewsType = "Politics", //Scores = new List<UserScore> { new UserScore { Score = 1, User = user, Post = this } }, User = user, Title = "BlaBla" }; db.NewsPosts.Add(post); db.SaveChanges(); //db.NewsPosts.AddOrUpdate(p => p.Id, post); //db.SaveChanges(); var score = new UserScore { Score = 1, User = user, NewsPost = post }; //db.UserScores.AddOrUpdate(score); //db.SaveChanges(); } catch (Exception e) { Console.WriteLine(e); } return(Ok()); }
public async Task <int> CreateAsync(string title, string content, string userId, List <string> imageUrls, string latinTitle, string author) { var newsPost = new NewsPost { Title = title, Content = content, UserId = userId, ImageUrl = imageUrls.First().Insert(54, "c_fill,h_500,w_500/"), LatinTitle = latinTitle, Author = author, }; await this.newsPostsRepository.AddAsync(newsPost); await this.newsPostsRepository.SaveChangesAsync(); foreach (var url in imageUrls) { var newsPostPicture = new NewsPostPicture { PictureUrl = url.Insert(54, "c_fill,h_960,w_1920/"), NewsPostId = newsPost.Id, }; await this.newsPostPicturesRepository.AddAsync(newsPostPicture); await this.newsPostPicturesRepository.SaveChangesAsync(); } return(newsPost.Id); }
public async Task <IActionResult> DeletePost(int?id) { if (id == null) { return(NotFound()); } NewsPost newsPostFromDb = _context.NewsPosts.Find(id); if (newsPostFromDb == null) { return(NotFound()); } string currentFilePath = Path.Combine(_env.WebRootPath, "img", newsPostFromDb.PhotoURL); if (System.IO.File.Exists(currentFilePath)) { System.IO.File.Delete(currentFilePath); } _context.NewsPosts.Remove(newsPostFromDb); await _context.SaveChangesAsync(); return(RedirectToAction("Posts", "News")); }
public async Task <IActionResult> Edit(int id, [Bind("Title,Content,ShortContent,ImageOrVideoUrl,IsDeleted,DeletedOn,Id,CreatedOn,ModifiedOn")] NewsPost newsPost) { if (id != newsPost.Id) { return(this.NotFound()); } if (this.ModelState.IsValid) { try { this.dataRepository.Update(newsPost); await this.dataRepository.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!this.NewsPostExists(newsPost.Id)) { return(this.NotFound()); } else { throw; } } return(this.RedirectToAction(nameof(this.Index))); } return(this.View(newsPost)); }
public async Task <NewsPost> CreatePostAsync(NewsPost post, bool publish) { VerifyManagementPermission(); if (post == null) { throw new GraException("Could not add post: post was empty."); } post.Title = post.Title.Trim(); post.Content = post.Content.Trim(); post.EmailSummary = post.EmailSummary?.Trim(); if (publish) { post.PublishedAt = _dateTimeProvider.Now; await _newsCategoryRepository.SetLastPostDate(post.CategoryId, _dateTimeProvider.Now); } var addedPost = await _newsPostRepository .AddSaveAsync(GetClaimId(ClaimType.UserId), post); if (publish) { var category = await _newsCategoryRepository.GetByIdAsync(addedPost.CategoryId); addedPost.CategoryName = category.Name; await _cache.RemoveAsync($"s{GetClaimId(ClaimType.SiteId)}.{CacheKey.LatestNewsPostId}"); } return(addedPost); }
public static List <NewsPost> CompilePosts(int postCount) { List <NewsPost> newsPosts = new List <NewsPost>(); List <HtmlNode> posts = new List <HtmlNode>(); int page = 1; // iterate through pages untill all posts are retrieved while (Math.Abs(postCount) > posts.Count) { posts.AddRange(ExtractPostsFromUrl(newsUrl + "news?p=" + page).Take(Math.Abs(postCount) - posts.Count)); page++; } // serialise posts for (int i = 0; i < postCount && i < posts.Count; i++) { NewsPost newsPost = NewsPostFromNode(posts[i]); if (newsPost != null) { newsPosts.Add(newsPost); } } return(newsPosts); }
public void Put(int id, IFormFile file, [FromForm] NewsPost model) { var existingPost = _context.NewsPosts.Find(id); string filePath = null; if (file != null) { using (var stream = file.OpenReadStream()) { var connectionString = _configuration.GetConnectionString("StorageConnection"); filePath = AzureStorage.AddUpdateFile(file.FileName, stream, connectionString, "CoWork454Container"); } } //retain existing photo if none uploaded else if (file == null && existingPost.NewsPhoto != null) { filePath = existingPost.NewsPhoto; } //if nothing use default image else { filePath = "/images/news_default.jpg"; } existingPost.NewsText = model.NewsText; existingPost.NewsTitle = model.NewsTitle; existingPost.NewsTag = model.NewsTag; existingPost.AuthorId = Convert.ToInt32(GetEncryptedGenericCookie("USER_ID")); existingPost.NewsPhoto = filePath; existingPost.DateTimePosted = DateTimeOffset.Now; _context.NewsPosts.Update(existingPost); _context.SaveChanges(); }
public AddComment(NewsPost post, Comment comment, IEngineContext context) { this.post = post; this.comment = comment; this.context = context; this.context = context; }
public async Task <NewsPost> CreatePostAsync(NewsPost post, string postUrl, bool publish = false) { VerifyManagementPermission(); post.Title = post.Title.Trim(); post.Content = post.Content.Trim(); if (publish) { post.PublishedAt = _dateTimeProvider.Now; await _newsCategoryRepository.SetLastPostDate(post.CategoryId, _dateTimeProvider.Now); } var addedPost = await _newsPostRepository .AddSaveAsync(GetClaimId(ClaimType.UserId), post); if (publish) { addedPost.CategoryName = (await _newsCategoryRepository.GetByIdAsync(addedPost.CategoryId)).Name; await SendSubscriptionEmailsAsync(addedPost, postUrl); } if (publish) { _cache.Remove($"s{GetClaimId(ClaimType.SiteId)}.{CacheKey.LatestNewsPostId}"); } return(addedPost); }
public NewsPostPage(NewsPost post) { InitializeComponent(); thepost = post; model = new PostViewModel(post); Content.BindingContext = model; }
public NewsPost GetNewsById(int postId) { NewsPost post = this.Context .Posts .FirstOrDefault(p => p.Id == postId); return(post); }
public ActionResult DeleteConfirmed(int id) { NewsPost newsPost = db.NewsPosts.Find(id); db.NewsPosts.Remove(newsPost); db.SaveChanges(); return(RedirectToAction("Index")); }
public CommentViewModelCollection(NewsPost newsPost, string imagePath, ICollection <CommentViewModel> commentViewModels, CommentToolsModel toolBar, int commentsCount) : base(toolBar) { CommentViewModels = commentViewModels; CommentsCount = commentsCount; NewsPost = newsPost; ImagePath = imagePath; Page++; }
public async Task InsertNewsPostAsync(NewsPost news) { using (var unitOfWork = new UnitOfWork(new RssContext())) { await unitOfWork.NewsPostRepository.Add(news); await unitOfWork.Complete(); } }
public async Task Save(NewsPost newsPost, CancellationToken cancellationToken) { if (_context.Entry(newsPost).State == EntityState.Detached) { _context.News.Add(newsPost); } await _context.SaveChangesAsync(cancellationToken); }
public async Task <bool> CreateNewsPost(NewsPost post) { var client = new HttpClient(); var json = JsonConvert.SerializeObject(post); HttpContent content = new StringContent(json, Encoding.UTF8, "application/json"); var response = await client.PostAsync(ConnectionString + "api/NewsPost/AddNewsPost/", content); return(response.IsSuccessStatusCode); }
public NewsPostCreateModel(NewsPost newsPost) { Name = newsPost.Name; Description = newsPost.Description; PublicationDate = newsPost.PublicationDate; IsVisible = newsPost.IsVisible; AuthorId = newsPost.AuthorId; ImageId = newsPost.ImageId; }
public NewsPost Create(string title, string content, Administrator creator) { var post = new NewsPost() { Title = title, Text = content, PostDate = DateTime.Now, PostedBy = creator }; return post; }
public static NewsPost[] CreateManyPosts(int numberOfPosts, Administrator poster) { var posts = new List<NewsPost>(); for (int i = 0; i < numberOfPosts; i++) { var post = new NewsPost { PostDate = DateTime.MinValue, PostedBy = poster, Text = String.Format("Test {0}", i), Title = String.Format("Test {0}", i) }; post.SaveAndFlush(); posts.Add(post); } return posts.ToArray(); }
public static Comment[] CreateManyComments(int numberOfComments, NewsPost post) { var comments = new List<Comment>(); for (int i = 0; i < numberOfComments; i++) { var comment = new Comment() { CommentIp = "127.0.0.1", Name = "Daniel" + i, Text = "Hello World " + i, ParentPost = post, Time = DateTime.MinValue }; comment.SaveAndFlush(); comments.Add(comment); } return comments.ToArray(); }
private int SaveDetails( NewsPost item ) { int rowsAffected; try { Session["CurrentObject"] = item.Save(); rowsAffected = 1; } catch (Csla.Validation.ValidationException ex) { System.Text.StringBuilder message = new System.Text.StringBuilder(); message.AppendFormat( "{0}<br/>", ex.Message ); if (item.BrokenRulesCollection.Count == 1) message.AppendFormat( "* {0}: {1}", item.BrokenRulesCollection[0].Property, item.BrokenRulesCollection[0].Description ); else foreach (Csla.Validation.BrokenRule rule in item.BrokenRulesCollection) message.AppendFormat( "* {0}: {1}<br/>", rule.Property, rule.Description ); NewsPostError.Visible = true; NewsPostError.Text = message.ToString(); rowsAffected = 0; } catch (Csla.DataPortalException ex) { NewsPostError.Visible = true; NewsPostError.Text = ex.BusinessException.Message; rowsAffected = 0; } catch (Exception ex) { NewsPostError.Visible = true; NewsPostError.Text = ex.Message; rowsAffected = 0; } return rowsAffected; }
private static PostInfo PostToPostInfo(NewsPost post) { PostInfo postInfo = new PostInfo(); List<string> categories = new List<string>(); postInfo.categories = categories.ToArray(); postInfo.dateCreated = post.PostDate; postInfo.description = post.Text.Split(MoreDelimiter.ToCharArray())[0]; if (post.Text.IndexOf(MoreDelimiter) > -1) postInfo.mt_text_more = post.Text.Split(MoreDelimiter.ToCharArray())[1]; postInfo.title = post.Title; postInfo.permalink = GetBlogUrl() + "/Home/Detail.aspx?Id=" + post.Id; postInfo.postid = post.Id.ToString(); return postInfo; }