public ActionResult Create(int?projectId) { if (projectId.HasValue) { var project = _database.Projects .Where(p => p.Id == projectId) .SingleOrDefault(); var currentUser = _userManager.FindById(User.Identity.GetUserId()); if (project != null) { if (project.Owner == currentUser || User.IsInRole(UserRoles.ADMIN)) { var session = new CreateSessionViewModel() { Name = "", StartTime = _timeProvider.CurrentTime.Ceiling(TimeSpan.FromHours(1)), Length = TimeSpan.FromHours(1), UseProjectDefinitionTemplate = true, Definition = project.SessionDefinitionTemplate ?? "", ProjectId = project.Id }; return(View(session)); } } return(HttpNotFound()); } return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); }
public void CreateSession_ShouldAddThatSession() { // Arrange var controller = new SessionController(_activityManager, _sessionManager, _personManager, _utilityManager); var sessionToAdd = new CreateSessionViewModel() { Activity = _activityManager.GetActivityById(1), Name = "New Session", AddedParticipants = "1,2", AddedTags = "5,6", NameOfLocation = "New Location" }; // Act var controllerResult = controller.CreateSession(sessionToAdd); var sessionID = _sessionManager.GetAllSessions().SingleOrDefault(n => n.Name == "New Session").Id; var result = _sessionManager.GetSessionByIdWithIncludes(sessionID); var tags = new string[2]; tags[0] = "databaser"; tags[1] = "sql"; //TODO: check that it's the correct sessionparticipants & tags!? // Assert Assert.AreEqual(2, result.SessionParticipants.Count); Assert.AreEqual(2, result.SessionTags.Count); }
public async Task <IActionResult> CreateSession(CreateSessionViewModel vm) { var dto = _createSessionViewModelMapper.MapFrom(vm); await _sessionService.Create(dto); return(Redirect("~/Moderator/Member/OnlineUsers")); }
public void CreateSessionWithInvalidModel_ShouldReturnModelStateNotValid() { var controller = new SessionController(_activityManager, _sessionManager, _personManager, _utilityManager); var model = new CreateSessionViewModel() { Activity = null, Name = "" }; //Init ModelState var modelBinder = new ModelBindingContext() { ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType( () => model, model.GetType()), ValueProvider = new NameValueCollectionValueProvider( new NameValueCollection(), CultureInfo.InvariantCulture) }; var binder = new DefaultModelBinder().BindModel( new ControllerContext(), modelBinder); controller.ModelState.Clear(); controller.ModelState.Merge(modelBinder.ModelState); ViewResult result = (ViewResult)controller.CreateSession(model); Assert.IsTrue(result.ViewData.ModelState["Activity"].Errors.Count > 0); Assert.IsTrue(result.ViewData.ModelState["Name"].Errors.Count > 0); Assert.IsTrue(!result.ViewData.ModelState.IsValid); }
// GET: Session/Create public ActionResult Create() { var speakers = this.mapper.Map <IList <SpeakerViewModel> >(this.repositoryWrapper.Speaker.GetAllSpeakers()); ViewBag.Speakers = speakers; var model = new CreateSessionViewModel(); this.loggerManager.LogInfo($"{User.Identity.Name} access Create(Get) page (Dashboard.SesionController.Create)"); return(View(model)); }
public IActionResult Create() { CreateSessionViewModel viewModel = new CreateSessionViewModel(); viewModel.Session = new Session(); viewModel.Adventures = new SelectList(_context.Adventures, "AdventureID", "Title"); viewModel.SessionPlayers = new SelectList(_context.Players, "PlayerID", "Name"); viewModel.SelectedSessionPlayers = new List <int>(); return(View(viewModel)); }
public static void AddHistoryRecord(CreateSessionViewModel viewModel, string userId) { List <CreateSessionViewModel> userHistory; if (!allHistory.TryGetValue(userId, out userHistory)) { userHistory = new List <CreateSessionViewModel>(); allHistory.Add(userId, userHistory); } userHistory.Add(viewModel); }
public JsonResult GetHotelsByTripDescription(CreateSessionViewModel viewModel) { var bookingFacade = new BookingFacade(); DateTime date1 = new DateTime(2017, 06, 11); DateTime date2 = new DateTime(2017, 06, 20); var model = bookingFacade.FindHotels(viewModel.DestinationPlace, date1, date2, Booking.Implementation.Enums.ArrivingMethod.Aeroplane); var data = JsonConvert.SerializeObject(model); var json = Json(data, JsonRequestBehavior.AllowGet); return(json); }
public IEnumerable <KeyValuePair <string, string> > ToUrlEncodedContent(CreateSessionViewModel viewModel) { var kvPairs = new List <KeyValuePair <string, string> >(); var allProps = viewModel.GetType().GetProperties(); foreach (var propertyInfo in allProps) { kvPairs.Add(new KeyValuePair <string, string>(propertyInfo.Name, viewModel.GetType().GetProperty(propertyInfo.Name).GetValue(viewModel)?.ToString() ?? String.Empty)); } return(kvPairs); }
public async Task <IActionResult> Create(CreateSessionViewModel viewModel) { if (ModelState.IsValid) { try { if (viewModel.SelectedSessionPlayers == null) { viewModel.SelectedSessionPlayers = new List <int>(); } List <SessionPlayer> playersInSession = new List <SessionPlayer>(); List <AdventurePlayer> playersInAdventure = new List <AdventurePlayer>(); foreach (int playerID in viewModel.SelectedSessionPlayers) { //Wie speelt mee in de session SessionPlayer sessionPlayer = new SessionPlayer(); sessionPlayer.PlayerID = playerID; sessionPlayer.SessionID = viewModel.Session.SessionID; //Welke spelers spelen het avontuur mee AdventurePlayer adventurePlayer = new AdventurePlayer(); adventurePlayer.PlayerID = playerID; adventurePlayer.AdventureID = viewModel.Session.AdventureID; playersInSession.Add(sessionPlayer); playersInAdventure.Add(adventurePlayer); } _context.Add(viewModel.Session); await _context.SaveChangesAsync(); Session session = await _context.Sessions .Include(s => s.SessionPlayers) .Include(a => a.Adventure.AdventurePlayers) .SingleOrDefaultAsync(x => x.SessionID == viewModel.Session.SessionID); session.SessionPlayers.AddRange(playersInSession); session.Adventure.AdventurePlayers.AddRange(playersInAdventure); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } catch (Exception) { return(Redirect("~/Views/Shared/Error.cshtml")); } } return(View(viewModel)); }
public async Task <IActionResult> CreateSession(string id) { var devices = await _deviceService.GetAllDevices(); var deviceSelectList = devices.Select(d => new SelectListItem { Text = d.Type, Value = d.DeviceName }).OrderBy(x => x.Text).ThenBy(x => x.Value.Length).ThenBy(x => x.Value).ToList(); var vm = new CreateSessionViewModel() { UserID = id, AllDevices = deviceSelectList, }; return(View(vm)); }
public ActionResult Create(CreateSessionViewModel viewModel) { if (!ModelState.IsValid) { return(View(viewModel)); } using (var sqlStorage = new SqlStorage()) { // trimmin viewModel.Username = (viewModel.Username ?? "").Trim(); var branchIdentity = sqlStorage.BranchIdentities.FirstOrDefault( i => i.Email.ToLower() == viewModel.Username.ToLower() || i.Username.ToLower() == viewModel.Username.ToLower()); if (branchIdentity == null) { ModelState.AddModelError("Username", "An Identity with that Username/Email doesn't exist."); return(View(viewModel)); } if (!Pbkdf2Crypto.ValidateHash(viewModel.Password, branchIdentity.PasswordHash, branchIdentity.PasswordSalt, branchIdentity.PasswordIterations)) { ModelState.AddModelError("Password", "Incorrect Password."); return(View(viewModel)); } // Create Session var ipAddress = Request.ServerVariables.Get("HTTP_CF_CONNECTING_IP") ?? Request.UserHostAddress; var branchSession = BranchSession.Create(ipAddress, Request.UserAgent, branchIdentity, viewModel.RememberMe); sqlStorage.BranchSessions.Add(branchSession); branchIdentity.BranchIdentitySessions.Add(branchSession); // Set Cookie var cookie = new HttpCookie("SessionIdentifier", branchSession.Identifier.ToString()) { Expires = branchSession.ExpiresAt }; Response.SetCookie(cookie); sqlStorage.SaveChanges(); return(RedirectToRoute("BranchIdentityView", new { controller = "Home", action = "Index", slug = branchIdentity.Username })); } }
public ActionResult Create(CreateSessionViewModel newSession) { using (WSADDbContext context = new WSADDbContext()) { Session newSessionDTO = new WSAD_App1.Models.Data.Session() { Title = newSession.Title, Description = newSession.Description, Presenter = newSession.Presenter, Room = newSession.Room, Time = newSession.Time, Occupancy = newSession.Occupancy }; newSessionDTO = context.Sessions.Add(newSessionDTO); context.SaveChanges(); } return(RedirectToAction("index")); }
public ActionResult Create(CreateSessionViewModel newSession) { //Check required fields if (!ModelState.IsValid) { return(View(newSession)); } //Create DbContext using (WSADDbContext context = new WSADDbContext()) { //Check for duplicate sessions if (context.Sessions.Any(row => row.Course.Equals(newSession.Course))) { ModelState.AddModelError("", "Session '" + newSession.Course + "' already exists. Try Again"); newSession.Course = ""; return(View(newSession)); } //Create Session DTO Session newSessionDTO = new WSAD_App1.Models.Data.Session() { Course = newSession.Course, Instructor = newSession.Instructor, MeetingDate = newSession.MeetingDate, MeetingTime = newSession.MeetingTime, Description = newSession.Description }; //Add to DbContext newSessionDTO = context.Sessions.Add(newSessionDTO); //Save changes context.SaveChanges(); } //Redirect to login return(RedirectToAction("Index")); }
public ActionResult Create(CreateSessionViewModel model) { try { if (ModelState.IsValid) { var session = this.mapper.Map <Session>(model); this.repositoryWrapper.Session.Create(session); this.repositoryWrapper.Save(); this.loggerManager.LogInfo($"{User.Identity.Name} access Create(Post) page (Dashboard.SesionController.Create)"); } return(RedirectToAction(nameof(Index))); } catch (Exception ex) { var speakers = this.mapper.Map <IList <SpeakerViewModel> >(this.repositoryWrapper.Speaker.GetAllSpeakers()); ViewBag.Speakers = speakers; ModelState.AddModelError("", ex.Message); this.loggerManager.LogInfo($"{User.Identity.Name} access Create(Post) page (Dashboard.SesionController.Create). Error: {ex.Message}"); return(View(model)); } }
public async Task <JsonResult> GetItinerariesByTripDescription(CreateSessionViewModel viewModel) { // Check defaults if (viewModel.Locale == null) { viewModel.Locale = "en-US"; } if (viewModel.Country == null) { viewModel.Country = "US"; } if (viewModel.Currency == null) { viewModel.Currency = "USD"; } DateTime parsedOutboundDate; try { parsedOutboundDate = DateTime.Parse(viewModel.OutboundDate); } catch { parsedOutboundDate = DateTime.Now.AddMonths(1); } DateTime parsedInboundDate; try { parsedInboundDate = DateTime.Parse(viewModel.InboundDate); } catch { parsedInboundDate = DateTime.Now.AddMonths(2); } viewModel.OutboundDate = parsedOutboundDate.ToString("yyyy-MM-dd"); viewModel.InboundDate = parsedInboundDate.ToString("yyyy-MM-dd"); if (User.Identity.IsAuthenticated) { var id = User.Identity.GetUserId(); HistoryService.AddHistoryRecord(viewModel, id); } /* * // Create a session with ScyScanner * * var subUrl = $"pricing/v1.0"; * * var content = ToUrlEncodedContent(viewModel); * * string userApi = Request.UserHostAddress; * string bodyString = $"cabinclass={viewModel.CabinClass}&country={viewModel.Country}¤cy={viewModel.Currency}&locale={viewModel.Locale}&locationSchema=iata&originplace={viewModel.OriginPlace}&destinationplace={viewModel.DestinationPlace}&outbounddate={viewModel.OutboundDate}&inbounddate={viewModel.InboundDate}&adults={viewModel.Adults}&children={viewModel.Children}&infants={viewModel.Infants}"; * string locationHeader = await _searchService.GetLocationHeader(subUrl, content, bodyString, userApi); */ var partialUrl = string.Format(CultureInfo.CurrentCulture, $"browseroutes/v1.0/{viewModel.Country}/{viewModel.Currency}/{viewModel.Locale}/{viewModel.OriginPlace}/{viewModel.DestinationPlace}/{viewModel.OutboundDate}/{viewModel.InboundDate}?"); var routes = await _searchService.GetFromUrl <RoutesWrapper>(partialUrl); // It's a terrible hack to simplify data manipulation on the frontend IEnumerable <QuoteExpanded> quotesExpanded = routes.Quotes.Select(quote => new QuoteExpanded() { QuoteId = quote.QuoteId, MinPrice = string.Format(CultureInfo.CurrentCulture, "{0} {1}", quote.MinPrice, routes.Currencies.FirstOrDefault().Symbol), MinPriceNum = quote.MinPrice, Direct = quote.Direct, QuoteDateTime = quote.QuoteDateTime, OutboundLeg = quote.OutboundLeg == null ? null : new OutboundlegExpanded() { DepartureDate = quote.OutboundLeg.DepartureDate, Destination = routes.Places.SingleOrDefault(place => quote.OutboundLeg.DestinationId == place.PlaceId), Origin = routes.Places.SingleOrDefault(place => quote.OutboundLeg.OriginId == place.PlaceId), Carriers = routes.Carriers.Where(carrier => quote.OutboundLeg.CarrierIds.Contains(carrier.CarrierId)).ToArray() }, InboundLeg = quote.InboundLeg == null ? null : new InboundlegExpanded() { DepartureDate = quote.InboundLeg.DepartureDate, Destination = routes.Places.SingleOrDefault(place => quote.InboundLeg.DestinationId == place.PlaceId), Origin = routes.Places.SingleOrDefault(place => quote.InboundLeg.OriginId == place.PlaceId), Carriers = routes.Carriers.Where(carrier => quote.InboundLeg.CarrierIds.Contains(carrier.CarrierId)).ToArray() } }).Take(50); var json = Json(quotesExpanded, JsonRequestBehavior.AllowGet); Thread.Sleep(1000); return(json); }
//[ValidateAntiForgeryToken] public ActionResult CreateSession(CreateSessionViewModel sessionVm) { if (ModelState.IsValid) { List <Participant> participantsToAddFromDb = new List <Participant>(); if (sessionVm.AddedParticipants != null) { string[] participants = sessionVm.AddedParticipants.Split(','); List <int> participantsId = new List <int>(); foreach (var participant in participants) { participantsId.Add(int.Parse(participant)); } //TODO: Make a proper join, this is inefficient participantsToAddFromDb = _personManager.GetAllParticipants().Where(n => participantsId.Contains(n.Id)).ToList(); } // -> TAGS var tagsToAdd = sessionVm.GenerateSessionTags; _utilitiesManager.AddNewTagsToDb(tagsToAdd); // <- END TAGS int?locationId = _utilitiesManager.GetIdForLocationOrCreateIfNotExists(sessionVm.NameOfLocation); var result = new Session() { Name = sessionVm.Name, ActivityId = sessionVm.Activity.Id, StartDate = sessionVm.StartDate, EndDate = sessionVm.EndDate, LocationId = locationId, HrPersonId = sessionVm.HrPerson, Description = sessionVm.Description, IsOpenForExpressionOfInterest = sessionVm.IsOpenForExpressionOfInterest, SessionParticipants = null, SessionTags = null }; if (sessionVm.AddedParticipants != null) { List <SessionParticipant> final = new List <SessionParticipant>(); foreach (var participant in participantsToAddFromDb) { final.Add(new SessionParticipant() { ParticipantId = participant.Id, Session = result, Rating = 0, }); result.SessionParticipants = final; } } // Save session in db if (_sessionManager.AddSession(result)) { // Now add tags to the created session!... _sessionManager.AddSessionTags(tagsToAdd, result.Id); return(RedirectToAction("SessionForActivity", "ActivitySummary", new { id = result.Id })); } else { ModelState.AddModelError("", "Ett tillfälle med samma namn existerar redan till denna aktivitet!"); } } ModelState.AddModelError("", "Lyckades inte skapa tillfället!"); var allActivities = _activityManager.GetAllActivities().OrderBy(n => n.Name).ToList(); var allSessionParticipants = _personManager.GetAllParticipants().OrderBy(n => n.FirstName).ToList(); var allHrPersons = _personManager.GetAllHrPersons().OrderBy(n => n.FirstName).ToList(); var selectedActivityId = allActivities.First().Id; ViewBag.AllActivities = new SelectList(allActivities, "Id", "Name", selectedActivityId); ViewBag.AllSessionParticipants = new SelectList( allSessionParticipants, "Id", "FullName", allSessionParticipants.Skip(1).First().Id); // TODO: TAKE AWAY SKIP ViewBag.AllHrPersons = new SelectList(allHrPersons, "Id", "FullName"); return(View(sessionVm)); }
public CreateSessionPage(ClientViewModel frame, LoggedClient loggedClient, LoginSessionClient loginSessionNetworkClient) { InitializeComponent(); DataContext = new CreateSessionViewModel(frame, loggedClient, loginSessionNetworkClient); }
public ActionResult CreateSession(CreateSessionViewModel newSession) { bool sessionCreated = false; //admin has the right to populate this, and commit changes to the database if (newSession == null) { ModelState.AddModelError("", "No Message Provided"); return(View()); } //form verification if (string.IsNullOrWhiteSpace(newSession.SessionTitle) || string.IsNullOrWhiteSpace(newSession.SessionDescription) || string.IsNullOrWhiteSpace(newSession.SessionPresenter) || string.IsNullOrWhiteSpace(newSession.SessionAddress) || string.IsNullOrWhiteSpace(newSession.SessionRoom)) { ModelState.AddModelError("", "All Fields Required!"); return(View()); } //Seats Verification if (newSession.SessionSeatsAvailable == null || newSession.SessionSeatsAvailable < 1) { ModelState.AddModelError("", "Session Cannot Be Added"); return(View()); } //TODO: Loop through all the user emails and notify about new session //store the session into the database using (WSADDbContext context = new WSADDbContext()) { //Check to see if a session already exists if (context.Sessions.Any(row => row.SessionTitle.Equals(newSession.SessionTitle, StringComparison.OrdinalIgnoreCase))) { ModelState.AddModelError("", "A Session with the Title " + newSession.SessionTitle + " Already Exists"); newSession.SessionTitle = " "; return(View(newSession)); } Session newSessionDto = new Session() { SessionTitle = newSession.SessionTitle, SessionDescription = newSession.SessionDescription, SessionPresenter = newSession.SessionPresenter, SessionAddress = newSession.SessionAddress, SessionRoom = newSession.SessionRoom, SessionSeatsAvailable = newSession.SessionSeatsAvailable, SessionDateCreated = DateTime.Now, SessionDateModified = DateTime.Now }; newSessionDto = context.Sessions.Add(newSessionDto); //commit changes to the database try { context.SaveChanges(); sessionCreated = true; } catch (DbException d) { return(Content(d.Message)); } } //toast - session created sucessfully if (sessionCreated) { TempData["SessionSuccess"] = "Session Created Successfully"; return(View()); } return(View()); }