public ActionResult CreateRoom(RoomViewModel model) { if (!this.ModelState.IsValid) { return this.View(model); } var roomName = this.Rooms.Create(model, this.User.Identity.GetUserId()); this.TempData.Add("RoomCreated", roomName); return this.RedirectToActionPermanent("GetRooms"); }
public ActionResult JoinRoom(RoomViewModel model) { if (!this.ModelState.IsValid) { return this.RedirectToAction("GetRooms"); } if(!this.Rooms.CanJoinRoom(model, this.User.Identity.GetUserId())) { this.TempData.Add(ServicesConstants.RoomUnavailableKey, true); return this.RedirectToAction("GetRooms"); } model = this.Mapper.Map<Room,RoomViewModel>(this.Rooms.GetByContext(model.Context)); return this.View(model); }
public ActionResult CreateRoom(RoomViewModel roomViewModel) { var fileName = Path.GetFileNameWithoutExtension(roomViewModel.ImageFile.FileName); var extension = Path.GetExtension(roomViewModel.ImageFile.FileName); fileName += extension; roomViewModel.RoomImage = "~/Content/Image/" + fileName; fileName = Path.Combine(Server.MapPath("~/Content/Image/"), fileName); try { roomViewModel.ImageFile.SaveAs(fileName); } catch (DirectoryNotFoundException dirEx) { Logger.Log.Error("Error adding image.", dirEx); } try { if (ModelState.IsValid) { var room = new Room { RoomDescription = roomViewModel.RoomDescription, RoomNumber = roomViewModel.RoomNumber, RoomPriceForOneNight = roomViewModel.RoomPriceForOneNight, Sleeps = roomViewModel.Sleeps, RoomImage = roomViewModel.RoomImage, RoomTypeId = roomViewModel.RoomTypeId, RoomType = roomViewModel.RoomType, RoomStatus = roomViewModel.RoomStatus, RoomStatusId = roomViewModel.RoomStatusId }; Logger.Log.Debug("Add new room"); _roomService.Create(room); return(RedirectToAction("RoomList")); } } catch (Exception ex) { Logger.Log.Error("Error adding new room", ex); ModelState.AddModelError("", ex.Message); } return(RedirectToAction("CreateRoom")); }
public ActionResult Create(RoomViewModel model) { ActionResult result; if (ModelState.IsValid) { writer.CreateRoom(model); result = RedirectToAction("List"); } else { result = View("Create", model); } return(result); }
public RoomViewModel GetRoomViewModel(Guid id) { RoomViewModel rvm = new RoomViewModel(); rvm.Room = db.Rooms.SingleOrDefault(r => r.RoomId == id); rvm.Owner = db.Users.SingleOrDefault(u => u.UserId == rvm.Room.OwnerId); rvm.Messages = new List<MessageViewModel>(); rvm.CurrentUser = CurrentUser(); foreach (Message message in rvm.Room.Messages.OrderBy(m => m.Timestamp)) { rvm.Messages.Add(SerializeMessage(message)); } rvm.OnlineUserList = OnlineUserList(id); return rvm; }
public void PostCreateNewRoomWithInvalidRoomNameCausesValidationError(string roomName) { var controller = CreateController(); var viewModel = new RoomViewModel { Name = roomName }; var context = new ValidationContext(viewModel, serviceProvider: null, items: null); var results = new List <ValidationResult>(); var isValid = Validator.TryValidateObject(viewModel, context, results); Assert.That(isValid, Is.False); // Changes Sprint 2 -- “I want to filter message content so that it is appropriate.” -- Makar Grytsevych }
public IActionResult CreateRoom([FromBody] RoomViewModel room) { if (room == null) { return(BadRequest("Neivesti duomenys")); } if (room.Number < 0) { return(BadRequest("Blogas nr")); } if (room.Area < 0) { return(BadRequest("Blogas plotas")); } if (!new List <int>() { 1, 2, 3 }.Contains(room.TypeId)) // shouldn't be hardcoded xD { return(BadRequest("Blogas tipo id")); } if (room.Size < 0) { return(BadRequest("Nenurodytas vietu sk")); } try { Db.Connection.Open(); var cmd = Db.Connection.CreateCommand() as MySqlCommand; cmd.CommandText = string.Format("INSERT INTO patalpos (nr, plotas, vietu_sk, tipas) VALUES({0}, {1}, {2}, {3})" , room.Number, room.Area, room.Size, room.TypeId); int code = cmd.ExecuteNonQuery(); return(Ok()); } catch (Exception ex) { return(StatusCode(500, "Patalpos pridėti nepavyko, patikrinkite duomenis.")); } }
public ActionResult Index(RoomViewModel objRoomViewModel) { //string ImageUniqueName = Guid.NewGuid().ToString(); //string ActualImageName = ImageUniqueName + Path.GetExtension(objRoomViewModel.Image.FileName); //objRoomViewModel.Image.SaveAs(Server.MapPath("~/RoomImages/" + ActualImageName)); try { Room objRoom = new Room() { RoomNumber = objRoomViewModel.RoomNumber, RoomDescription = objRoomViewModel.RoomDescription, RoomPrice = objRoomViewModel.RoomPrice, BookingStatusId = objRoomViewModel.BookingStatusId, //RoomImage = objRoomViewModel.RoomImage, //IsActive = true, RoomCapacity = objRoomViewModel.RoomCapacity, RoomTypeId = objRoomViewModel.RoomTypeId, }; objhotelDBEntities.Rooms.Add(objRoom); objhotelDBEntities.SaveChanges(); } catch (DbEntityValidationException e) { foreach (var eve in e.EntityValidationErrors) { Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); } } throw; } return(Json(new { message = "Room Succsessfully Added.", success = true }, JsonRequestBehavior.AllowGet)); }
public static RoomsViewModel GetRoomsViewModel(List <string> Styles, List <string> Sizes) { RoomsViewModel model = new RoomsViewModel(); model.RoomStyles = RoomStyleDAO.GetAllRoomStyleViewModel(); model.RoomSizes = RoomSizeDAO.GetAllRoomSizeViewModel(); using (SqlConnection conn = Connection.GetConnection()) { if (conn != null) { string styles_formated = string.IsNullOrEmpty(string.Join(",", Styles)) ? ("0") : (string.Join(",", Styles)); string sizes_formated = string.IsNullOrEmpty(string.Join(",", Sizes)) ? ("0") : (string.Join(",", Sizes)); string sql = "select RoomID from Room, RoomType where Room.RoomTypeID = RoomType.RoomTypeID and RoomStyleID IN (" + styles_formated + ") and RoomSizeID IN (" + sizes_formated + ")"; SqlCommand cm = new SqlCommand(sql, conn); var rs = cm.ExecuteReader(); if (rs.HasRows) { while (rs.Read()) { RoomViewModel room = GetRoomViewModel(rs.GetInt32(0)); if (room.Status == "Empty") { model.EmptyCount++; } if (room.Status == "Reserved") { model.ReservedCount++; } if (room.Status == "Occupied") { model.OccupiedCount++; } if (room.Status == "Stayover") { model.StayoverCount++; } model.Rooms.Add(room); } } conn.Close(); } } return(model); }
public async Task CreateRoom(string roomName) { try { // Accept: Letters, numbers and one space between words. Match match = Regex.Match(roomName, @"^\w+( \w+)*$"); if (!match.Success) { await Clients.Caller.SendAsync("onError", "Invalid room name!\nRoom name must contain only letters and numbers."); } else if (roomName.Length < 5 || roomName.Length > 100) { await Clients.Caller.SendAsync("onError", "Room name must be between 5-100 characters!"); } else if (_context.Rooms.Any(r => r.Name == roomName)) { await Join(roomName); } else { // Create and save chat room in database var user = _context.Users.Where(u => u.Username == IdentityName).FirstOrDefault(); var room = new Room() { Name = roomName, Admin = user }; _context.Rooms.Add(room); _context.SaveChanges(); if (room != null) { // Update room list RoomViewModel roomViewModel = _mapper.Map <Room, RoomViewModel>(room); _Rooms.Add(roomViewModel); await Clients.All.SendAsync("addChatRoom", roomViewModel); await Join(roomName); } } } catch (Exception ex) { await Clients.Caller.SendAsync("onError", "Couldn't create chat room: " + ex.Message); } }
public IActionResult Room(int id) { var room = this.db.ChatRooms.FirstOrDefault(x => x.Id == id); if (room == null) { return(this.NotFound()); } var viewModel = new RoomViewModel() { Id = room.Id, Name = room.Name, Messages = this.db.Messages.Where(x => x.ChatRoomId == room.Id).ToList(), }; return(View(viewModel)); }
public async Task <ActionResult> Edit(RoomViewModel room) { if (!ModelState.IsValid) { return(View(room)); } try { await _repository.UpdateAsync(RoomViewModel.FromRoomViewModel(room)); return(RedirectToAction(nameof(Index))); } catch { return(View(room)); } }
public void Handle(MessageReceived message) { String roomName = message.RoomName; RoomViewModel activeRoom = this.ViewModel.ActiveRoom; if (activeRoom == null || activeRoom.Name != message.RoomName) { var roomLink = this.chatGroup.Links.OfType <RoomLink>().FirstOrDefault(r => r.RoomName == roomName); if (roomLink != null) { roomLink.UnreadCount++; } } mediaElement.Position = TimeSpan.Zero; mediaElement.Play(); }
/// <summary> /// Converts viewmodel to model /// </summary> /// <param name="model">The model.</param> /// <returns></returns> public static RoomModel ToModel(this RoomViewModel model) { if (model == null) { return(null); } var entity = new RoomModel { FacilityID = model.FacilityID, RoomCapacity = model.RoomCapacity, RoomID = model.RoomID, RoomName = model.RoomName, ModifiedOn = model.ModifiedOn, IsSchedulable = model.IsSchedulable }; return(entity); }
public static ReturnResult Update(int id, RoomViewModel item) { ReturnResult obj = new ReturnResult(); if (item == null || id <= 0) { obj.ProcessingStatus = ProcessingStatus.ValidationFailed; return(obj); } var room = Room.FixBack(item); room.Id = id; room.InsertUpdate(); var updatedroom = Room.FixBack(Room.GetById(new RoomPrimaryKey(Convert.ToInt32(id)))); obj.ReturnObject = updatedroom; return(obj); }
public RoomsControllerTests() { mockRepo = new Mock <IHouseworkRepository>(); mockMapper = new Mock <IMapper>(); kitchen = new Room() { Id = kitchenId, Name = "Kitchen" }; kitchenViewModel = new RoomViewModel() { RoomId = kitchenId, Name = "Kitchen" }; controller = new RoomsController(mockRepo.Object, mockMapper.Object); }
public void PostCreateNewRoomWithInvalidRoomNameShowsCreateView(string roomName) { var controller = CreateController(); var viewModel = new RoomViewModel { Name = roomName }; controller.ViewData.ModelState.AddModelError("Room Name", "Room name is required"); var result = controller.Create(viewModel); Assert.That(result, Is.InstanceOf <ViewResult>()); var viewResult = result as ViewResult; Assert.That(viewResult.View, Is.Null); Assert.That(viewResult.Model, Is.EqualTo(viewModel)); }
public ActionResult EditRoom(int id) { var roomInDb = _roomRepository.GetRoomById(id); var viewModel = new RoomViewModel { Branches = _branchRepository.GetBranches(), Room = roomInDb }; if (roomInDb != null) { return(View("RoomForm", viewModel)); } else { return(RedirectToAction("Index", "Rooms")); } }
/// <summary> /// Updates the current room. /// </summary> /// <param name="currentRoom">The current room.</param> public void UpdateCurrentRoom([CanBeNull] RoomViewModel currentRoom) { if (ViewModel != null) { RouteManager?.UpdateCurrentRoom(currentRoom, ViewModel); } var actionToExecute = (Action)(() => { if (ViewModel != null) { NavigateToCurrentRoom(currentRoom); ViewModel.CurrentRoom = currentRoom; } }); Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, actionToExecute); }
public static Room ToModel(this RoomViewModel viewModel) { if (viewModel != null) { Room model = new Room(); model.Id = viewModel.Id; model.AccommodationId = viewModel.AccommodationId; model.Capacity = viewModel.Capacity; model.Images = viewModel.Images; model.Price = viewModel.Price; model.RegisterId = viewModel.RegisterId; model.RoomTypeId = viewModel.RoomTypeId; model.Status = viewModel.Status; model.Dimension = viewModel.Dimension; return(model); } return(null); }
// Room/Details/{Guid} public ActionResult Details(Guid Id) { // Get images paths by room id from Web Api string[] paths = GetImagesPathsByRoomId(Id); // Get images Srcs for this room and send to view ViewBag.imgSrcs = GetImageSrcs(paths); RoomDTO roomDto = roomService.GetRoomById(Id); RoomViewModel room = Mapper.Map <RoomDTO, RoomViewModel>(roomDto); ViewBag.hotelName = hotelService.GetHotelById(room.HotelId).HotelName; if (room == null) { return(HttpNotFound()); } return(View(room)); }
void INotificationService.ChangeTopic(ChatUser user, ChatRoom room) { bool isTopicCleared = String.IsNullOrWhiteSpace(room.Topic); var parsedTopic = ConvertUrlsAndRoomLinks(room.Topic ?? ""); foreach (var client in user.ConnectedClients) { Clients[client.Id].topicChanged(isTopicCleared, parsedTopic); } // Create the view model var roomViewModel = new RoomViewModel { Name = room.Name, Topic = parsedTopic }; Clients[room.Name].changeTopic(roomViewModel); }
public ActionResult Create(RoomViewModel model) { ActionResult result; if (ModelState.IsValid) { writer.CreateRoom(model); result = RedirectToAction("List"); } else { result = View("Create", model); } return(result); //Changes Sprint 1 -- "I want to view a list of rooms that represent conversations." -- Julie Braford }
public JsonResult Get(int id) { var room = repoRoom.GetById(id); var vm = new RoomViewModel(); vm.RoomId = id; vm.Name = repoRoom.GetRoomName(id); vm.PostCount = room.PostCount; vm.ViewerCount = room.ViewerCount; vm.Category = repoRoom.GetCategory(id); vm.Messages = repoRoom.GetMessages(id); vm.FirstUser = repoRoom.GetUser(room.FirstUserId); vm.SecondUser = repoRoom.GetUser(room.SecondUserId); vm.Topic = repoRoom.GetTopic(id); vm.FirstUserTurn = repoRoom.IsFirstUserTurn(id); return(new JsonResult(vm)); }
// GET: Rooms public ActionResult Index(int page = 1) { RoomViewModel roomView = new RoomViewModel { Rooms = unitOfWork.Rooms.Rooms .OrderBy(room => room.RoomId) .Skip((page - 1) * pageSize) .Take(pageSize), PagingInfo = new PagingInfo { CurrentPage = page, ItemsPerPage = pageSize, TotalItems = unitOfWork.Rooms.Rooms.Count() } }; return(View(roomView)); }
public ActionResult Create(RoomViewModel model) { // Made Changes Sprint 1 -- User Story 1 -- I want to create rooms for categorizing conversations -- Tina Hauck // Made Changes Sprint 1 -- User Story 2 -- I want to view a list of rooms that represent conversations -- Tina Hauck ActionResult result; if (ModelState.IsValid) { writer.CreateRoom(model); result = RedirectToAction("List"); } else { result = View("Create", model); } return(result); }
public override void TestInit() { base.TestInit(); desktopVm = viewModelFactory.GetViewModel <SharedDesktopServerViewModel>(); roomVm = viewModelFactory.GetViewModel <RoomViewModel>(); // errors = viewModelFactory.GetViewModel<ErrorCollectionViewModel>(); mockVnc = new Mock <IVncServer>(); session = new Session { SessionId = Guid.NewGuid(), Room = room, User = user, IsActive = true }; roomVm.SessionId = session.SessionId; mockVnc.SetupAllProperties(); mockVnc.Setup(v => v.IsBrowserSupported()).Returns(true); mockVnc.Setup(v => v.InitializeVnc()).Returns(VncInitializationStatus.Initialized); mockInstaller = new Mock <IVncInstaller>(); desktopVm.VncServer = mockVnc.Object; desktopVm.VncInstaller = mockInstaller.Object; }
public async Task <IActionResult> CreateRoom([FromBody] RoomViewModel room) { if (!this.ModelState.IsValid) { return(this.BadRequest("Bad data")); } try { this.repository.AddRoom(this.mapper.Map <Room>(room)); return(this.Ok("Done")); } catch (Exception ex) { this.logger.LogError($"Failed to create the room: {ex}"); return(this.BadRequest("Error Occurred")); } }
public ActionResult List(int page = 1, RoomSortBy orderBy = RoomSortBy.None, bool desc = false) { RoomViewModel roomView = new RoomViewModel { Rooms = unitOfWork.Rooms.GetAll(orderBy, desc) .Skip((page - 1) * pageSize) .Take(pageSize) , PagingInfo = new PagingInfo { CurrentPage = page, ItemsPerPage = pageSize, TotalItems = unitOfWork.Rooms.Rooms.Count() } }; return(View(roomView)); }
public ActionResult Edit(int id, RoomViewModel model) { try { bool result = _roomService.UpdateRoom(model); if (result) { return(RedirectToAction(nameof(Index))); } throw new Exception(); } catch { ModelState.AddModelError(string.Empty, "Ooops! Something went wrong!"); return(View()); } }
public ActionResult Edit(RoomViewModel model) { var IsAdminUser = (User.IsInRole("Admin") || User.IsInRole("System")) ? true : false; var RoomIsCanEdit = IsAdminUser ? true : IsCanEdit; if (!RoomIsCanEdit) { return(RedirectToAction("Index")); } if (ModelState.IsValid) { // model.HOTELID = 11; model.Edit(); return(RedirectToAction("Edit", new { id = model.ID })); } return(View()); }
public void PostCreateNewRoomWithInvalidRoomNameCausesValidationError(string roomName) // Changes for Sprint # -- User Story -- Developer's Name // Changes for Sprint 1 -- 1.I want to create rooms for categorizing conversations -- Matt Goodson // Sprint 2 -- I want to filter message content so that it is appropriate -- David Bohn { var controller = CreateController(); var viewModel = new RoomViewModel { Name = roomName }; var context = new ValidationContext(viewModel, serviceProvider: null, items: null); var results = new List <ValidationResult>(); var isValid = Validator.TryValidateObject(viewModel, context, results); Assert.That(isValid, Is.False); }
void INotificationService.AllowUser(ChatUser targetUser, ChatRoom targetRoom) { // Build a viewmodel for the room var roomViewModel = new RoomViewModel { Name = targetRoom.Name, Private = targetRoom.Private, Closed = targetRoom.Closed, Topic = targetRoom.Topic ?? String.Empty, Count = _repository.GetOnlineUsers(targetRoom).Count() }; // Tell this client it's allowed. Pass down a viewmodel so that we can add the room to the lobby. Clients.User(targetUser.Id).allowUser(targetRoom.Name, roomViewModel); // Tell the calling client the granting permission into the room was successful Clients.Caller.userAllowed(targetUser.Name, targetRoom.Name); }
public void GetRoomByIdShouldReturnRoom() { var expectedRoom = new RoomViewModel() { Name = "room 1" }; var httpResponse = this.controller .GetRoomById(1) .ExecuteAsync(CancellationToken.None).Result; Assert.AreEqual(HttpStatusCode.OK, httpResponse.StatusCode); var serverResponseJson = httpResponse.Content.ReadAsStringAsync().Result; var room = this.serializer.Deserialize<RoomViewModel>(serverResponseJson); Assert.AreEqual(expectedRoom.Name, room.Name); }
public RoomView(RoomModel model) { InitializeComponent(); DataContext = _viewModel = new RoomViewModel(model); Unloaded += RoomView_Unloaded; }
public ActionResult DeleteRoom(RoomViewModel model) { this.Rooms.DeleteBy(model.Context, this.User.Identity.GetUserId()); this.TempData.Add(ServicesConstants.RoomDeletedKey, model.Name); return this.RedirectToActionPermanent("GetRooms"); }