public ActionResult Add(int id) { //TODO: Validation var user = _users.GetUserFromUserIdentity(Request.GetIdentity()); var comment = new Comment { User = user, Time = DateTime.UtcNow, Text = Request.Form["comment"] }; _activities.Add(id, comment); return(Redirect(string.Format("/idea/{0}#{1}", id, comment.Id))); }
public Activity Add(Activity activity) { var activityType = _activityTypeRepository.Get(activity.ActivityTypeId); if (activityType == null) { throw new Exception("Invalid activity type"); } switch (activityType.RecordType) { case RecordType.DurationOnly: if (activity.Duration < 0) { throw new Exception("Duration must be greater than 0"); } break; case RecordType.DurationAndDistance: if (activity.Distance < 0) { throw new Exception("Distance must be greater than 0"); } if (activity.Duration < 0) { throw new Exception("Duration must be greater than 0"); } break; } return(_activityRepository.Add(activity)); }
public async Task <int> Handle(CreateActivityCommand request, CancellationToken cancellationToken) { var activity = new Domain.AggregatesModel.ActivityAggregate.Activity( request.Creator, request.Title, request.Content, request.EndRegisterTime, request.ActivityStartTime, request.ActivityEndTime, request.Address, request.CategoryId, request.AddressVisibleRuleId, request.LimitsNum); var entity = _repository.Add(activity); var result = await _repository.UnitOfWork.SaveEntitiesAsync(); if (result) { var index = new ActivityIndex(entity.Id, entity.Title, entity.Content, entity.CreateTime, entity.EndRegisterTime, entity.ActivityStartTime, entity.ActivityEndTime, entity.Address.City, entity.Address.County, entity.Address.DetailAddress, entity.Address.Latitude, entity.Address.Longitude, entity.CategoryId, request.Creator.UserId, request.Creator.Nickname); _indexService.CreateIndex(index); } return(result ? entity.Id : 0); }
public void Post([FromBody] CreateActivityModel activity) { var entity = Activity.Create(activity.Name, activity.Description, activity.Type, activity.DashboardId, activity.StartingTime, activity.EndingTime); //Activity.AddActivity(entity); _repository.Add(entity); }
/// <summary> /// 添加 /// </summary> /// <param name="activityAddViewModel"></param> /// <returns></returns> public int AddActivity(ActivityAddViewModel activityAddViewModel) { var aAddInsertModel = _IMapper.Map <ActivityAddViewModel, Activity>(activityAddViewModel); //var a = new InfoRelationShip(); _activityRepository.Add(aAddInsertModel); return(_activityRepository.SaveChanges()); }
public IActionResult PostActivity([FromBody] Activity activity) { using (var scope = new TransactionScope()) { _activityRepository.Add(activity); scope.Complete(); return(CreatedAtAction(nameof(GetActivityById), new { id = activity.ActivityId }, activity)); } }
public IActionResult Add([FromBody] Activity model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } return(Ok(_activityRepository.Add(model))); }
public bool AddActivity(Activity activity) { if (_repository.Get(filter => filter.Name == activity.Name).Count() >= 1) { return(false); } _repository.Add(activity); _uow.Commit(); return(true); }
public Activity Add(Activity Activity) { var activityType = _activityTypeRepo.Get(Activity.ActivityTypeId); if (activityType.RecordType == RecordType.DurationAndDistance && Activity.Distance <= 0) { throw new ApplicationException("You must supply a Distance for this activity."); } _activityRepo.Add(Activity); return(Activity); }
public void EndTrack() { var exitActivity = new Activity { Recipient = AppName, Action = Constant.AppExitAction, Level = ActivityLevel.Application, Time = DateTime.Now, }; _activityRepository.Add(exitActivity); var startActivity = _activityRepository .GetActivities() .Where(a => a.Recipient == AppName && a.Action == Constant.AppStartupAction) .OrderByDescending(a => a.Time) .FirstOrDefault(); if (startActivity != null) { var duration = exitActivity.Time - startActivity.Time; _operationDurationRepository.Add(new OperationDuration { Level = ActivityLevel.Application, Duration = duration, Action = Constant.RunningApp }); } _tokenDictionary.Clear(); }
public void Save(PersonActivity data) { var release = repository.FindBy(data._id); if (release == null) { repository.Add(data); } else { repository.Save(data); } }
public Activity Add(Activity Activity) { // retrieve the ActivityType so we can check var activityType = _activityTypeRepo.Get(Activity.ActivityTypeId); // for a DurationAndDistance activity, you must supply a Distance if (activityType.RecordType == RecordType.DurationAndDistance && Activity.Distance <= 0) { throw new ApplicationException("You must supply a Distance for this activity."); } _activityRepo.Add(Activity); return(Activity); }
public Activity Add(Activity newActivity) //create { var activityType = _activityTypeRepository.Get(newActivity.ActivityTypeId); if (activityType.RecordType == RecordType.DurationAndDistance && newActivity.Distance <= 0) { throw new Exception("You must supply a distance for this activity."); } if (newActivity.Duration <= 0) { throw new ApplicationException("You must supply a Duration for this activity."); } _activityRepository.Add(newActivity); return(newActivity); }
public async Task <ActivityDto> Handle(CreateActivityCommand request, CancellationToken cancellationToken) { var activityModel = _activityDxos.MapCreateRequesttoActivity(request); _activityRepository.Add(activityModel); if (await _activityRepository.SaveChangesAsync() == 0) { throw new ApplicationException("Insertion to database failed"); } await _mediator.Publish(new ActivityCreatedEvent(activityModel.Id), cancellationToken); var activityDto = _activityDxos.MapActivityDto(activityModel); return(activityDto); }
public IActionResult Post([FromBody] ActivityModel activity) { var act = Mapper.Map <Activity>(activity); act.ActivityId = (_activityRepository.GetMaxId() + 1).ToString(); act.ClassroomId = activity.ClassroomId; act.SchoolId = activity.SchoolId; act.Name = activity.Name; act.Date = activity.Date; _activityRepository.Add(act); var result = _activityRepository.Fetch(); var results = Mapper.Map <IEnumerable <ActivityModel> >(result); return(new ObjectResult(results)); }
public IActionResult CreateActivity([FromBody] ActivityCreateDto activityCreateDto) { try { // Validation if (activityCreateDto == null) { return(BadRequest()); } if (!_activityTypeRepository.ValidActivityType(activityCreateDto.Type)) { return(BadRequest("Type is not valid")); } ; if (activityCreateDto.ExpirationDate != null && activityCreateDto.ExpirationDate <= DateTime.Today) { return(BadRequest("ExpirationDate needs to be in the future")); } // Create the new object var activityEntity = Mapper.Map <Activity>(activityCreateDto); activityEntity.UserId = User.FindFirst(JwtRegisteredClaimNames.Sid).Value; activityEntity.CreatedDate = DateTime.Now; if (activityEntity.PublishDate == null) { activityEntity.PublishDate = DateTime.Parse("9999-12-31"); } _activityRepository.Add(activityEntity); if (!_activityRepository.Save()) { return(StatusCode(500, "A problem happend while handeling your request.")); } var activityDtoToReturn = Mapper.Map <ActivityDto>(activityEntity); return(CreatedAtRoute("GetActivity", new { id = activityDtoToReturn.Id }, activityDtoToReturn)); } catch (Exception ex) { _logger.LogCritical($"An exception was thrown: ", ex); return(StatusCode(500, "A problem happend while handeling your request.")); } }
public CommentModule(IIdeaRepository ideas, IActivityRepository activities) : base("/idea") { _ideas = ideas; _activities = activities; Post["/{idea}/comment"] = _ => { int id = _.Idea; var comment = new Comment { Time = DateTime.UtcNow, Text = Request.Form.comment }; _activities.Add(id, comment); return(Response.AsRedirect(string.Format("/idea/{0}#{1}", id, comment.Id))); }; /* * Get["/{idea}/comment/{id}"] = parameters => * { * using (var db = new IdeastrikeContext()) * { * int id = parameters.id; * int idea = parameters.idea; * var comment = db.Comments.FirstOrDefault(i => i.Id == id && i.IdeaId == idea); * return string.Format("Comment Id:{0}", comment.Id); * } * }; * * Get["/{idea}/comment/{id}/delete"] = parameters => * { * using (var db = new IdeastrikeContext()) * { * int id = parameters.id; * int idea = parameters.idea; * * var comment = db.Comments.FirstOrDefault(i => i.Id == id && i.IdeaId == idea); * db.Comments.Remove(comment); * db.SaveChanges(); * return string.Format("Deleted Comment {0} for Idea {1}", id, idea); * } * };*/ }
public CommentModule(IIdeaRepository ideas, IActivityRepository activities, IUserRepository users) : base("/comment") { this.RequiresAuthentication(); _ideas = ideas; _activities = activities; _users = users; Post["/{idea}/add"] = parameters => { int id = parameters.Idea; var user = _users.FindBy(u => u.UserName == Context.CurrentUser.UserName).FirstOrDefault(); if (user == null) { return(Response.AsRedirect(string.Format("/idea/{0}", id))); //TODO: Problem looking up the user? Return an error } var text = Request.Form.comment; if (string.IsNullOrEmpty(text)) // additional validation required { return(Response.AsJson(new { result = "Error" })); } var comment = new Comment { User = user, Time = DateTime.UtcNow, Text = Request.Form.comment }; _activities.Add(id, comment); // why not return JSON here and leave it up to client to render inline? return(Response.AsRedirect(string.Format("/idea/{0}#{1}", id, comment.Id))); }; // TODO: shouldn't these actually sit under the Comment root // TODO: user should be able to edit their own comment Post["/{id}/edit"] = parameters => Response.AsJson(new { result = "Error" }); // TODO: user should be able to remove their own comment Post["/{id}/delete"] = parameters => Response.AsJson(new { result = "Error" }); }
public CommentModule(IIdeaRepository ideas, IActivityRepository activities) : base("/idea") { _ideas = ideas; _activities = activities; Post["/{idea}/comment"] = _ => { int id = _.Idea; var comment = new Comment { Time = DateTime.UtcNow, Text = Request.Form.comment }; _activities.Add(id, comment); return Response.AsRedirect(string.Format("/idea/{0}#{1}", id, comment.Id)); }; /* Get["/{idea}/comment/{id}"] = parameters => { using (var db = new IdeastrikeContext()) { int id = parameters.id; int idea = parameters.idea; var comment = db.Comments.FirstOrDefault(i => i.Id == id && i.IdeaId == idea); return string.Format("Comment Id:{0}", comment.Id); } }; Get["/{idea}/comment/{id}/delete"] = parameters => { using (var db = new IdeastrikeContext()) { int id = parameters.id; int idea = parameters.idea; var comment = db.Comments.FirstOrDefault(i => i.Id == id && i.IdeaId == idea); db.Comments.Remove(comment); db.SaveChanges(); return string.Format("Deleted Comment {0} for Idea {1}", id, idea); } };*/ }
public IActionResult Post([FromBody] ActivityModel newActivity) { try { // TODO: convert the newAuthor to a domain model // add the new author _activityRepository.Add(newActivity.ToDomainModel()); } catch (System.Exception ex) { ModelState.AddModelError("AddActivity", ex.GetBaseException().Message); return(BadRequest(ModelState)); } // return a 201 Created status. This will also add a "location" header // with the URI of the new author. E.g., /api/authors/99, if the new is 99 return(CreatedAtAction("Get", new { Id = newActivity.Id }, newActivity)); }
public Activity Add(Activity newActivity) { //retrieve the ActivityType so we can check var activityType = _activityTypeRepo.Get(newActivity.ActivityTypeId); //for a DurationAndDistance activity, a distance must be supplied if (activityType.RecordType == RecordType.DurationAndDistance && newActivity.Distance <= 0) { throw new ApplicationException("You must supply a distance for this activity."); } //for either type, a duration must be supplied if (newActivity.Duration <= 0) { throw new ApplicationException("You must supply a duration for this activity."); } _activityRepo.Add(newActivity); return(newActivity); }
public ActionResult <Activity> Add(ActivityDTO model) { try { Activity activityToCreate = new Activity( model.ActivityType, model.Name, model.Description, model.Pictogram); _activityRepository.Add(activityToCreate); _activityRepository.SaveChanges(); return(Ok(activityToCreate)); } catch (Exception ex) { return(BadRequest(ex.Message)); } }
public async Task <string> AddAsync( string nodeId, string message, string userId) { var activity = new Activity() { Id = Guid.NewGuid().ToString(), NodeId = nodeId, Content = message, CreatedDate = DateTimeOffset.UtcNow.ToString("s"), CreatedBy = userId }; _activityRepository.Add(activity); await _activityRepository.SaveChangesAsync(); return(activity.Id); }
public Activity Add(Activity newActivity) { // todo fix this var activityType = _activityTypeRepo.Get(newActivity.ActivityTypeId); // todo fix this if (activityType.RecordType == RecordType.DurationAndDistance && newActivity.Distance <= 0) { throw new ApplicationException("You must supply a Distance for this activity."); } if (newActivity.Duration <= 0) { throw new ApplicationException("You must supply a Duration for this activity."); } _activityRepo.Add(newActivity); return(newActivity); }
public Activity Add(Activity activity) { // retrieve the ActivityType so we can check var activityType = _activityTypeRepo.Get(activity.ActivityTypeId); // for a DurationAndDistance activity, you must supply a Distance if (activityType.RecordType == RecordType.DurationAndDistance && activity.Distance <= 0) { throw new ApplicationException("You must supply a Distance for this activity."); } // for either type, you must supply a Duration if (activity.Duration <= 0) { throw new ApplicationException("You must supply a Duration for this activity."); } // TODO: implement add _activityRepo.Add(activity); return(activity); }
/// <summary> /// Add a new Activity object to the database. /// </summary> /// <param name="activity">Activity object to be added</param> /// <returns>The Activity object after it was added (with the Activity Id)</returns> public ServiceResponse <Activity> Add(Activity activity) { Activity result; try { result = _repository.Add(activity); } catch (Exception ex) { return(new ServiceResponse <Activity>(true, $"Error occurred while adding an Activity object to database. {ex.GetType()} was thrown. Exception Message: {ex.Message}", ex)); } if (result == null) { return(new ServiceResponse <Activity>(true, "Error occurred while adding an Activity object to database. Activity object returned by add process was null for some reason.")); } return(new ServiceResponse <Activity>(result)); }
/// <summary> /// Zapisuje rankingi w kolejnych miesiącach /// </summary> /// <param name="points"></param> /// <param name="playoff"></param> /// <param name="isActive"></param> private void SaveRanking(Rankings[] points, Rankings playoff, Activity isActive) { Rankings november = new Rankings(), december = new Rankings(), january = new Rankings(), february = new Rankings(), march = new Rankings(), april = new Rankings(); foreach (Teams team in allTeams) { PropertyInfo propInfo = points[0].GetType().GetProperty(team.Name.Replace(' ', '_').Replace('.', '_')); propInfo.SetValue(november, propInfo.GetValue(points[0])); propInfo.SetValue(december, propInfo.GetValue(points[1])); propInfo.SetValue(january, propInfo.GetValue(points[2])); propInfo.SetValue(february, propInfo.GetValue(points[3])); propInfo.SetValue(march, propInfo.GetValue(points[4])); propInfo.SetValue(april, propInfo.GetValue(points[5])); } november.ID = string.Format("{0} {1}", _currentSeason.ToString(), Month.November.ToString()); _rankingRepository.Add(november); december.ID = string.Format("{0} {1}", _currentSeason.ToString(), Month.December.ToString()); _rankingRepository.Add(december); january.ID = string.Format("{0} {1}", _currentSeason.ToString(), Month.January.ToString()); _rankingRepository.Add(january); february.ID = string.Format("{0} {1}", _currentSeason.ToString(), Month.February.ToString()); _rankingRepository.Add(february); march.ID = string.Format("{0} {1}", _currentSeason.ToString(), Month.March.ToString()); _rankingRepository.Add(march); april.ID = string.Format("{0} {1}", _currentSeason.ToString(), Month.April.ToString()); _rankingRepository.Add(april); playoff.ID = string.Format("{0} {1}", _currentSeason.ToString(), Month.PlayOffs.ToString()); _rankingRepository.Add(playoff); _rankingRepository.SaveChanges(); isActive.Id = _currentSeason.ToString(); _activityRepository.Add(isActive); _activityRepository.SaveChanges(); }
public void InsertActivity(ApplicationUser user, string activity) { //Create PDR var activities = GetAllActivityUserId(user.Id); if (activities.Count() >= 5) { var firstAct = activities.OrderBy(x => x.DateTimeCreated).FirstOrDefault(); if (firstAct != null) { _ActivityRepository.Delete(firstAct); Save(); } } Activity act = new Activity(); act.ApplicationUser = user; act.ApplicationUserId = user.Id; act.Name = activity; _ActivityRepository.Add(act); Save(); }
public CommentModule(IIdeaRepository ideas, IActivityRepository activities) : base("/comment") { _ideas = ideas; _activities = activities; Post["/{idea}/add"] = parameters => { int id = parameters.Idea; int userId = Request.Form.userId; // addtional validation required var text = Request.Form.comment; if (string.IsNullOrEmpty(text)) // additional validation required { return Response.AsJson(new { result = "Error" }); } var comment = new Comment { UserId = userId, Time = DateTime.UtcNow, Text = Request.Form.comment }; _activities.Add(id, comment); // why not return JSON here and leave it up to client to render inline? return Response.AsRedirect(string.Format("/idea/{0}#{1}", id, comment.Id)); }; // TODO: shouldn't these actually sit under the Comment root // TODO: user should be able to edit their own comment Post["/{id}/edit"] = parameters => Response.AsJson(new { result = "Error" }); // TODO: user should be able to remove their own comment Post["/{id}/delete"] = parameters => Response.AsJson(new { result = "Error" }); }
public IActionResult Edit(Activity activity) { if (!ModelState.IsValid) { ActivityEditViewModel activityEditViewModel = new ActivityEditViewModel(); activityEditViewModel.Priorities = htmlHelper.GetEnumSelectList <Priority>(); activityEditViewModel.Activity = activity; return(View(activityEditViewModel)); } if (activity.Id > 0) { activityRepository.Update(activity); TempData["Message"] = $"Zadanie '{activity.Title}' zostało zapisane."; } else { activityRepository.Add(activity); TempData["Message"] = $"Zadanie '{activity.Title}' zostało utworzone."; } activityRepository.Commit(); return(RedirectToAction("Index")); }
public AdminModule(IdeastrikeContext dbContext, Settings settings, IUserRepository users, IIdeaRepository ideas, IActivityRepository activities) : base("/admin") { this.RequiresAuthentication(); this.RequiresValidatedClaims(c => c.Contains("admin")); _settings = settings; _users = users; _ideas = ideas; _activities = activities; Get["/"] = _ => { var m = Context.Model(string.Format("Admin - {0}", (string)_settings.SiteTitle)); m.Name = _settings.Name; m.WelcomeMessage = _settings.WelcomeMessage; m.HomePage = _settings.HomePage; m.GAnalyticsKey = _settings.GAnalyticsKey; return View["Admin/Index", m]; }; Get["/users"] = _ => { var m = Context.Model(string.Format("Admin - {0}", (string)_settings.SiteTitle)); m.Name = _settings.Name; m.WelcomeMessage = _settings.WelcomeMessage; m.HomePage = _settings.HomePage; m.GAnalyticsKey = _settings.GAnalyticsKey; m.Users = users.GetAll(); return View["Admin/Users", m]; }; Get["/moderation"] = _ => { var m = Context.Model(string.Format("Admin - {0}", (string)_settings.SiteTitle)); m.Name = _settings.Name; m.WelcomeMessage = _settings.WelcomeMessage; m.HomePage = _settings.HomePage; m.GAnalyticsKey = _settings.GAnalyticsKey; return View["Admin/Moderation", m]; }; Get["/settings"] = _ => { var m = Context.Model(string.Format("Admin - {0}", (string)_settings.SiteTitle)); m.Name = _settings.Name; m.SiteTitle = _settings.SiteTitle; m.WelcomeMessage = _settings.WelcomeMessage; m.HomePage = _settings.HomePage; m.GAnalyticsKey = _settings.GAnalyticsKey; m.MaxThumbnailWidth = _settings.MaxThumbnailWidth; return View["Admin/Settings", m]; }; Post["/settings"] = _ => { _settings.WelcomeMessage = Request.Form.welcomemessage; _settings.SiteTitle = Request.Form.sitetitle; _settings.Name = Request.Form.yourname; _settings.HomePage = Request.Form.homepage; _settings.GAnalyticsKey = Request.Form.analyticskey; _settings.MaxThumbnailWidth = Request.Form.maxthumbnailwidth; return Response.AsRedirect("/admin/settings"); }; Get["/search"] = _ => ""; Get["/forums"] = _ => ""; Get["/forum/{forumId}"] = _ => ""; Get["/uservoice"] = _ => View["Admin/Uservoice", Context.Model("Admin")]; Post["/uservoice"] = _ => { var client = new WebClient(); var suggestions = GetSuggestions(client, Request.Form.channel, Request.Form.forumid, Request.Form.apikey, Request.Form.trusted); foreach (var s in suggestions) { string title = s.title; //If the idea exists, skip it if (ideas.FindBy(i => i.Title == title).Any()) continue; string date = s.created_at; var idea = new Idea { Title = title, Description = s.text, Time = DateTime.Parse(date.Substring(0, date.Length - 5)), }; string status = string.Empty; switch ((string)s.state) { case "approved": status = "Active"; break; case "closed" : if (s.status.key == "completed") status = "Completed"; else status = "Declined"; break; default: status = "New"; break; } idea.Status = status; //Get the author, or create string name = s.creator.name; var existing = users.FindBy(u => u.UserName == name).FirstOrDefault(); if (existing != null) idea.Author = existing; else { idea.Author = NewUser(s.creator); users.Add(idea.Author); } ideas.Add(idea); //Process all comments var comments = GetComments(client, (string)s.id, Request.Form.channel, Request.Form.forumid, Request.Form.apikey, Request.Form.trusted); List<Activity> ideaComments = new List<Activity>(); foreach (var c in comments) { string commentdate = c.created_at; var comment = new Comment { Time = DateTime.Parse(commentdate), Text = c.text }; string commentname = c.creator.name; existing = users.FindBy(u => u.UserName == commentname).FirstOrDefault(); if (existing != null) comment.User = existing; else { comment.User = NewUser(c.creator); users.Add(comment.User); } activities.Add(idea.Id, comment); } //Process all votes var votes = GetVotes(client, (string)s.id, Request.Form.channel, Request.Form.forumid, Request.Form.apikey, Request.Form.trusted); foreach (var v in votes) { string votername = v.user.name; string votesfor = v.votes_for; int vote; if (Int32.TryParse(votesfor, out vote)) { existing = users.FindBy(u => u.UserName == votername).FirstOrDefault(); if (existing != null) ideas.Vote(idea.Id, existing.Id, vote); else { var author = NewUser(v.user); users.Add(author); ideas.Vote(idea.Id, author.Id, vote); } } } } return Response.AsRedirect("/admin"); }; }
protected override async Task Handle(Command request, CancellationToken cancellationToken) { await _activityRepository.Add(MapCreateViewToActivity(request)); }
public void Create(Activity activity) { activityRepository.Add(activity); }