Example #1
0
        public List <RoomDto> GetAllRooms()
        {
            try
            {
                List <RoomDto> roomList = new List <RoomDto>();

                using (UnitOfWork unitOfWork = new UnitOfWork())
                {
                    var list = from room in unitOfWork.GetRepository <room>().Select(null, null)
                               join depRoom in unitOfWork.GetRepository <departmentroom>().Select(null, null) on room.RoomID equals depRoom.RoomID
                               join dep in unitOfWork.GetRepository <department>().Select(null, null) on depRoom.DepartmentID equals dep.DepartmentID
                               join floor in unitOfWork.GetRepository <floor>().Select(null, null) on room.FloorID equals floor.FloorID
                               select new
                    {
                        RoomID   = room.RoomID,         //Room
                        FloorID  = room.FloorID,
                        RTypeID  = room.RoomTypeID,
                        Name     = room.Name,
                        Map      = room.Map,
                        DPID     = depRoom.DepartmentRoomID,       //DepartmetnRoom
                        DPDepID  = depRoom.DepartmentID,
                        DPRoomID = depRoom.RoomID,
                        DepID    = dep.DepartmentID,
                        DName    = dep.Name,        //Department
                        DDesc    = dep.Description,
                        Dother   = dep.Other,
                        FName    = floor.Name,        //Floor
                    };
                    foreach (var item in list)
                    {
                        RoomDto rDto = new RoomDto();
                        rDto.RoomID     = item.RoomID;
                        rDto.FloorID    = item.FloorID.Value;
                        rDto.RoomTypeID = item.RTypeID.Value;
                        rDto.Name       = item.Name;
                        rDto.Map        = item.Map;
                        //Departman Oda İlişki
                        rDto.DepartmentRoomDto = new DepartmentRoomDto();
                        rDto.DepartmentRoomDto.DepartmentID     = item.DPDepID.Value;
                        rDto.DepartmentRoomDto.DepartmentRoomID = item.DPRoomID.Value;
                        rDto.DepartmentRoomDto.RoomID           = item.RoomID;
                        //Departman
                        rDto.DepartmentDto = new DepartmentDto();
                        rDto.DepartmentDto.DepartmentID = item.DepID;
                        rDto.DepartmentDto.Name         = item.DName;
                        rDto.DepartmentDto.Other        = item.Dother;
                        //Kat
                        rDto.FloorDto         = new FloorDto();
                        rDto.FloorDto.FloorID = item.FloorID.Value;
                        rDto.FloorDto.Name    = item.FName;
                        roomList.Add(rDto);
                    }
                    return(roomList);
                }
            }
            catch (Exception ex)
            {
                return(new List <RoomDto>());
            }
        }
Example #2
0
 public ResultHelper SetRoom(RoomDto roomDto)
 {
     try
     {
         room item = new room();
         item.FloorID = roomDto.FloorID;
         if (string.IsNullOrEmpty(roomDto.Map))
         {
             item.Map = roomDto.Map;
         }
         item.Name       = roomDto.Name;
         item.RoomID     = roomDto.RoomID;
         item.RoomTypeID = roomDto.RoomTypeID;
         using (UnitOfWork unitofWork = new UnitOfWork())
         {
             unitofWork.GetRepository <room>().Update(item);
             unitofWork.saveChanges();
             return(new ResultHelper(true, roomDto.RoomID, ResultHelper.SuccessMessage));
         }
     }
     catch (Exception ex)
     {
         return(new ResultHelper(false, roomDto.RoomID, ResultHelper.UnSuccessMessage));
     }
 }
Example #3
0
        public async Task <IActionResult> PutRoom(int id, RoomDto roomDto)
        {
            if (id != roomDto.Id)
            {
                return(BadRequest());
            }

            try
            {
                await _room.UpdateRoom(roomDto);
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!RoomExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Example #4
0
        private void ValidateRoom(RoomDto roomDto, long adminId)
        {
            if (string.IsNullOrEmpty(roomDto.RoomName))
            {
                throw new ValidationException(ErrorCodes.EmptyUserName);
            }
            if (roomDto.RoomName.Length > 100)
            {
                throw new ValidationException(ErrorCodes.NameExceedLength);
            }
            if (string.IsNullOrEmpty(roomDto.Password))
            {
                throw new ValidationException(ErrorCodes.EmptyPassword);
            }
            if (roomDto.Password.Length < 8 || roomDto.Password.Length > 25)
            {
                throw new ValidationException(ErrorCodes.PasswordLengthNotMatched);
            }

            if (_supervisorService.CheckUserNameDuplicated(roomDto.RoomName, roomDto.RoomId, adminId))
            {
                throw new ValidationException(ErrorCodes.UserNameAlreadyExist);
            }
            if (_receptionistService.CheckUserNameDuplicated(roomDto.RoomName, roomDto.RoomId, adminId))
            {
                throw new ValidationException(ErrorCodes.UserNameAlreadyExist);
            }
            if (_roomService.CheckUserNameDuplicated(roomDto.RoomName, roomDto.RoomId, adminId))
            {
                throw new ValidationException(ErrorCodes.UserNameAlreadyExist);
            }
        }
        // POST api/rooms
        public async Task <HttpResponseMessage> Post([FromBody] RoomDto room)
        {
            try
            {
                var floorsModelAlreadyExists = m_roomsRepo.Get(room.Id) != null;
                if (floorsModelAlreadyExists)
                {
                    // we already have a user with this ID
                    return(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                    {
                        ReasonPhrase = "Floor with this ID already exists."
                    });
                }

                // TODO: link floors with rooms ...
                await m_roomsRepo.Add(new Room { Id = room.Id, DisplayName = room.DisplayName });

                return(new HttpResponseMessage(HttpStatusCode.OK));
            }
            catch (Exception ex)
            {
                return(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    ReasonPhrase = $"Something went wrong when trying to add the floor. ({ex.Message})"
                });
            }
        }
Example #6
0
        public async void Get_Returns_OkObjectResult_With_RoomDto()
        {
            var dto = new RoomDto
            {
                Id       = Guid.NewGuid(),
                StudioId = Guid.NewGuid(),
                Name     = "RoomName"
            };

            _roomService
            .Setup(s => s.GetAsync(It.Is <Guid>(x => x == dto.Id)))
            .Returns(Task.FromResult(dto));

            var result = await _roomsController.Get(dto.Id);

            Assert.IsType <OkObjectResult>(result);

            var okResult = result as OkObjectResult;

            Assert.IsType <RoomDto>(okResult.Value);

            var model = okResult.Value as RoomDto;

            Assert.Equal(dto.Id, model.Id);
            Assert.Equal(dto.StudioId, model.StudioId);
            Assert.Equal(dto.Name, model.Name);
        }
Example #7
0
        public async void CreateRoomAsync_Returns_New_StudioRoomDto()
        {
            var name        = "StudioName";
            var friendlyUrl = "FriendlyUrl";
            var postalCode  = "12345";
            var ownerUserId = Guid.NewGuid();
            var model       = Studio.Create(name, friendlyUrl, postalCode, ownerUserId, _studioValidator.Object);

            _studioRepository
            .Setup(r => r.GetAsync(It.IsAny <Guid>()))
            .Returns(Task.FromResult(model));

            var roomName  = "RoomName";
            var roomModel = Room.Create(model.Id, roomName);

            _studioRepository
            .Setup(r => r.CreateRoomAsync(It.IsAny <Guid>(), It.IsAny <string>()))
            .Returns(Task.FromResult(roomModel));

            var dto = new RoomDto {
                StudioId = model.Id, Name = roomName
            };
            var result = await _studioService.CreateRoomAsync(ownerUserId, model.Id, dto);

            Assert.NotNull(result);
            Assert.Equal(model.Id, result.StudioId);
            Assert.Equal(roomName, result.Name);
        }
Example #8
0
 public Room(RoomDto room)
 {
     Id       = room.Id;
     Name     = room.Name;
     Messages = new List <Message>();
     Users    = new List <User>();
 }
Example #9
0
        //public List<RoomDto> All(int?hid)
        //{
        //    //RoomDto dto = new RoomDto();
        //    //List<RoomDto> listdto = new List<RoomDto>();
        //    //var list = _unitOfWork.RoomRepository.GetAll().Where(x=>x.HotelBlock.Id==hid).ToList();
        //    //foreach (var item in list)
        //    //{
        //    //    dto.Id = item.Id;
        //    //    dto.RoomNum = item.RoomNum;
        //    //    if (item.HotelBlock!=null)
        //    //    {
        //    //    dto.RoomDirection = item.RoomDirection;
        //    //    dto.HotelBlock.Id = item.HotelBlock.Id;
        //    //    }
        //    //    if (item.RoomStatus!=null)
        //    //    {
        //    //        dto.RoomStatus.Id = item.RoomStatus.Id;
        //    //    }
        //    //    listdto.Add(dto);
        //    //    dto = new RoomDto();
        //    //}
        //    //return listdto;
        //}

        public bool Edit(RoomDto dto, bool Editing = false)
        {
            Room n = _unitOfWork.RoomRepository.FindById(dto.Id);

            n.Id            = dto.Id;
            n.RoomNum       = dto.RoomNum;
            n.RoomDirection = dto.RoomDirection;
            n.RoomType      = _unitOfWork.RoomTypeRepository.FindById(dto.RoomType_id);
            n.Isbusy        = dto.Isbusy;
            n.IsInService   = dto.IsInService;
            n.isneedclean   = dto.isneedclean;
            n.IsNeedfix     = dto.IsNeedfix;
            if (!Editing)
            {
                n.Isrequisted    = dto.Isrequisted;
                n.Isrequistedfix = dto.Isrequistedfix;
            }

            n.HotelBlock = _unitOfWork.HotelBlockRepository.FindById(dto.HotelBlock_id);
            n.RoomType   = _unitOfWork.RoomTypeRepository.FindById(dto.RoomType_id);
            _unitOfWork.RoomRepository.Update(n);

            _unitOfWork.SaveChanges();
            return(true);
        }
    private void SetPosition()
    {
        SetPlayerData(Caches.UserDto);
        //重置玩家位置
        Caches.RoomDto.ResetPosition(Caches.UserDto.Id);
        RoomDto roomDto = Caches.RoomDto;

        //设置左边玩家的数据并显示头像
        if (roomDto.LeftId != -1)
        {
            Dispatch(AreaCode.UI, UIEvent.SET_LEFT_PLAYER_DATA, roomDto.uidlistDict[roomDto.LeftId]);
            //判断左边玩家是否已准备
            if (roomDto.readyuidList.Contains(roomDto.LeftId))
            {
                //显示准备按钮
                Dispatch(AreaCode.UI, UIEvent.PLAYER_READY, roomDto.LeftId);
            }
        }
        //设置右边玩家的数据并显示头像
        if (roomDto.RightId != -1)
        {
            Dispatch(AreaCode.UI, UIEvent.SET_RIGHT_PLAYER_DATA, roomDto.uidlistDict[roomDto.RightId]);
            //判断右边玩家是否已准备
            if (roomDto.readyuidList.Contains(roomDto.RightId))
            {
                //显示准备按钮
                Dispatch(AreaCode.UI, UIEvent.PLAYER_READY, roomDto.RightId);
            }
        }
    }
Example #11
0
        public IActionResult GetBooking([FromBody] RoomDto room)
        {
            var roomid   = Convert.ToInt32(room.MeetingRoomId);
            var bookings = _meetingRoomService.GetBooking(roomid);

            if (bookings == null)
            {
                return(StatusCode(StatusCodes.Status204NoContent, new { message = "No bookings yet" }));
            }
            var room_bookings = new List <Object>();

            foreach (var booking in bookings)
            {
                var user = _userService.GetUserById(booking.UserId.ToString());
                room_bookings.Add(new
                {
                    BookingId     = booking.BookingId,
                    MeetingRoomId = booking.MeetingRoomId,
                    EvenId        = booking.EventId,
                    StartTime     = booking.StartTime,
                    EndTime       = booking.EndTime,
                    UserId        = user.Userid,
                    UserName      = user.Username,
                    Email         = user.Email
                });
            }
            return(Ok(room_bookings));
        }
Example #12
0
        public Room Create(RoomCreationOptions options, P2PGroup p2pGroup)
        {
            using (_sync.Lock())
            {
                uint id = 1;
                while (true)
                {
                    if (!_rooms.ContainsKey(id))
                    {
                        break;
                    }
                    id++;
                }

                var room = new Room(this, id, options, p2pGroup, options.Creator);
                _rooms.TryAdd(id, room);
                RoomDto roomDto = new RoomDto();
                roomDto.RoomId      = (byte)room.Id;
                roomDto.PlayerCount = (byte)room.Players.Count;
                roomDto.PlayerLimit = room.Options.PlayerLimit;
                roomDto.State       = (byte)room.GameRuleManager.GameRule.StateMachine.State;
                roomDto.State2      = (byte)room.GameRuleManager.GameRule.StateMachine.State;
                roomDto.GameRule    = (int)room.Options.GameRule;
                roomDto.Map         = (byte)room.Options.MapID;
                roomDto.WeaponLimit = room.Options.ItemLimit;
                roomDto.Name        = room.Options.Name;
                roomDto.Password    = room.Options.Password;
                roomDto.FMBURNMode  = room.GetFMBurnModeInfo();
                Channel.Broadcast(new RoomDeployAck2Message(roomDto));

                return(room);
            }
        }
Example #13
0
        public async Task <Room> UpdateRoom(int id, RoomDto roomDto)
        {
            var room = mapper.Map <Room>(roomDto);

            if (!(await isRoomExist(id)))
            {
                throw new RoomNotFoundException("room not exist");
            }


            if (roomDto.Name != null)
            {
                if (!(await isRoomNameUnique(roomDto.Name)))
                {
                    throw new RoomNameMustBeUniqueException();
                }
            }
            Room updatedRoom = await roomRepository.UpdateRoomById(id, room);

            if (updatedRoom != null)
            {
                await roomRepository.SaveChanges();

                Console.WriteLine("Updated Room = " + updatedRoom);
                return(updatedRoom);
            }
            throw new RoomNotFoundException("Room not exist");
        }
Example #14
0
        public void CreateRoom_UnderNormalConditions_AddsRoomToRoomList()
        {
            //arrange
            var originalCountOfRooms = _roomList.Count;
            var roomToCreate         = new RoomDto()
            {
                RoomId          = 5,
                RoomDescription = "room description 5",
                RoomName        = "room name 5"
            };

            var mockRepo = Mock.Create <IRoomRepository>();

            Mock.Arrange(() => mockRepo.Create(Arg.IsAny <Room>())).DoInstead(() => _roomList.Add(roomToCreate)).OccursOnce();

            _roomService = new RoomService(mockRepo);

            //act
            _roomService.Create(roomToCreate);
            var actualCountOfRooms = _roomList.Count;

            //assert
            Mock.Assert(mockRepo);
            Assert.That(actualCountOfRooms, Is.EqualTo(originalCountOfRooms + 1));
        }
Example #15
0
        public async Task <ActionResult <RoomDto> > Put(int id, RoomDto model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest("Model is not valid"));
                }

                var oldRoom = await _roomServices.GetRoomByIdAsync(id);

                if (oldRoom == null)
                {
                    return(NotFound($"Could not find camp with id of {id}"));
                }

                var updatedRoom = _mapper.Map(model, oldRoom);

                if (await _roomServices.UpdateRoom(updatedRoom))
                {
                    return(Ok(updatedRoom));
                }
            }
            catch (Exception e)
            {
                return(this.StatusCode(StatusCodes.Status500InternalServerError, $"Database Failure: {e}"));
            }

            return(BadRequest());
        }
Example #16
0
        public async Task AddRoom(RoomDto roomDto, string creatorId)
        {
            var room = mapper.Map <Room>(roomDto);

            Room isRoomNameNotUnique = await roomRepository.GetRoomByName(room.Name);

            if (isRoomNameNotUnique != null)
            {
                throw new RoomNameMustBeUniqueException();
            }

            room.CreatedAt = DateTime.Now;
            room.CreatorId = creatorId;
            await roomRepository.SaveRoom(room);

            await roomRepository.SaveChanges();

            if (room != null)
            {
                Team newTeam = new Team()
                {
                    Name        = $" {room.Name}/main ",
                    Description = room.Description,
                    CreatedAt   = DateTime.Now,
                    LeaderId    = creatorId
                };

                await teamService.AddTeam(newTeam, room.Id, creatorId, 0);


                return;
            }
            throw new  RoomNotFoundException("Error While Saving the Room");
        }
        public async void CanCreateRoomAndSaveToDatabase()
        {
            DbContextOptions <AsyncInnDbContext> options = new DbContextOptionsBuilder <AsyncInnDbContext>()
                                                           .UseInMemoryDatabase("CanCreateRoomAndSaveToDatabase")
                                                           .Options;

            using AsyncInnDbContext context = new AsyncInnDbContext(options);

            AmenityManager amenities = new AmenityManager(context);

            RoomManager service = new RoomManager(context, amenities);

            var dto = new RoomDto()
            {
                Name = "Test", Layout = "0"
            };

            Assert.Equal(0, context.Rooms.CountAsync().Result);

            var result = await service.CreateRoom(dto);

            var actual = context.Rooms.FindAsync(result.Id).Result;

            Assert.Equal(1, await context.Rooms.CountAsync());
            Assert.IsType <Room>(actual);
            Assert.Equal(1, actual.Id);
            Assert.Equal("Test", actual.Name);
            Assert.Equal(Layout.Studio, actual.Layout);
        }
Example #18
0
        public static RoomDto ToRoomDto(this Room model)
        {
            if (model == null)
            {
                return(null);
            }

            var dto = new RoomDto
            {
                Id           = model.Id,
                AddedDate    = model.AddedDate,
                Capacity     = model.Capacity,
                Color        = model.Color,
                Description  = model.Description,
                IpAddress    = model.IPAddress,
                ModifiedDate = model.ModifiedDate,
                Name         = model.Name
            };

            if (model.Place != null)
            {
                dto.PlaceId = model.Place.Id;
            }

            return(dto);
        }
Example #19
0
        public async void roomMaker(int id, int Aid, string name, int[] users)
        {
            HttpClient client = new HttpClient();

            client.BaseAddress = uri;
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            try
            {
                var club = new  RoomDto()
                {
                    roomId      = id,
                    roomAdminId = Aid,
                    roomName    = name,
                    users       = users
                };
                var response = await client.PostAsJsonAsync("/Rooms/register", club);

                if (response.IsSuccessStatusCode)
                {
                    MessageBox.Show("Register Successfully");
                }
                else
                {
                    MessageBox.Show("Register Failed...");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
Example #20
0
 public Room(RoomDto roomDto)
 {
     Length          = roomDto.Length;
     Width           = roomDto.Width;
     NumberOfWindows = roomDto.NumberOfWindows;
     NumberOfDoors   = roomDto.NumberOfDoors;
 }
Example #21
0
        public bool IsGameEnd(RoomDto room)
        {
            if (IsDraw(room))
            {
                return(true);
            }
            for (var i = 0; i < 3; i++)
            {
                if (room.PlayingField[i][0] != 0 &&
                    room.PlayingField[i][0] == room.PlayingField[i][1] &&
                    room.PlayingField[i][0] == room.PlayingField[i][2])
                {
                    return(true);
                }
                if (room.PlayingField[0][i] != 0 &&
                    room.PlayingField[0][i] == room.PlayingField[1][i] &&
                    room.PlayingField[0][i] == room.PlayingField[2][i])
                {
                    return(true);
                }
            }
            if (room.PlayingField[0][0] != 0 &&
                room.PlayingField[0][0] == room.PlayingField[1][1] &&
                room.PlayingField[0][0] == room.PlayingField[2][2])
            {
                return(true);
            }

            return(room.PlayingField[0][2] != 0 &&
                   room.PlayingField[0][2] == room.PlayingField[1][1] &&
                   room.PlayingField[0][2] == room.PlayingField[2][0]);
        }
Example #22
0
        public ActionResult Edit(RoomDto roomDto, int DepartmentID, int DepartmentRoomID, HttpPostedFileBase mapFile)
        {
            if (mapFile != null)
            {
                if (mapFile.ContentLength > 0)
                {
                    string _FileName = roomDto.Name + "_" + Path.GetFileName(mapFile.FileName);
                    string _path     = Path.Combine(Server.MapPath("~/Maps/Room"), _FileName);
                    mapFile.SaveAs(_path);
                    roomDto.Map = _FileName;
                }
            }
            ResultHelper result = JsonConvert.DeserializeObject <ResultHelper>(roomService.SetRoom(roomDto));

            if (result.Result)
            {
                ResultHelper resultC = JsonConvert.DeserializeObject <ResultHelper>(departmentRoomService.SetDepartmentRoom(new DepartmentRoomDto
                {
                    DepartmentRoomID = DepartmentRoomID,
                    DepartmentID     = DepartmentID,
                    RoomID           = result.ResultSet,
                    Other            = null,
                }));
                ViewBag.Message = Helper.GetResultMessage(resultC.Result, result.ResultDescription);
            }
            else
            {
                ViewBag.Message = Helper.GetResultMessage(result.Result, result.ResultDescription);
            }

            GetAllDropdowns();
            return(View());
        }
Example #23
0
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
            {
                return(Application.Current.Resources["DefaultRoomWidth"]);
            }
            else
            {
                RoomDto roomDto = value as RoomDto;
                switch (roomDto.Type)
                {
                case RoomType.Single:
                    return(Application.Current.Resources["SingleRoomWidth"]);

                case RoomType.Double:
                    return(Application.Current.Resources["DoubleRoomWidth"]);

                case RoomType.Family:
                    return(Application.Current.Resources["FamilyRoomWidth"]);

                default:
                    return(Application.Current.Resources["DefaultRoomWidth"]);
                }
            }
        }
Example #24
0
 public IActionResult AddRoom([FromBody] RoomModel room)
 {
     try
     {
         if (room == null)
         {
             return(BadRequest("Empty body request"));
         }
         else
         {
             RoomDto room1 = new RoomDto
             {
                 //Id = room.Id,
                 Description      = room.Description,
                 ReservationPrize = room.ReservationPrize
             };
             _db.Rooms.Add(room1);
             _db.SaveChanges();
             return(Created("Room Added", room1));
         }
     }
     catch (Exception ex)
     {
         return(BadRequest("Bład przy dodawaniu pokoju do bazy /n" + ex.Message));
     }
 }
        private static UpdateMessagesResult UpdateRoomMessages(Room room, RoomDto dto)
        {
            // Select removed and added messages
            var added = new HashSet <long>(dto.Messages.Select(m => m.Id));

            foreach (var message in room.Messages)
            {
                added.Remove(message.Id);
            }

            var removed = new HashSet <long>(room.Messages.Select(m => m.Id));

            foreach (var message in dto.Messages)
            {
                removed.Remove(message.Id);
            }

            // Add and remove messages
            foreach (var messageId in removed)
            {
                room.RemoveMessage(messageId);
            }

            foreach (var message in dto.Messages)
            {
                if (!added.Contains(message.Id))
                {
                    continue;
                }

                room.AddMessage(new Message(message));
            }

            return(new UpdateMessagesResult(added, removed));
        }
Example #26
0
        public IActionResult SaveRoom([FromBody] RoomDto entityDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }
            Room item = new Room
            {
                Number = entityDto.Number,
                Type   = entityDto.Type,
                Price  = entityDto.Price
            };

            _context.Rooms.Add(item);

            try
            {
                _context.SaveChanges();
            }
            catch (Exception)
            {
                throw;
            }

            return(Ok(item));
        }
        private static HashSet <UserId> UpdateRoomUsers(Room room, RoomDto dto)
        {
            var removed = new HashSet <UserId>(room.Users);
            var added   = new HashSet <UserId>(dto.Users);

            foreach (var nick in room.Users)
            {
                added.Remove(nick);
            }
            foreach (var nick in dto.Users)
            {
                removed.Remove(nick);
            }

            foreach (var nick in removed)
            {
                room.RemoveUser(nick);
            }

            foreach (var nick in added)
            {
                room.AddUser(nick);
            }

            return(removed);
        }
Example #28
0
        public int Add(RoomDto dto)
        {
            var model = Mapper.Map <RoomDto, Room>(dto);

            model.HotelBlock  = _unitOfWork.HotelBlockRepository.FindById(dto.HotelBlock_id);
            model.RoomType    = _unitOfWork.RoomTypeRepository.FindById(dto.RoomType_id);
            model.Isrequisted = false;
            //Room n = new Room();

            //n.Id = dto.Id;
            //n.RoomNum = dto.RoomNum;
            //n.HotelBlock =;

            //n.RoomDirection = dto.RoomDirection;
            //n.RoomType.Id = dto.RoomType;
            //n.Isbusy = dto.Isbusy;
            //n.IsInService = dto.IsInService;
            //n.isneedclean = dto.isneedclean;
            //n.IsNeedfix = dto.IsNeedfix;



            _unitOfWork.RoomRepository.Add(model);
            _unitOfWork.SaveChanges();
            return(model.Id);
        }
        private static void UpdateRoomFiles(Room room, RoomDto dto)
        {
            // Select removed and added files
            var added = new HashSet <FileId>(dto.Files.Select(f => f.Id));

            foreach (var file in room.Files)
            {
                added.Remove(file.Id);
            }

            var removed = new HashSet <FileId>(room.Files.Select(f => f.Id));

            foreach (var file in dto.Files)
            {
                removed.Remove(file.Id);
            }

            // Add and remove files
            foreach (var fileId in removed)
            {
                room.RemoveFile(fileId);
            }

            foreach (var file in dto.Files)
            {
                if (!added.Contains(file.Id))
                {
                    continue;
                }

                room.AddFile(new FileDescription(file));
            }
        }
        public IActionResult CreateRoom([FromBody] RoomDto roomDto)
        {
            var room = _mapper.Map <Room>(roomDto);
            var user = _userService.GetById(Int32.Parse(User.Identity.Name));

            if (user == null)
            {
                return(Unauthorized());
            }

            var validator = new RoomValidator();
            var result    = validator.Validate(roomDto);

            try
            {
                if (!result.IsValid)
                {
                    throw new ApplicationException(string.Join(",", result.Errors));
                }

                var returnedRoom = _roomService.Create(room, roomDto.Password);

                _userRoomService.Create(user, room, true);

                return(StatusCode(201, new
                {
                    returnedRoom.Id,
                    returnedRoom.Title
                }));
            }
            catch (ApplicationException ex)
            {
                return(BadRequest(ex.Message));
            }
        }
        ///<summary>
        /// Converts Room/CombinedRoom to RoomDto
        ///</summary>
        ///<param name="room">Room</param>
        ///<returns>RoomDto</returns>
        public static RoomDto ConvertRoomToDto(Room room)
        {
            if (room != null)
            {
                var roomDto = new RoomDto
                {
                    Id = room.Id,
                    Code = room.Code,
                    Name = room.Name,
                    DisplayOrder = room.DisplayOrder,
                    IsCombined = room.IsCombined,
                };

                // Check if the room is combined and populate the list of AssociatedRoomIds
                if (room.IsCombined)
                {
                    roomDto.AssociatedRoomIds = new List<int>();
                    foreach (Room associatedRoom in ((CombinedRoom)room).Rooms)
                    {
                        roomDto.AssociatedRoomIds.Add(associatedRoom.Id);
                    }
                }

                return roomDto;
            }
            return null;
        }