public void EditPost_WithFile() { UserPost editPost = new UserPost { Verified = false, RecordStatusId = (int)RecordStatus.Active, IdUser = 2, Text = "Test", PostId = 1 }; Mock <HttpContextBase> contextMock = new Mock <HttpContextBase>(); Mock <HttpPostedFileBase> file = new Mock <HttpPostedFileBase>(); // The required properties from my Controller side MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("Hello")); file.Setup(x => x.InputStream).Returns(stream); file.Setup(x => x.ContentLength).Returns((int)stream.Length); file.Setup(x => x.FileName).Returns("Test.js"); string basePath = @"c:\yourPath\App"; contextMock.Setup(x => x.Server.MapPath(It.IsAny <String>())).Returns(basePath); file.Setup(x => x.SaveAs(It.IsAny <String>())).Verifiable(); string folderPath = basePath + HardcodedValues.UserFiles + _loginUser.UserId; var fakeFileSystem = new MockFileSystem(new Dictionary <string, MockFileData> { { folderPath, new MockDirectoryData() } }); _postsRepoMock.Setup(m => m.EditPost(editPost)).Returns(true); PostController controller = new PostController(_postsRepoMock.Object, _loginUser, fakeFileSystem); RequestContext rc = new RequestContext(contextMock.Object, new RouteData()); controller.ControllerContext = new ControllerContext(rc, controller); JsonResult result = controller.EditPost(editPost, file.Object); Assert.IsNotNull(result); Assert.IsNotNull(result.Data); Assert.IsTrue(result.Data is JsonResponseVM); Assert.IsTrue((result.Data as JsonResponseVM).Result == "OK"); Assert.IsTrue(!String.IsNullOrEmpty((result.Data as JsonResponseVM).Msg)); }
public async Task <IActionResult> OnPostAsync(int?id) { if (id == null) { return(NotFound()); } UserPost = await _context.UserPost.FindAsync(id); if (UserPost != null) { _context.UserPost.Remove(UserPost); await _context.SaveChangesAsync(); } return(RedirectToPage("./Index")); }
/// <summary> /// Create a new post and add it to the database /// </summary> /// <param name="post">A UserPostDTO to create the new entity</param> /// <returns>Returns the DTO if successful</returns> public async Task <UserPostDTO> Create(UserPostDTO post) { var timeNow = DateTime.UtcNow; var newPost = new UserPost() { UserId = post.UserId, Caption = post.Caption, Created = timeNow, Modified = timeNow }; _context.Entry(newPost).State = EntityState.Added; await _context.SaveChangesAsync(); return(post); }
public async Task <ActionResult> CommentAsync(string id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } UserPost item = await DocumentDBRepository <UserPost> .GetItemAsync(id); if (item == null) { return(HttpNotFound()); } ViewBag.PostId = item.PostId; return(View()); }
public static async Task <string> Register(string email, string password) { string hashedPass = StringHash.HashedPassword(password); string result = ""; var response = await UserAPI_Logic.RegisterUser(email, hashedPass); if (response[0] == "Token") { using (SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation)) { conn.CreateTable <UserPost>(); try { string dekoduotasTokenas = StringHash.DecryptToken(response[1]); var user = conn.Find <UserPost>(email); if (user == null) { UserPost post = new UserPost() { Token = dekoduotasTokenas, Email = email, Password = password }; conn.InsertOrReplace(post); } else { /* if (response[1] != user.Token) * { * //Padaryt tokeno update * }*/ } } catch (NullReferenceException nrex) { } conn.Close(); } } else { result = response[1]; } return(result); }
public static void PostToUser(int fromUserId, int toUserId, string content) { var context = new SocialNetworkContext(); var sender = context.Users.Find(fromUserId); var recipient = context.Users.Find(toUserId); var post = new UserPost() { Content = content, Author = sender, PostedOn = DateTime.Now, User = recipient }; context.UserPosts.Add(post); context.SaveChanges(); }
public int InsertUserPosts(UserPost obj) { try { using (var context = _dbContextFactory.CreateConnection()) { obj = context.UserPosts.Add(obj); context.SaveChanges(); return(obj.PostId); } } catch (Exception ex) { _Logger.Error(ex.Message, ex); throw ex; } }
public void DeserializeUserPosts(User user) { using (var writer = new StreamWriter(dir + $"/data/userposts/{user.Name}.txt", true)) { }; // Create if doesn't exist using (var reader = new StreamReader(dir + $"/data/userposts/{user.Name}.txt")) { while (!reader.EndOfStream) { var values = reader.ReadLine().Split('|'); var post = new UserPost() { ID = int.Parse(values[0]), DatePosted = DateTime.Parse(values[1]), Community = Communities[values[2]], Text = values[3], User = user }; Posts[post.ID] = post; user.Posts.Push(post); } } }
public IHttpActionResult postVacancyPosts([FromBody] UserPost uPost) { try { String query = " insert into Userposts(userID,text,privacy,Video,picture,upVote,downVote)" + "VALUES(" + uPost.userID + ",'" + uPost.text + "','" + uPost.privacy + "','" + uPost.Video + "','" + uPost.picture + "','" + uPost.upVote + "','" + uPost.downVote + "'); "; c = new SqlCommand(query, con); con.Open(); c.ExecuteNonQuery(); con.Close(); return(Ok()); } catch (Exception e) { return(NotFound()); } }
private async Task UpdateChannels(Dictionary <string, List <UserPost> > newPosts, VideosResource.ListRequest req) { for (var i = 0; i < newPosts.Keys.Count; i += 50) { req.Id = string.Join(",", newPosts.Keys.Skip(i).Take(50)); var response = await req.ExecuteAsync(); foreach (var vid in response.Items) { foreach (var upost in newPosts[vid.Id]) { upost.ChannelID = vid.Snippet.ChannelId; upost.ChannelName = vid.Snippet.ChannelTitle; UserPost.UpdatePost(upost); } } } }
public bool EditPost(UserPost editPost) { UserPost original = _context.UserPosts .FirstOrDefault(x => x.PostId == editPost.PostId && x.IdUser == editPost.IdUser && (x.Verified || editPost.Verified)); if (original != null) { editPost.PostDateTime = original.PostDateTime; editPost.SharedFromPostId = original.SharedFromPostId; editPost.RecordStatusId = original.RecordStatusId; editPost.LastUpdate = DateTime.Now; _context.Entry(original).State = System.Data.Entity.EntityState.Detached; _context.Entry(editPost).State = System.Data.Entity.EntityState.Modified; return(SaveChanges()); } return(false); }
public ActionResult PostMessage(string message, DateTime dateSent) { var incomingMessage = message; var user = from a in db.UserInfos where a.email == User.Identity.Name select a.userId; UserPost userPost = new UserPost { message = message, time = dateSent, userId = user.ToList()[0] }; db.UserPosts.Add(userPost); db.SaveChanges(); return(Json(Url.Action("UserProfile", "UserInfoes"))); }
private void getPosts(List <UserPost> list, SqlDataReader reader) { while (reader.Read()) { int id = Int32.Parse(reader[0].ToString()); int Uid = Int32.Parse(reader[1].ToString()); int privacy = Int32.Parse(reader[3].ToString()); int upVote = Int32.Parse(reader[4].ToString()); int downVote = Int32.Parse(reader[5].ToString()); Upost = new UserPost(id, Uid, upVote, downVote, reader[2].ToString(), reader[6].ToString(), reader[7].ToString(), privacy); list.Add(Upost); } reader.Close(); }
public async Task <bool> Update(UserPost post) { var r = from x in await All() where x.Id == post.Id select x; if (await r.AnyAsync()) { var v = await r.FirstAsync(); v.PostType = post.PostType; v.UserId = post.UserId; _context.Entry(v).State = EntityState.Modified; await _context.SaveChangesAsync(); return(true); } return(false); }
public ActionResult Create([Bind(Include = "ID,Title,Description,POST,Rating,Date_Posted,User_ID")] UserPost userPost, HttpPostedFileBase image) { userPost.User_ID = (int)Session["id"]; if (ModelState.IsValid) { if (image != null) { userPost.POST = new byte[image.ContentLength]; image.InputStream.Read(userPost.POST, 0, image.ContentLength); } db.UserPosts.Add(userPost); db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.User_ID = new SelectList(db.Users, "ID", "First_Name", userPost.User_ID); return(View(userPost)); }
public UserPost Update(int id) { try { using (var context = _dbContextFactory.CreateConnection()) { UserPost User = context.UserPosts.Where(x => x.PostId == id).First(); User.Status = false; context.SaveChanges(); return(User); } } catch (Exception ex) { _Logger.Error(ex.Message, ex); throw ex; } }
public ActionResult AddPost(HttpPostedFileBase file, ConsumedModels userPost, string NewsText) { var path = ""; //for path to save if (file != null) //check file is null or not { if (file.ContentLength > 0) //check length of bytes are greater then zero or not { //სურათის სახელის წამოღება var pictureName = Path.GetFileName(file.FileName); pictureName = Random32(); //სურათის სახელის წამოღება extension-ისთვის string fileNameExt = Path.GetFileName(file.FileName); string pictureExtension = Path.GetExtension(fileNameExt); //ფაილების შემოწმება, რა ტიპის ფაილია. if (Path.GetExtension(file.FileName).ToLower() == ".jpg" || Path.GetExtension(file.FileName).ToLower() == ".png" || Path.GetExtension(file.FileName).ToLower() == ".gif" || Path.GetExtension(file.FileName).ToLower() == ".jpeg") { path = Path.Combine(Server.MapPath("~/Content/Images"), pictureName + pictureExtension); file.SaveAs(path); } UserRegistration user = (UserRegistration)Session["user"]; var thisLoggedUser = db.UserRegistrations.FirstOrDefault(x => x.ID == user.ID); UserPost UserPst = new UserPost(); UserPst.UserID = thisLoggedUser.ID; UserPst.NewsTitle = userPost.NewsTitle; UserPst.AuthorName = userPost.AuthorName; UserPst.AuthorSurName = userPost.AuthorSurName; UserPst.NewsText = NewsText; UserPst.PicturePath = path; UserPst.PictureName = pictureName; UserPst.PictureExtension = pictureExtension; UserPst.CreateDate = DateTime.Now; db.UserPosts.InsertOnSubmit(UserPst); db.SubmitChanges(); } } return(RedirectToAction("AddPost", "Admin")); }
public User PostUser(UserPost userPost) { User user = null; using (var con = new NpgsqlConnection(connectionString)) { con.Open(); using (var cmd = new NpgsqlCommand($"INSERT INTO users (user_name,first_name,last_name,restaurant_id) VALUES (@user_name,@first_name,@last_name,@restaurant_id)", con)) { cmd.Parameters.AddWithValue("user_name", userPost.User_name); cmd.Parameters.AddWithValue("first_name", userPost.First_name); cmd.Parameters.AddWithValue("last_name", userPost.Last_name); cmd.Parameters.AddWithValue("restaurant_id", userPost.Restaurant_id); cmd.ExecuteNonQuery(); } return(user); } }
//[ValidateAntiForgeryToken] public async Task <ActionResult> EditAsync([Bind(Include = "PostId,Heading,Content,Tag,CreatedOn,Author")] UserPost item) { if (ModelState.IsValid) { UserPost post = await DocumentDBRepository <UserPost> .GetItemAsync(item.PostId); post.Heading = item.Heading; post.Content = item.Content; post.Tag = item.Tag; post.CreatedOn = item.CreatedOn; post.Author = item.Author; await DocumentDBRepository <UserPost> .UpdateItemAsync(item.PostId, item); return(RedirectToAction("Index")); } return(View(item)); }
public bool UpdateUser(UserPost post) { if (!IsAuthorized()) { ReAuthorise(); } StringBuilder localBoxUrl = new StringBuilder(); localBoxUrl.Append(_localBox.BaseUrl + "lox_api/user"); string AccessToken = _authorization.AccessToken; var handler = new HttpClientHandler { }; using (var httpClient = new HttpClient(handler)) { httpClient.MaxResponseContentBufferSize = int.MaxValue; httpClient.DefaultRequestHeaders.ExpectContinue = false; httpClient.DefaultRequestHeaders.Add("x-li-format", "json"); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Uri.EscapeDataString(AccessToken)); var jsonString = JsonConvert.SerializeObject(post); var httpRequestMessage = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri(localBoxUrl.ToString()), Content = new StringContent(jsonString) }; try { var response = httpClient.SendAsync(httpRequestMessage).Result; return(response.IsSuccessStatusCode); } catch (Exception ex) { Insights.Report(ex); return(false); } } }
//[ValidateAntiForgeryToken] public async Task <ActionResult> CommentAsync(PostComment comment) { if (ModelState.IsValid) { comment.UserName = User.Identity.Name; UserPost item = await DocumentDBRepository <UserPost> .GetItemAsync(comment.PostId); if (item.Comments == null) { item.Comments = new List <PostComment>(); } item.Comments.Add(comment); await DocumentDBRepository <UserPost> .UpdateItemAsync(item.PostId, item); return(RedirectToAction("Index")); } return(View(comment)); }
public JsonResult EditPost(UserPost editPost, HttpPostedFileBase javascriptFile = null) { editPost.IdUser = _loginUser.UserId; if (javascriptFile != null && Path.GetExtension(javascriptFile.FileName) == ".js") { editPost.Verified = false; editPost.CanvasJavascriptFilePath = "~/Content/UserFiles/" + _loginUser.UserId + "/" + Guid.NewGuid().ToString() + ".js"; } if (ModelState.IsValid && _postsRepo.EditPost(editPost)) { if (javascriptFile != null && !String.IsNullOrEmpty(editPost.CanvasJavascriptFilePath)) { string folderPath = Server.MapPath(HardcodedValues.UserFiles + _loginUser.UserId); if (!_fileSystem.Directory.Exists(folderPath)) { _fileSystem.Directory.CreateDirectory(folderPath); } javascriptFile.SaveAs(Server.MapPath(editPost.CanvasJavascriptFilePath)); return(Json(new JsonResponseVM { Result = "OK", PostId = editPost.PostId, Msg = "Vaša objava će biti dostupna nakon potvrde administratora" })); } return(Json(new JsonResponseVM { Result = "OK", PostId = editPost.PostId })); } else if (ModelState.Values.Any(x => x.Errors.Count > 0)) { return(Json(new JsonResponseVM { Result = "ERROR", Msg = ModelState.Values.First(x => x.Errors.Count > 0).Errors.First().ErrorMessage })); } else { return(Json(new JsonResponseVM { Result = "ERROR", Msg = "Traženi podatak ne postoji ili nemate potrebna prava." })); } }
public async Task <ActionResult <User> > Update([FromBody] UserPost model, int id) { if (!ModelState.IsValid) { return(BadRequest(model)); } User user = await db.User .Where(k => k.id_user == id) .FirstOrDefaultAsync(); if (user == null) { return(NotFound(new { ok = false, err = "The id " + id + " does not exist in the records" })); } AssignsControllers.AssingUser(model, user, "PUT"); try { await db.SaveChangesAsync(); } catch (System.Exception err) { return(BadRequest(new { ok = false, err = err.InnerException.Message })); } return(Ok(new { ok = true, user = new { user.name, user.email, user.role, user.status } })); }
public ActionResult <IEnumerable <string> > PutUser(long id, UserPost userPost) { if (!auth.CheckIfDebugPermissions(userPost)) { return(Unauthorized()); } //TODO UserPost überprüfen var result = model.PutUser(id, userPost); if (result) { return(NoContent()); } else { return(NotFound()); } }
public IActionResult Add(UserPost userPost) { if (ModelState.IsValid) { Post postToCreate = new Post() { idea = userPost.Idea, user_id = (int)HttpContext.Session.GetInt32("id") }; _context.posts.Add(postToCreate); _context.SaveChanges(); return(RedirectToAction("Ideas", "Post")); } return(RedirectToAction("Ideas")); }
public void GetPost() { UserPost newPost = new UserPost { Verified = false, RecordStatusId = (int)RecordStatus.Active, IdUser = 2, Text = "Test", PostId = 1 }; _postsRepoMock.Setup(m => m.GetPost(newPost.PostId)).Returns(newPost); PostController controller = new PostController(_postsRepoMock.Object, _loginUser); JsonResult result = controller.GetPost(newPost.PostId); Assert.IsNotNull(result); Assert.IsNotNull(result.Data); Assert.IsTrue(result.Data is UserPost); }
public async Task PatchPerformanceTest() { var restClient = new RestClientDotNet.RestClient(new NewtonsoftSerializationAdapter(), new Uri("https://jsonplaceholder.typicode.com")); UserPost userPost = null; var startTime = DateTime.Now; for (var i = 0; i < 15; i++) { userPost = await restClient.PatchAsync <UserPost, UserPost>(new UserPost { title = "Moops" }, "/posts/1"); } var restClientTotalMilliseconds = (DateTime.Now - startTime).TotalMilliseconds; Console.WriteLine($"RestClient Get : Total Milliseconds:{ restClientTotalMilliseconds}"); startTime = DateTime.Now; var restSharpClient = new RestSharp.RestClient("https://jsonplaceholder.typicode.com"); var request = new RestRequest(Method.PATCH) { Resource = "/posts/1" }; for (var i = 0; i < 15; i++) { var taskCompletionSource = new TaskCompletionSource <UserPost>(); var response = restSharpClient.ExecuteAsync <UserPost>(request, (a) => { taskCompletionSource.SetResult(a.Data); }); userPost = await taskCompletionSource.Task; } var restSharpTotalMilliseconds = (DateTime.Now - startTime).TotalMilliseconds; Console.WriteLine($"RestSharp Get : Total Milliseconds:{ restSharpTotalMilliseconds}"); Assert.IsTrue(restClientTotalMilliseconds < restSharpTotalMilliseconds, "😞 RestSharp wins."); Console.WriteLine("🏆 RestClient Wins!!!"); }
public async Task <Unit> Handle(Command request, CancellationToken cancellationToken) { // handler logic var posts = await _context.Posts.FindAsync(request.Id); if (posts == null) { throw new RestException(HttpStatusCode.NotFound, new { Post = "Could not find Post" }); } var user = await _context.Users.SingleOrDefaultAsync(x => x.UserName == _userAccessor.GetCurrentUsername()); var liked = await _context.UserPosts .SingleOrDefaultAsync(x => x.PostId == posts.Id && x.AppUserId == user.Id); if (liked != null) { throw new RestException(HttpStatusCode.BadRequest, new { Post = "Already liked this posts" }); } liked = new UserPost { Post = posts, AppUser = user, IsHost = false, DateJoined = DateTime.Now }; _context.UserPosts.Add(liked); var success = await _context.SaveChangesAsync() > 0; if (success) { return(Unit.Value); } throw new Exception("Problem saving changes"); }
public ActionResult Edit(int?id) { if (!id.HasValue) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } var post = UserPost.GetPostById(id.Value); if (post == null) { return(HttpNotFound()); } if ((post.ExpirationDate.HasValue && post.ExpirationDate.Value.CompareTo(DateTime.Today) < 0) || post.Deleted) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } return(View(post)); }
public async Task <ActionResult> DetailsAsync(string id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } UserPost item = await DocumentDBRepository <UserPost> .GetItemAsync(id); if (item == null) { return(HttpNotFound()); } if (item.Comments == null) { item.Comments = new List <PostComment>(); } return(View(item)); }
public bool UpdateUser(UserPost post) { if (!IsAuthorized ()) { ReAuthorise (); } StringBuilder localBoxUrl = new StringBuilder(); localBoxUrl.Append(_localBox.BaseUrl + "lox_api/user"); string AccessToken = _authorization.AccessToken; var handler = new HttpClientHandler {}; using (var httpClient = new HttpClient(handler)) { httpClient.MaxResponseContentBufferSize = int.MaxValue; httpClient.DefaultRequestHeaders.ExpectContinue = false; httpClient.DefaultRequestHeaders.Add("x-li-format", "json"); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( "Bearer", Uri.EscapeDataString (AccessToken)); var jsonString = JsonConvert.SerializeObject(post); var httpRequestMessage = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri(localBoxUrl.ToString()), Content = new StringContent(jsonString) }; try { var response = httpClient.SendAsync(httpRequestMessage).Result; return response.IsSuccessStatusCode; } catch (Exception ex){ Insights.Report(ex); return false; } } }
public ActionResult Index(WhiteBoardModel WhiteBoards, IEnumerable<HttpPostedFileBase> Images, IEnumerable<HttpPostedFileBase> Files) { if (Session["UserId"] != null) { List<YearsforFaculty> Years = new List<YearsforFaculty>(); int UserId = Convert.ToInt32(Session["UserId"]); View_UserDetails Userdetails = UserDetailsViewService.GetUserByUserId(Convert.ToInt32(UserId)); List<Batches> Batches = new List<Batches>(); int PostId = 0; if (ModelState.IsValid) { if (WhiteBoards.selections == "Visible To All") { UserPost UserPosts = new UserPost() { EventId = WhiteBoards.EventId, ViewBy = WhiteBoards.selections, UserId = UserId, UserMessage = WhiteBoards.Message, Status = true, CreatedOn = DateTime.Now }; PostId = UserPostService.InsertUserPosts(UserPosts); UserPosts_Visisble UserPostVisible = new UserPosts_Visisble() { PostId = PostId, Batch = WhiteBoards.selections, Branch = WhiteBoards.Degree, Degreee = Userdetails.CourseId, CreatedOn = DateTime.Now, Status = true, BatchTo = (WhiteBoards.WorkFromTo) }; UserPostVisibleServices.Create(UserPostVisible); } else { UserPost UserPosts = new UserPost() { EventId = WhiteBoards.EventId, UserId = UserId, UserMessage = WhiteBoards.Message, ViewBy = WhiteBoards.Batchyear, Status = true, CreatedOn = DateTime.Now }; PostId = UserPostService.InsertUserPosts(UserPosts); UserPosts_Visisble UserPostVisible = new UserPosts_Visisble() { PostId = PostId, Batch = WhiteBoards.WorkFromYear, Branch = WhiteBoards.Degree, Degreee = Userdetails.CourseId, CreatedOn = DateTime.Now, Status = true, BatchTo = (WhiteBoards.WorkFromTo) }; UserPostVisibleServices.Create(UserPostVisible); } if (Images != null) { foreach (var Pictures in Images) { if (Pictures != null) { var fileName = Path.GetFileName(Pictures.FileName); var path = Path.Combine(Server.MapPath("~/UserPostingImages/" + fileName)); Pictures.SaveAs(path); var FilePath = "/UserPostingImages/" + fileName; UserPost_Images UserImages = new UserPost_Images() { PostId = PostId, ImagePath = FilePath, CreatedOn = DateTime.Now, Status = true }; UserpostPictureServices.Create(UserImages); } } } ViewBag.Userdata = GenericMethods.GetUserdetailsonFaculty(UserId, Convert.ToString(Userdetails.Batch)); return RedirectToAction("Index", "WhiteBoard", new { area = "Faculty" }); } if (Userdetails.RoleId == "2") { for (int? i = Userdetails.WorkingFrom; i <= Userdetails.WorkingTo; i++) { Years.Add(new YearsforFaculty { Year = Convert.ToString(i) }); } } WhiteBoardModel WhiteBoard = new WhiteBoardModel() { Viewdetails = Batches, RoleId = Userdetails.RoleId, Batch = Userdetails.Batch, Stream = Userdetails.CourseName, Events = EventCategoryService.GetCategorys(), yearsList = Years, Coursecategorys = CategoryServices.GetAllCourseCategories(), }; ViewBag.Userdata = GenericMethods.GetUserdetailsonFaculty(UserId, Convert.ToString(Userdetails.Batch)); return View(WhiteBoard); } return RedirectToAction(LoginPages.Login, LoginPages.Account, new { area = "" }); }