public async Task <IActionResult> Edit(int id, [Bind("id,Position,postlistlvl")] PostList postList) { if (id != postList.id) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(postList); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!PostListExists(postList.id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(postList)); }
public async Task <IActionResult> Authors(string name, int page = 1) { var author = await _db.Authors.GetItem(a => a.AppUserName == name); var pager = new Pager(page); var posts = await _db.BlogPosts.GetList(p => p.Published > DateTime.MinValue && p.AuthorId == author.Id, pager); if (pager.ShowOlder) { pager.LinkToOlder = $"authors/{name}?page={pager.Older}"; } if (pager.ShowNewer) { pager.LinkToNewer = $"authors/{name}?page={pager.Newer}"; } var model = new PostList { PostListType = PostListType.Author, Author = author, Posts = posts, Pager = pager }; SetViewBag(); return(View(_listView, model)); }
public async Task <List <ProductHuntPost> > RefreshDataAsync() { PostList = new PostList(); var uri = new Uri(string.Format(App.RestUrl, postsUrl)); try { var response = await client.GetAsync(uri); if (response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync(); PostList = JsonConvert.DeserializeObject <PostList>(content); foreach (ProductHuntPost post in PostList.List) { post.PosterID = post.User.ID; if (post.User.ImageUrl != null) { post.User.Image = post.User.ImageUrl.original ?? ""; } else { post.User.Image = ""; } } } } catch (Exception ex) { Debug.WriteLine("ERROR: " + ex.Message); } return(new List <ProductHuntPost>(PostList.List)); }
private async Task <bool> Like(Guid id) { try { IsBusy = true; await _postService.LikePost(id, _runtimeContext.Token); var postDto = await _postService.GetPost(id, _runtimeContext.Token); PostList.First(x => x.Id == id).Likes = postDto.Likes; PostList.First(x => x.Id == id).IsLikedByUser = postDto.IsLikedByUser; return(await Task.FromResult(true)); } catch (Exception ex) { await Application.Current.MainPage.DisplayAlert("Error", ex.Message, "OK"); return(await Task.FromResult(false)); } finally { IsBusy = false; } }
/// <summary> /// /// </summary> /// <param name="nav"></param> /// <param name="postList"></param> /// <param name="blogIndexType"></param> /// <param name="pageIndex"></param> public BlogIndexModel(Nav nav, PostList postList, BlogIndexType blogIndexType, int pageIndex) { Nav = nav; PostList = postList; ListType = blogIndexType; PageIndex = pageIndex; }
private void updatePostSelect(object o) { if (o == null) { return; } else if (o is object[]) { var param = (object[])o; foreach (var item in param) { if (item == null) { postparams = new Dictionary <int, string>(); return; } } int index = PostList.IndexOf(param[0] as OptionalItem <string, string>[]); if (param.Length != 2) { return; } if (postparams.ContainsKey(index)) { postparams[index] = param[1].ToString(); } else { postparams.Add(index, param[1].ToString()); } } }
public async Task <List <ProductHuntPost> > RefreshDataByDateAsync(DateTime filterByDate) { PostList = new PostList(); int daysBack = DateTime.Today.Subtract(filterByDate).Days; var uri = new Uri(string.Format(App.RestUrl, postsByDateUrl + daysBack)); try { var response = await client.GetAsync(uri); if (response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync(); PostList = JsonConvert.DeserializeObject <PostList>(content); foreach (ProductHuntPost post in PostList.List) { post.PosterID = post.User.ID; if (post.User.ImageUrl != null) { post.User.Image = post.User.ImageUrl.original ?? ""; } else { post.User.Image = ""; } } } } catch (Exception ex) { Debug.WriteLine("ERROR: " + ex.Message); } return(new List <ProductHuntPost>((PostList != null && PostList.List != null) ? PostList.List : new ProductHuntPost[0])); }
public string GetUserPostById(string userId) { PostList postList = new PostList(); postList = postList.GetByUserId(new Guid(userId)); return(JsonConvert.SerializeObject(postList.List)); }
private PostModel() { postList = new PostList(); cloudUserSystem = new CloudUserSystem(); cloudDatabase = new CloudDatabase(this); databaseOnline = true; new Thread(async() => postList = await cloudDatabase.GetAllPost()).Start(); }
public void ClearItems() { int lastPostListCount = PostList.Count; PostList.Clear(); NotifyItemRangeRemoved(0, lastPostListCount); }
public void ReplaceItems(List <Post> newItems) { ClearItems(); PostList.AddRange(newItems); NotifyItemRangeInserted(0, newItems.Count); }
public MainPage() { this.InitializeComponent(); this.NavigationCacheMode = NavigationCacheMode.Required; DataContext = new MainPageViewModel(); PostList.RegisterPropertyChangedCallback(ItemsControl.ItemsSourceProperty, OnItemsSourceChanged); }
/// <summary> /// Writes the saved messages to the Logger file. /// </summary> public Logger Flush() { var fileText = File.Exists(Path) ? File.ReadAllText(Path) : ""; var lista = JsonConvert.DeserializeObject <List <Entry> >(fileText) ?? new List <Entry>(); var result = lista.Concat(PostList); File.WriteAllText(Path, JsonConvert.SerializeObject(result)); PostList.Clear(); return(this); }
public void AddPost(Post p) { PostList pl = (PostList)ServerManager.Instance.ServerInstance.ReadDomainObject("PostList"); if (pl == null) { pl = new PostList("PostList"); } pl.AddPost(p); ServerManager.Instance.ServerInstance.WriteDomainObject(pl); }
public List <Post> GetPostsFromLastDate(DateTime dt) { PostList pl = GetPostList(); if (pl != null) { return((pl.PList.Where <Post>(x => x.TimeStamp.CompareTo(dt) > 0)).ToList <Post>()); } return(null); }
public void AddItems(List <Post> newItem) { SetLoadingAnimation(false); int lastItemPos = PostList.Count - 1; PostList.AddRange(newItem); NotifyItemRangeInserted(lastItemPos + 1, newItem.Count); }
public String GetMostRecentPosts() { PostList postList = new PostList(); postList = postList.GetMostRecent(); string pList = JsonConvert.SerializeObject(postList.List); return(pList); }
public async Task <IActionResult> Create([Bind("id,Position,postlistlvl")] PostList postList) { if (ModelState.IsValid) { _context.Add(postList); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(postList)); }
// GET: Posts public ActionResult Index() { try { PostList oPosts = new PostList(); return(View(oPosts.GetPosts())); } catch (Exception e) { ViewBag.Error = e.Message; return(RedirectToAction("Index", "Home")); } }
// GET: Posts/Edit/5 public ActionResult Edit(int id) { try { PostList oPosts = new PostList(); return(View(oPosts.GetPostForEdit(id))); } catch (Exception e) { ViewBag.Error = e.Message; return(RedirectToAction("NotFound", "Error")); } }
public async Task <IActionResult> GetPostsAsync([FromQuery] PostGetModel model) { model.Validate(); var list = await _postRepository.GetPostsAsync(model.Keyword, model.StartDate, model.EndDate, model.Page, model.PageSize); if (list.Items.Count == 0) { throw new NotFound404Exception("page"); } return(Ok(PostList.GetFrom(list))); }
public async Task <IActionResult> Index(string category, int page = 1) { try { var result = await postService.GetAll(x => x.IsActive == true); if (category != null) { result = await postService.GetAll(x => (x.Category.Title == category) && (x.IsActive == true)); } TempData["mainHead"] = GetPageInfo().Result.MainHeader; TempData["subHead"] = GetPageInfo().Result.MainSubHeader; TempData["blogName"] = GetPageInfo().Result.BlogName; TempData["path"] = "pageimg"; TempData["headerImage"] = GetPageInfo().Result.MainHeaderImage; TempData["title"] = "Ana Sayfa"; TempData["css"] = "col-lg-12 col-md-10 mx-auto"; var count = result.Count(); int pagesize = 5; result = result.Skip((page - 1) * pagesize).Take(pagesize); var response = new PostList() { Posts = result.ToList(), PagingInfo = new PagingInfo() { CurrentPage = page, ItemPerPage = pagesize, Total = count, CategoryName = category } }; if (response.Posts.Count > 0) { return(View(response)); } else { return(RedirectToAction("ErrorPage", "Error")); } } catch (Exception) { return(RedirectToAction("ErrorPage", "Error")); } }
// GET: Posts/Delete/5 public ActionResult Delete(int id) { try { PostList oPosts = new PostList(); oPosts.DeletePost(id); return(RedirectToAction("Index")); } catch (Exception e) { ViewBag.Error = e.Message; return(RedirectToAction("NotFound", "Error")); } }
public List<Post> GetPostList() { PostList pl = (PostList)ServerManager.Instance.ServerInstance.ReadDomainObject("PostList"); if (pl == null) { pl = new PostList("PostList"); ServerManager.Instance.ServerInstance.WriteDomainObject(pl); } //obter posts de amigos List<Post> Friends = UpdateFriends(); Friends.AddRange(pl.PList); Friends.Sort(); return Friends; }
public Floor Clone() => new Floor( PartitionClass.ToArray(), ClassDimensions.ToArray(), ClassSubs.ToArray(), ClassBook.ToArray(), ClassSubBook.Select(s => s.ToArray()).ToArray(), Mult, PostList.ToArray(), MaxOver, MaxUnder, MaxError, TwoFitWeight, TwoFitAtten, N);
public async Task <PostList> GetPostToShowByUserId(string userId) { PostList searchList = new PostList(); FriendList friendList = await cloudUserSystem.GetFriendListByUserId(userId); foreach (var post in postList.Posts) { //user's post or friends' post which is not disable user if (friendList.GetFriendById(post.SenderId) != null && !post.IsDisable(userId) || post.SenderId == userId) { searchList.AddPost(post); } } return(searchList); }
} // END Get Post List Model public bool UpdatePostStatus(PostList model, Status status) { using (var ctx = new ApplicationDbContext()) { var entity = ctx.Posts .Single(e => e.PostID == model.PostID); entity.PostID = model.PostID; entity.PostUserID = model.PostUserID; entity.AboutUserID = model.AboutUserID; entity.Status = status; entity.ModifiedUTC = DateTimeOffset.Now; return(ctx.SaveChanges() == 1); } } //END Post Update Post
private void TryToConnectWithDatabaseSystem() { new Thread(async() => { while (!databaseOnline) { Console.Write("Try to reconnect with Database System in 5s.\n["); for (int x = 10; x > 0; x--) { Console.Write("-"); Thread.Sleep(500); } Console.WriteLine("]\nTry reconnecting..."); postList = await cloudDatabase.GetAllPost(); } }).Start(); }
public ActionResult Edit(CreatePost model) { try { if (ModelState.IsValid) { PostList oPosts = new PostList(); oPosts.EditPost(model); } return(RedirectToAction("Index")); } catch (Exception e) { throw new Exception(e.Message); } }
public async Task <IActionResult> Tags(string id) { using HttpClient client = new HttpClient(); string query = $"https://blogger.googleapis.com/v3/blogs/{blogId}/posts?fetchBodies=false&fetchImages=true&maxResults=500&orderBy=PUBLISHED&view=READER&key={apiKey}&labels={id}"; string response = await client.GetStringAsync(new Uri(query)).ConfigureAwait(false); PostList list = JsonConvert.DeserializeObject <PostList>(response); BlogListViewModel viewModel = new BlogListViewModel(Database, list) { SearchTerm = "#" + id }; return(View(viewName: "~/Views/Blog/Index.cshtml", viewModel)); }
public List <Post> GetPostList() { PostList pl = (PostList)ServerManager.Instance.ServerInstance.ReadDomainObject("PostList"); if (pl == null) { pl = new PostList("PostList"); ServerManager.Instance.ServerInstance.WriteDomainObject(pl); } //obter posts de amigos List <Post> Friends = UpdateFriends(); Friends.AddRange(pl.PList); Friends.Sort(); return(Friends); }
private async Task Edit(Guid id) { try { IsBusy = true; var selectedPost = PostList.Single(x => x.Id == id); await _navigationService.NavigateAsync <PostDetailsViewModel>(selectedPost); } catch (Exception ex) { await Application.Current.MainPage.DisplayAlert("Error", ex.Message, "OK"); } finally { IsBusy = false; } }
public void AcceptFriendRequest(FriendRequest f) { try { ServerManager.Instance.ServerInstance.ServerRequestInvoker.AcceptFriendRequest(f); //Get processed requests Post p = new Post("PADIBook de " + f.RequestedUserName, f.RequestingUserName + " ficou seu amigo. O seu endereço é " + f.FromAddress + ":" + f.FromPort); PostList pl = (PostList)ServerManager.Instance.ServerInstance.ReadDomainObject("PostList"); if (pl == null) { pl = new PostList("PostList"); } pl.AddPost(p); ServerManager.Instance.ServerInstance.WriteDomainObject(pl); } catch (ServiceUnavailableException) { throw new ServiceUnavailableException("Não foi possível enviar a resposta."); } catch (RemotingException) { throw new ServiceUnavailableException("Não foi possível enviar o pedido."); } f.FriendRequestState = FriendRequest.RequestState.ACCEPTED; FriendRequestList recvFrdReqs = GetReceivedFriendRequests(); //add friend Friends friends = GetFriendList(); friends.AddFriend(f.RequestingUserName, f.FromAddress, f.FromPort); ServerManager.Instance.ServerInstance.WriteDomainObject(friends); //Remove request from received requests recvFrdReqs.RemoveFriendRequest(f); ServerManager.Instance.ServerInstance.WriteDomainObject(recvFrdReqs); }
/// <summary> /// Returns a list of posts for a particular nav that also satisfy other query /// critirions. /// </summary> /// <param name="query"></param> /// <returns></returns> public PostList GetPosts(PostQuery query) { List<Post> posts = new List<Post>(); List<PostEntity> postEnts = null; int totalPosts = 0; //int skip = query.PageIndex * query.PageSize; int skip = (query.PageIndex - 1) * query.PageSize; int take = query.PageSize; using (var db = new BlogDbContext()) { if (query.QueryBy == QueryBy.Index) // index { totalPosts = db.PostEntities.Count(p => p.NavId == query.Nav.NavId && p.PostStatus == PostStatus.Published); postEnts = (from p in db.PostEntities.Include(p => p.TagEntities) where p.NavId == query.Nav.NavId && p.PostStatus == PostStatus.Published orderby p.DateCreated descending select p) .Skip(skip).Take(take).ToList(); } else if (query.QueryBy == QueryBy.Drafts) // drafts { totalPosts = db.PostEntities.Count(p => p.NavId == query.Nav.NavId && p.PostStatus == PostStatus.Draft); postEnts = (from p in db.PostEntities.Include(p => p.TagEntities) where p.NavId == query.Nav.NavId && p.PostStatus == PostStatus.Draft orderby p.DateCreated descending select p) .Skip(skip).Take(take).ToList(); } else if (query.QueryBy == QueryBy.Article) { totalPosts = db.PostEntities.Count(p => p.PostType == (short)PostType.Article && p.NavId == query.Nav.NavId && p.PostStatus == PostStatus.Published); postEnts = (from p in db.PostEntities.Include(p => p.TagEntities) where p.PostType == PostType.Article && p.PostStatus == PostStatus.Published && p.NavId == query.Nav.NavId orderby p.DateCreated descending select p) .Skip(skip).Take(take).ToList(); } else if (query.QueryBy == QueryBy.Tag) { TagEntity tagEnt = db.TagEntities.FirstOrDefault(t => t.Name.ToLower() == query.TagName.ToLower() && t.NavId == query.Nav.NavId); if (tagEnt != null) { // get the total published posts count from the tag totalPosts = (from p in db.PostEntities from t in p.TagEntities where p.NavId==query.Nav.NavId && t.TagId == tagEnt.TagId && p.PostStatus == PostStatus.Published select p).Count(); //http://stackoverflow.com/questions/15556134/entity-framework-many-to-many-works-but-include-does-not/15577053?noredirect=1#15577053 postEnts = (from p in db.PostEntities.Include(p => p.TagEntities) where p.TagEntities.Any(t=>t.TagId ==tagEnt.TagId) && p.NavId == query.Nav.NavId && p.PostStatus == PostStatus.Published orderby p.DateCreated descending select p).Skip(skip).Take(take).ToList(); } } else if (query.QueryBy == QueryBy.Archive) { if (query.Month.HasValue && query.Month >0) { // get the total posts for the year and month totalPosts = (from p in db.PostEntities where p.NavId == query.Nav.NavId && p.DateCreated.Year == query.Year && p.DateCreated.Month == query.Month.Value && p.PostStatus == PostStatus.Published select p).Count(); postEnts = (from p in db.PostEntities.Include(p => p.TagEntities) where p.NavId == query.Nav.NavId && p.DateCreated.Year == query.Year && p.DateCreated.Month == query.Month.Value && p.PostStatus == PostStatus.Published orderby p.DateCreated descending select p) .Skip(skip).Take(take).ToList(); } else { // get the total posts for the year only totalPosts = (from p in db.PostEntities where p.NavId == query.Nav.NavId && p.DateCreated.Year == query.Year && p.PostStatus == PostStatus.Published select p).Count(); postEnts = (from p in db.PostEntities.Include(p => p.TagEntities) where p.NavId == query.Nav.NavId && p.DateCreated.Year == query.Year && p.PostStatus == PostStatus.Published orderby p.DateCreated descending select p) .Skip(skip).Take(take).ToList(); } } foreach (var postEnt in postEnts) { User user = db.Users.FirstOrDefault(u => u.UserId == postEnt.UserId); posts.Add(BlogMapper.MapPost(postEnt, query.Nav, user)); } PostList postList = new PostList(posts, totalPosts); return postList; } }
public void AcceptFriendRequest(FriendRequest fr) { //Remove request FriendRequestList pl = (FriendRequestList)ServerManager.Instance.ServerInstance.ReadDomainObject("SentFriendRequests"); if (pl != null) { pl.RemoveFriendRequest(fr); ServerManager.Instance.ServerInstance.WriteDomainObject(pl); } //Add friend Friends plist = (Friends)ServerManager.Instance.ServerInstance.ReadDomainObject("Friends"); if (plist == null) { plist = new Friends("Friends"); } // Add only if we're not already friends if (!plist.FriendsInfo.ContainsKey(fr.RequestedUserName)) { plist.AddFriend(fr.RequestedUserName, fr.SendTo, fr.SendToPort); ServerManager.Instance.ServerInstance.WriteDomainObject(plist); //Add post Post p = new Post("PADIBook de " + fr.RequestingUserName, fr.RequestedUserName + " ficou seu amigo.O seu endereço é " + fr.SendTo + ":" + fr.SendToPort); PostList postl = (PostList)ServerManager.Instance.ServerInstance.ReadDomainObject("PostList"); if (postl == null) { postl = new PostList("PostList"); ServerManager.Instance.ServerInstance.WriteDomainObject(postl); } postl.AddPost(p); ServerManager.Instance.ServerInstance.WriteDomainObject(postl); } }
private PostList ListRecentPosts(string blogId, int maxPosts, DateTime? now, PostsResource.ListRequest.StatusEnum status, PostList previousPage) { if (previousPage != null && string.IsNullOrWhiteSpace(previousPage.NextPageToken)) { // The previous page was also the last page, so do nothing and return an empty list. return new PostList(); } var recentPostsRequest = GetService().Posts.List(blogId); if (now.HasValue) { recentPostsRequest.EndDate = now.Value; } recentPostsRequest.FetchImages = false; recentPostsRequest.MaxResults = maxPosts; recentPostsRequest.OrderBy = PostsResource.ListRequest.OrderByEnum.Published; recentPostsRequest.Status = status; recentPostsRequest.PageToken = previousPage?.NextPageToken; return recentPostsRequest.Execute(); }
public BlogServer(BlogServerOptions options) { if (options == null) { throw new System.ArgumentNullException("options"); } this.Options = options; CreateFolderSafe(this.Options.OutputFolder); // Initialize the log string logfilename = GetLogFilename(); Console.WriteLine("Log at: {0}", logfilename); if (this.Options.OverwriteLog) { LogStream = System.IO.File.CreateText(logfilename); } else { LogStream = System.IO.File.AppendText(logfilename); } LogStream.AutoFlush = true; this.WriteLog("----------------------------------------"); this.WriteLog("Start New Server Session "); this.WriteLog("----------------------------------------"); this.HostName = Environment.MachineName.ToLower(); // The Primary url is what will normally be used // However the server supports using localhost as well this.ServerUrlPrimary = string.Format("http://{0}:{1}/", HostName, this.Options.Port); this.ServerUrlSecondary = string.Format("http://{0}:{1}/", "localhost", this.Options.Port); this.WriteLog("Primary Url: {0}", this.ServerUrlPrimary); this.WriteLog("Secondary Url: {0}", this.ServerUrlSecondary); // The title of the blog will be based on the class name this.BlogTitle = "Untitled Blog"; // This server will contain a single user var adminuser = new BlogUser { Name = "admin", Password = "******" }; // Setup Collections this.BlogList = new List<UserBlogInfo>(); this.BlogUsers = new List<BlogUser>(); this.PostList = new PostList(); this.MediaObjectList = new MediaObjectList(); this.CategoryList = new CategoryList(); this.BlogUsers.Add(adminuser); // This server will contain a single blog this.BlogList.Add(new UserBlogInfo(adminuser.Name, this.ServerUrlPrimary, this.BlogTitle)); // Add Placeholder Content if (this.Options.CreateSampleContent && this.PostList.Count < 1) { if (this.CategoryList.Count < 1) { this.CategoryList.Add("0", "sports"); this.CategoryList.Add("0", "biology"); this.CategoryList.Add("0", "office supplies"); this.CategoryList.Add("0", "food"); this.CategoryList.Add("0", "tech"); } var cats1 = new[] {"sports","biology", "office supplies"}; var cats2 = new[] {"food"}; var cats3 = new[] {"food" }; var cats4 = new[] {"biology"}; string lipsum = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."; this.PostList.Add(new System.DateTime(2012, 12, 2), "1000 Amazing Uses for Staples", lipsum, cats1, true); this.PostList.Add(new System.DateTime(2012, 1, 15), "Why Pizza is Great", lipsum, cats2, true); this.PostList.Add(new System.DateTime(2013, 4, 10), "Sandwiches I have loved", lipsum, cats3, true); this.PostList.Add(new System.DateTime(2013, 3, 31), "Useful Things You Can Do With a Giraffe", lipsum, cats4, true); } this.HttpListener = new System.Net.HttpListener(); }