public async Task <ActionResult> Create([FromForm] StoryViewModel model) { try { var result = await storyService.CreateAsync(model); return(Ok(new { data = new { title = "Success", Msg = "Create success!" }, Success = true })); } catch { return(BadRequest(new { data = new { title = "Error", Msg = "Fail to create!" }, Success = false })); } }
public async Task <IActionResult> Add([FromBody] StoryViewModel ivm) { if (ivm != null) { // create a new story with the client-sent json data var story = Mapper.Map <Story>(ivm); // override any property that could be wise to set from server-side only story.CreatedDate = story.LastModifiedDate = DateTime.Now; story.UserId = await GetCurrentUserId(); // add the new story DbContext.Stories.Add(story); // persist the changes into the Database. DbContext.SaveChanges(); // return the newly-created story to the client. return(new JsonResult(Mapper.Map <StoryViewModel>(story), DefaultJsonSettings)); } // return a generic HTTP Status 500 (Not Found) if the client payload is invalid. return(new StatusCodeResult(500)); }
public IActionResult Update(int id, [FromBody] StoryViewModel ivm) { if (ivm != null) { var story = DbContext.Stories.Where(i => i.Id == id).FirstOrDefault(); if (story != null) { // handle the update (on per-property basis) story.UserId = ivm.UserId; story.Description = ivm.Description; story.Flags = ivm.Flags; story.Notes = ivm.Notes; story.Text = ivm.Text; story.Title = ivm.Title; story.Type = ivm.Type; // override any property that could be wise to set from server-side only story.LastModifiedDate = DateTime.Now; // persist the changes into the Database. DbContext.SaveChanges(); // return the updated story to the client. return(new JsonResult(Mapper.Map <StoryViewModel>(story), DefaultJsonSettings)); } } // return a HTTP Status 404 (Not Found) if we couldn't find a suitable story. return(NotFound(new { Error = String.Format("story ID {0} has not been found", id) })); }
public async Task ShouldIgnoreInvalidUrls() { var url = "invalidurl"; var dialog = Dialog; dialog.Setup(d => d.ConfirmAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())) .ReturnsAsync(true) .Verifiable(); var browser = Browser; browser.Setup(b => b.ShowInBrowserAsync(It.IsAny <Uri>(), It.IsAny <bool>())) .ReturnsAsync(true) .Verifiable(); var sut = new StoryViewModel(Share.Object, Browser.Object, dialog.Object); await sut.HandleExternalLinkAsync(url); browser.Verify(b => b.ShowInBrowserAsync(It.IsAny <Uri>(), It.IsAny <bool>()), Times.Never); dialog.Verify(d => d.ConfirmAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>()), Times.Never); }
public async Task <IHttpActionResult> GetFinishedTopicStory(string keyword) { keyword = keyword.Trim(); StoryViewModel random = await _storyOrchestrator.GetFinishedTopicStory(keyword); if (random.StoryId == Guid.Empty) { return(Content(HttpStatusCode.NotFound, "Error 404: No Stories Found Containing Given Word")); } else { string text = ""; foreach (StoryPartViewModel p in random.Parts.OrderBy(sp => sp.CreatedDateTime)) { text += p.PartText + "\n\n - Contributed by user " + p.Author + " on " + p.CreatedDateTime.ToShortDateString() + ".\n\n"; } ; text += "THE END"; Story story = new Story { StoryName = random.StoryName, Text = text }; return(Ok(story)); } }
public void GetTopStories_3daysAgo() { // Arrange const int storyCount = 60; var testStories = GenerateTestStories(storyCount); moqService.Setup(r => r.GetTopStoriesAsync(It.IsAny <int>())).ReturnsAsync(testStories); var expectedCandidate = testStories.TakeLast(1).First(); var expected = new StoryViewModel { Title = expectedCandidate.Title, Submitter = expectedCandidate.UserName, Url = expectedCandidate.Url, AgeDescription = "2 days ago" }; // Act var result = HomeController.GetTop(); //Assert Assert.AreEqual(TaskStatus.RanToCompletion, result.Status); var view = (ViewResult)result.Result; var actual = view.Model as List <StoryViewModel>; Assert.IsNotNull(actual, "Nothing returned."); Assert.AreEqual(storyCount, actual.Count, "Actual count different than expected."); AssertModel(expected, actual.TakeLast(1).First()); }
public void Delete_ShouldWork() { string modelTitle = "TestCreate"; string modelContent = "TestCreateContent"; StoryViewModel model = new StoryViewModel { Title = modelTitle, Content = modelContent, }; User user = new User { UserName = "******" }; var testOne = this.service.CreateAsync(modelTitle, user).GetAwaiter().GetResult(); var testTwo = this.service.CreateAsync(modelTitle, user).GetAwaiter().GetResult(); var result = service.GetAllStories(); Assert.Equal(2, result.Count()); this.service.DeleteAsync(testOne); result = service.GetAllStories(); Assert.Equal(1, result.Count()); Assert.Equal(testTwo, result.First().Id); this.service.DeleteAsync(testTwo); result = service.GetAllStories(); result.ShouldBeEmpty(); }
public async Task <StoryViewModel> Get(string hashId, Guid?userId) { var ids = new Hashids(minHashLength: 5); var storyId = ids.Decode(hashId).First(); var story = await StoriesDbContext.Stories.Include(s => s.User) .Include(s => s.Comments) .SingleOrDefaultAsync(s => s.Id == storyId); if (story == null) { return(null); } var userUpvoted = userId != null && await StoriesDbContext.Votes.AnyAsync(v => story.Id == v.StoryId && v.UserId == userId); var model = new StoryViewModel { Summary = MapToStorySummaryViewModel(story, hashId, userId, userUpvoted) }; var upvotedComments = await StoriesDbContext.Votes.Where(v => v.CommentId != null && v.UserId == userId) .Select(v => (int)v.CommentId) .ToListAsync(); foreach (var comment in story.Comments.OrderByDescending(c => c.Score?.Value).Where(c => c.ParentCommentId == null)) { model.Comments.Add(MapCommentToCommentViewModel(comment, upvotedComments)); } return(model); }
public IActionResult Details(string id) { try { StoryViewModel model = this.storyService.GetStoryByIdAsViewModel(id); if (model == null) { AddWarningNotification(Notifications.NotFound); return(Redirect("/")); } return(View(model)); } catch (System.Exception e) { logger.LogError(string.Format(SetLog.Error, CurrentUser.UserName, CurrentController, e.Message)); AddDangerNotification(string.Format(Notifications.Fail)); return(Redirect("/Stories")); } }
public IActionResult Details(string id) { StoryViewModel model = _repository.GetStoryByStoryId(id); IList <CommentViewModel> postComments = _repository.GetPostComments(id).ToList(); foreach (var comment in postComments) { comment.LikeCount = _repository.LikeDislikeCount("commentlike", comment.Id); comment.DislikeCount = _repository.LikeDislikeCount("commentdislike", comment.Id); comment.LikeOrDislike = _repository.LikeOrDislike("comment", comment.Id, _userManager.GetUserId(User)); //comment.NetLikeCount = likes - dislikes; //if (comment.Replies != null) comment.Replies.Clear(); IList <CommentViewModel> replies = _repository.GetReplies(comment.Id); comment.Replies = replies; //foreach (var reply in replies) //{ // var rep = _repository.GetReplyById(reply.Id); // comment.Replies.Add(rep); //} comment.ReplyCount = replies.Count; } postComments = postComments.OrderByDescending(x => x.LikeCount + x.DislikeCount).ToList(); model.Comments = postComments; //var post = _repository.GetStoryByStoryId(id); //Comments(post); return(View(model)); }
public static void ShouldMatch(this StoryViewModel vm, Story s) { vm.Title.ShouldEqual(s.Title); vm.State.ShouldEqual(s.State.ToString()); vm.Points.ShouldEqual(s.Points.ToString()); vm.Owner.ShouldEqual(s.Owner); }
public ActionResult New() { List <Sprint> allSprints = SprintService.GetAllSprints(_ScrumTimeEntities, SessionHelper.GetCurrentProductId(User.Identity.Name, Session)); Sprint noneSprint = new Sprint() { Name = "None", SprintId = -1 }; allSprints.Insert(0, noneSprint); int currentProductId = SessionHelper.GetCurrentProductId(User.Identity.Name, Session); Product product = _ScrumTimeEntities.Products.First <Product>(p => p.ProductId == currentProductId); StoryViewModel storyViewModel = new StoryViewModel() { StoryModel = new Story() { StoryId = 0, Narrative = "As a ...", Points = 0, Priority = 0, UserDefinedId = (product.Stories.Count() + 1).ToString() }, AllSprints = allSprints }; return(PartialView("Edit", storyViewModel)); }
public async Task <IActionResult> Index() { StoryViewModel storyViewModel = new StoryViewModel(); storyViewModel.biner = _context.sp_productbannerlatest(); storyViewModel.Sliders = _context.sp_productsliderlatestlist().Result; storyViewModel.lastproducts = _context.sp_productlatestlist(12); storyViewModel.products = _context.sp_productalllist(1, 20, null, null).Result; if (User.Identity.IsAuthenticated) { var iduser = this.User.FindFirstValue(ClaimTypes.NameIdentifier); storyViewModel.subfactors = _context.sp_subfactorlist(iduser).Result; foreach (var i in storyViewModel.subfactors) { storyViewModel.sumsubfactor += i.factorsubmoney * i.countfactorsub; storyViewModel.sumoffer += i.offpercent * i.countfactorsub; } } var menu = storyViewModel.menus = await _context.Menugroups.Include(m => m.Menus).Where(a => a.Istype == true) .ToListAsync(); return(View(storyViewModel)); }
public ActionResult EditStory(StoryViewModel model, int[] selectedItems) { StoryDetail detail = model.ConvertToStoryDetail(); int[] items = selectedItems; if (selectedItems == null) { items = new int[0]; } if (model.Title == null)//Invalid Model State, dirty approach { model.AllGroups = new GroupViewModel[0]; TaskResult <IEnumerable <GroupDetail> > groupDetailRequest = groupDataService.GetGroups(new DataRequest { StartPosition = 0, Count = 100 }); if (groupDetailRequest.Data != null) { model.AllGroups = groupDetailRequest.Data.Select(a => a.ConvertToGroupViewModel()); } return(View(model)); } detail.GroupDetails = items.Select(a => new GroupDetail { Id = a }); storyDataService.PostStory(detail); return(RedirectToAction("Index")); }
public async Task <ActionResult> Edit(/*[Bind(Exclude = "Picture")] */ StoryViewModel storyViewModel) { if (ModelState.IsValid) { var story = await db.Stories.FindAsync(storyViewModel.ID); story.Title = storyViewModel.Title; story.TimeForVotings = storyViewModel.TimeForVotings; story.TimeBetweenVotings = storyViewModel.TimeBetweenVotings; story.MaxChapterLength = storyViewModel.MaxChapterLength; story.MaxChaptersNumber = storyViewModel.MaxChaptersNumber; //byte[] imageData = FileUploader.GetFile("Picture", Request); //if(imageData != null && imageData.Count() > 0) //{ // story.Picture = imageData; //} db.Entry(story).State = EntityState.Modified; await db.SaveChangesAsync(); return(PartialView("~/Views/Home/Partials/_Story.cshtml", story)); } return(View()); }
public async Task <IActionResult> Index(string hashId) { StoryViewModel model = null; if (Guid.TryParse(CurrentUser.NameIdentifier, out Guid userId)) { model = await StoryService.Get(hashId, userId); if (CurrentUser.IsInRole(Roles.Moderator)) { model.Summary.IsDeletable = true; } } else { model = await StoryService.Get(hashId, null); } if (model == null) { return(NotFound()); } return(View(model)); }
private void AssertModel(StoryViewModel expected, StoryViewModel actual) { Assert.AreEqual(expected.Title, actual.Title, "Actual title is different then expected."); Assert.AreEqual(expected.Submitter, actual.Submitter, "Actual submitter is different then expected."); Assert.AreEqual(expected.Url, actual.Url, "Actual Url is different then expected."); Assert.AreEqual(expected.AgeDescription, actual.AgeDescription, "Actual AgeDescription is different then expected."); }
public async Task <IActionResult> DeleteComment(string commentId, string storyId) { try { await this.storyService.DeleteCommentAsync(commentId); logger.LogInformation( string.Format(SetLog.Delete, CurrentUser.UserName, CurrentController, $"StoryCommentFor-{storyId}" )); StoryViewModel model = storyService.GetStoryByIdAsViewModel(storyId); return(PartialView("_StoryComments", model.Comments)); } catch (System.Exception e) { logger.LogError(string.Format(SetLog.Error, CurrentUser.UserName, CurrentController, e.Message)); AddDangerNotification(Notifications.Fail); return(null); } }
public IViewComponentResult Invoke(StoryViewModel model = null) { if (model != null) { if (signInManager.IsSignedIn(UserClaimsPrincipal)) { if (model.Author.Id == userManager.GetUserId(UserClaimsPrincipal) || User.IsInRole("Administrator")) { return(View("Author", model)); } return(View("UserStoriesDetails", model)); } return(View("GuestStoriesDetails", model)); } if (signInManager.IsSignedIn(UserClaimsPrincipal)) { return(View("UserStoriesIndex")); } return(View("GuestStoriesIndex")); }
public async Task <ActionResult> SaveStory(StoryViewModel story) { try { story.UserId = SessionManager.CurrentUser.Id; story.PostedOn = DateTime.Now; var _story = Mapper.Map <StoryViewModel, Story>(story); story.Id = await StoryService.AddOrEditStory(_story); try { var _groupsUsers = await GroupService.GetGroupsUsers(story.Groups.Select(x => x.Id)); IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext <NotificationHub>(); hubContext.Clients.Clients(NotificationHub.GetUsersConnections(_groupsUsers.Where(x => x != story.UserId).ToList())).notify(new Notification { FromUser = SessionManager.CurrentUser.Name, StoryId = story.Id, Body = $"Posted story in group(s) {string.Join(",", story.Groups.Select(x => x.Name))}" }); } catch (Exception exx) { Logger.Error(exx); } return(Json(new ResponseData { Data = story }, JsonRequestBehavior.AllowGet)); } catch (Exception ex) { Logger.Error(ex); return(Json(ResponseData.ErrorDefault)); } }
public IActionResult EditStory(string id) { var model = new StoryViewModel(); model.Stories = new List <Story>(); model.Stories.Add(_reader.GetStory(id)); return(View(model)); }
public MainPage() { StoryViewModel storyViewModel = ServiceLocator.Current.GetInstance <StoryViewModel>(); InitializeComponent(); BindingContext = storyViewModel; _storyViewModel = storyViewModel; }
//Index Action public ActionResult Index(string input, int id = 0) { //als nieuw: start game + zet id in session //else: haal id uit session en start op if (id == 0) { var gameId = Session["gameId"] as int?; if (!gameId.HasValue) { return(RedirectToAction("FillDatabase")); } else { story = (Story)FindInDatabase("story", gameId.Value); player = (Player)FindInDatabase("player", gameId.Value); map = (Map)FindInDatabase("map", gameId.Value); } } else { story = (Story)FindInDatabase("story", id); player = (Player)FindInDatabase("player", id); map = (Map)FindInDatabase("map", id); } if (input == null) { storyViewModel = new StoryViewModel(story, player); return(View(storyViewModel)); } commandRepository = new CommandRepository(story, player); using (var context = ApplicationDbContext.Create()) { context.Stories.Attach(story); context.Players.Attach(player); if (!player.InBattle) { story.MyStory += commandRepository.GetCommandText(input); } else { story.MyStory += commandRepository.GetBattleCommandText(input); } story.MyStory += commandRepository.ExecuteCommand(input); story.MyStory += commandRepository.EndOfAction(); context.SaveChanges(); } storyViewModel = new StoryViewModel(story, player); return(View(storyViewModel)); }
public async Task <IActionResult> Update(StoryViewModel model) { if (!CurrentUser.Stories.Any(r => r.Id == model.Id)) { if (!User.IsInRole("Administrator")) { logger.LogInformation( string.Format(SetLog.NotTheAuthor, CurrentUser.UserName, CurrentController, model.Id )); AddDangerNotification(string.Format(Notifications.NotTheAuthor, model.Title)); return(Redirect($"/Stories/Details/{model.Id}")); } } try { if (this.ModelState.IsValid) { model.Content = model.Content.Replace("script", ""); await storyService.UpdateAsync(model); logger.LogInformation( string.Format(SetLog.UpdateSuccess, CurrentUser.UserName, CurrentController, model.Id )); AddSuccessNotification(string.Format(Notifications.UpdateSuccess, model.Title)); return(Redirect($"/Stories/Details/{model.Id}")); } else { AddDangerNotification(string.Format(Notifications.Fail)); return(View(model)); } } catch (System.Exception e) { logger.LogError(string.Format(SetLog.Error, CurrentUser.UserName, CurrentController, e.Message)); AddDangerNotification(string.Format(Notifications.Fail)); return(Redirect("/Stories")); } }
private static void NullChecker(StoryViewModel viewModel, Sprint sprint) { if (viewModel == null) { throw new ArgumentNullException($"{nameof(viewModel)} cannot be null"); } if (sprint == null) { throw new ArgumentNullException($"{nameof(sprint)} cannot be null"); } }
public async Task <ActionResult> ViewStory(Guid id) { StoryViewModel story = await _storyOrchestrator.GetStory(id); if (story.StoryId == Guid.Empty) { return(HttpNotFound()); } ViewBag.Message = story.StoryId; return(View(story)); }
public void When_GoToUrlCommand_Then_GoToUrlExecute() { browserServiceMock .Setup(x => x.OpenBrowser(It.IsAny<Uri>())) .Returns(Task.FromResult(true)); var storyViewModel = new StoryViewModel(navigationServiceMock.Object, hackerNewsServiceMock.Object, browserServiceMock.Object); storyViewModel.GoToUrlCommand.Execute(new Uri("https://www.twitch.tv/")); browserServiceMock.Verify(x => x.OpenBrowser(It.IsAny<Uri>()), Times.Once()); }
public IActionResult Edit(string id) { if (_repository.IsAuthor(User, id)) //Checking whether the author have permission to edit the story { StoryViewModel model = _repository.GetStoryByStoryId(id); return(View(model)); } ViewData["AllowAuthorError"] = "You are not allowed to access that URL"; //Otherwise returning to Index page IEnumerable <StoryViewModel> IndexModel = _repository.GetAllStories(); return(View("Index", IndexModel)); }
public async Task <IActionResult> GetStory(int?id) { if (id == null) { return(NotFound()); } Story story = await _boardService.GetStoryById(new ServiceContext { ContextId = "TEST" }, (int)id); StoryViewModel storyVM = story.EntityToViewModel(); return(View(storyVM)); }
public IActionResult EditStory(StoryViewModel model) { var result = _editor.EditStory(model.Stories[0]); if (result.Succeed) { return(RedirectToAction("Index", "Home")); } model.Warning = result.ErrorMessages[0]; return(View(model)); }
public ActionResult AddEditStory(int? storyId) { var model = new StoryViewModel { Id = 0 }; if (storyId.HasValue && storyId.Value > 0) { var story = _storyStore.GetStoriesWithGroups(s => s.Id == storyId.Value).FirstOrDefault(); if (story != null) { model.Id = story.Id; model.Title = story.Title; model.Description = story.Description; model.Content = story.Content; model.Groups = new List<GroupViewModel>((story.Groups ?? new List<Group>()).Select(g => new GroupViewModel { Id = g.Id, Title = g.Title, Description = g.Description, Content = g.Content ?? string.Empty, Stories = null })); model.GroupId = model.Groups.Count > 0 ? model.Groups.First().Id : 0; } } return View("_AddEditStory", model); }
public ActionResult SaveStory(StoryViewModel model) { if (!ModelState.IsValid) { return RedirectToAction("AddEditStory", "Home", new { storyId = model.Id }); } var userId = User.Identity.GetUserId(); var group = _groupStore.Get(model.GroupId, true); if (model.Id > 0) { var storyExistent = _storyStore.GetStory(model.Id, true); if (storyExistent != null) { storyExistent.Id = model.Id; storyExistent.Title = model.Title; storyExistent.Description = model.Description; storyExistent.Content = model.Content; storyExistent.UserId = userId; if (storyExistent.Groups == null) storyExistent.Groups = new List<Group>(); if (!storyExistent.Groups.Any(g => g.Id == model.GroupId)) storyExistent.Groups.Add(group); _storyStore.UpdateStory(storyExistent); } } else { var story = new Story { Id = model.Id, Title = model.Title, Description = model.Description, Content = model.Content, UserId = userId, Groups = new List<Group>() }; story.Groups.Add(group); _storyStore.AddStory(story); } return RedirectToAction("Index", "Home"); }
public StoryViewModel GetDetails(BaseInputModel inputModel) { if (!inputModel.Id.HasValue) inputModel.Id = 0; var story = _storyService.GetStoryByID((int)inputModel.Id); var vm = new StoryViewModel(story, CurrentUser); vm.AccountBalance = CurrentUser.AccountBalance; vm.StoryPrice = story.Price; return vm; }