protected void Button1_Click(object sender, EventArgs e)
        {
            IUserComponent userservice = new UserComponent();
            IBookingComponent bookingservice = new BookingComponent();
            User user = new User();
            Booking booking = new Booking();

            //booking.UserID = ((User)Session["UserSession"]).ID;
            booking.UserID = ((User)Session["UserSession"]).ID;
            booking.RoomID = int.Parse(DropDownList1.SelectedValue);
            booking.StartDate = clnstart.SelectedDate;
            booking.EndDate = clnEnd.SelectedDate;
           // booking.refNum = lblBookingID.Text;
            try
            {

                bookingservice.AddBooking(booking);
                lblBookingID.Text = "You have successfully booked room your refrence number is " + "<b>" + booking.RefNum + "</b>";


            }
            catch (Exception ex)
            {
                
                throw ex;
            }

        }
        private void ViewBookingDetail()
        {
            Booking book = new Booking();

            book.RefNum = txtRefNum.Text.Trim();

            BookingComponent serv = new BookingComponent();

            serv.ViewBooking(ref book);
            lblID.Text = book.ID.ToString();

            calStartDate.SelectedDate = book.StartDate;
            calEndDate.SelectedDate = book.EndDate;
            ddlRoom.SelectedValue = book.RoomID.ToString();

            foreach (AssetBooking asset in book.AssetBookings)
            {

                for (int i = 0; i < lstAssetList.Items.Count; i++)
                {
                    if (asset.AssetID == int.Parse(lstAssetList.Items[i].Value))
                    {
                        lstSelectedAsset.Items.Add(lstAssetList.Items[i]);
                        lstAssetList.Items.RemoveAt(i);

                        break;
                    }
                }

            }

        }
        protected void Button1_Click(object sender, EventArgs e)
        {
          //  IUserService userservice = new UserService();
            IBookingComponent bookingservice = new BookingComponent();
         //   User user = new User();
            Booking booking = new Booking();
            try
            {
              
                //booking.ID = int.Parse(lblID.Text);
                //booking.RoomID = (int.Parse)(txtroomid.Text);
                //booking.StartDate = DateTime.Parse(txtstartdate.Text);
                //booking.EndDate = DateTime.Parse(txtenddate.Text);
                booking.RefNum = txtrefnum.Text;
                bookingservice.ViewBooking(ref booking);
                txtroomid.Text = booking.RoomID.ToString();
                txtstartdate.Text = booking.StartDate.ToString();
                txtenddate.Text = booking.EndDate.ToString();
                

               // lblstatus.Text = "Your Booking has been update!" + booking.RefNum;
               
                
                    
                
 
            }
            catch (Exception)
            {
                
                throw;
            }
        }
        protected void btnviewbooking_Click(object sender, EventArgs e)
        {
            //IUserService userservice = new UserService();
            //IBookingService bookingservice = new BookingService();
            //User user = new User();
            //Booking booking = new Booking();
            //booking.RefNum = txtrefnum.Text;
            //try
            //{
            //    bookingservice.ViewBooking(ref booking);
            //    lblID.Text = booking.ID.ToString();
            //    lblLoginID.Text = user.LoginID;
            //   txtroomid.Text = booking.RoomID.ToString();
            //    txtstartdate.Text = booking.StartDate.ToString();
            //    txtenddate.Text = booking.EndDate.ToString();
            //}
            //catch (Exception ex)
            //{
            //    if (IsPostBack)
            //    {
            //        lblstatus.Text = ex.Message;
            //    }
            //}
            IBookingComponent bookingservice = new BookingComponent();
            //   User user = new User();
            Booking booking = new Booking();
            try
            {

                //booking.ID = int.Parse(lblID.Text);
                //booking.RoomID = (int.Parse)(txtroomid.Text);
                //booking.StartDate = DateTime.Parse(txtstartdate.Text);
                //booking.EndDate = DateTime.Parse(txtenddate.Text);
                booking.RefNum = txtrefnum.Text;
                bookingservice.ViewBooking(ref booking);
                txtroomid.Text = booking.RoomID.ToString();
                txtstartdate.Text = booking.StartDate.ToString();
                txtenddate.Text = booking.EndDate.ToString();


                // lblstatus.Text = "Your Booking has been update!" + booking.RefNum;





            }
            catch (Exception)
            {

                throw;
            }
           
           
        }
        public void AddBooking(Booking booking)
        {
            try
            {
                bookingRepository.Add(booking);
            }
            catch (Exception)
            {

                throw;
            }
        }
        public bool CancelBooking(Booking booking)
        {
            IBookingComponent component = new BookingComponent();

            try
            {
                component.CancelBooking(booking);
            }
            catch(Exception e)
            {
                throw new FaultException(e.Message);
            }
            return true;
        }
 protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
 {
     try
     {
         using (IBookingComponent bookingservice = new BookingComponent())
         {
             Booking booking = new Booking();
             booking.ID = int.Parse(GridView1.DataKeys[Int32.Parse(e.CommandArgument.ToString())].Value.ToString());
             bookingservice.CancelBooking(booking);
             lblID.Text = "Your Booking has been cnaceled";
             RefreshGridView();
            
         }
     }
     catch (Exception ex)
     {
         
         throw new Exception (ex.Message);
     }
 }
        public bool Add(Booking booking)
        {
            bool result = false;

            try
            {
                using (var session = NHibernateHelper.OpenSession(connString))
                {
                    var book = session.CreateSQLQuery("EXEC USP_MAKE_BOOKING :UserID, :RoomID, :StartDate, :EndDate")
                           .AddEntity(typeof(Booking))
                           .SetParameter("UserID", booking.UserID)
                           .SetParameter("RoomID", booking.RoomID)
                           .SetParameter("StartDate", booking.StartDate)
                           .SetParameter("EndDate", booking.EndDate)
                           .List<Booking>();

                    if (book.AsQueryable<Booking>().Count() > 0)
                    {
                        Booking detail = book.SingleOrDefault<Booking>();

                        foreach (AssetBooking asset in booking.AssetBookings)
                        {
                            var assetBooking = session.CreateSQLQuery("EXEC USP_SAVE_ASSET_BOOKING :BookingID, :AssetID, :Status")
                           .SetParameter("BookingID", detail.ID)
                           .SetParameter("AssetID", asset.AssetID)
                           .SetParameter("Status", asset.Status)
                           .UniqueResult();
                        }

                        booking.RefNum = detail.RefNum;
                    }
                }

            }
            catch (Exception)
            {
                throw;
            }
            return result;
        }
        public Booking SaveBooking(Booking booking)
        {
            IBookingComponent component = new BookingComponent();

            try
            {
                component.Save(booking);
            }
            catch (RoomClashException e)
            {
                var fault = new RoomClashFault() { Clashes = e.Clashes };
                throw new FaultException<RoomClashFault>(fault);
            }
            catch (AssetClashException e)
            {
                var fault = new AssetClashFault() { Clashes = e.Clashes };
                throw new FaultException<AssetClashFault>(fault);
            }
            catch (Exception e)
            {
                throw new FaultException(e.Message);
            }
            return booking;
        }
        public void ViewBooking(ref Booking booking)
        {
            try
            {

                List<Booking> detail = bookingRepository.ViewBooking(booking).ToList();

                foreach (Booking book in detail)
                {
                    if (book.ID == 0)
                    {
                        throw (new Exception("your refrence number is not valid."));

                    }

                    booking = book;
                }

            }
            catch (Exception)
            {
                throw;
            }
        }
        public void Save(Booking booking)
        {
#if DEBUG
            Thread.Sleep(3000);
#endif
            try
            {
                if (booking.StartDate.ToShortDateString() == "1/1/0001")
                    throw new Exception("StartDate is a require field");
                if (booking.EndDate.ToShortDateString() == "1/1/0001")
                    throw new Exception("EndDate is a require field");
                if(booking.StartDate >= booking.EndDate)
                    throw new Exception("EndDate must be greater than StartDate");
                if (booking.RoomID == 0 && booking.AssetBookings.Count == 0)
                    throw new Exception("Please select a room or asset to book");

                // Check if room is available
                var conflictingBookings = CheckRoomAvailability(booking);
                if (conflictingBookings.Count() > 0)
                {
                    throw new RoomClashException() { Clashes = conflictingBookings };
                }

                // Check if assets are available
                var conflictingAssetBookings = CheckAssetAvailability(booking);
                if (conflictingAssetBookings.Count() > 0)
                {
                    throw new AssetClashException() { Clashes = conflictingAssetBookings };
                }

                if (booking.ID > 0)
                {
                    bookingRepository.Update(booking);
                }
                else
                {
                    bookingRepository.Add(booking);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                BookingComponent bookServ = new BookingComponent();

                Booking detail = new Booking();

                detail.ID = 0;
                detail.IsCanceled = false;
                //detail.UserID = 3;
                detail.UserID = 3;
                detail.StartDate = calStartDate.SelectedDate;
                detail.EndDate = calEndDate.SelectedDate;

                if (ddlRoom.SelectedIndex > 0)
                    detail.RoomID = int.Parse(ddlRoom.SelectedValue);

                if (lstSelectedAsset.Items.Count > 0)
                {
                    //detail.AssetBooked = new List<AssetBooking>();

                    foreach (ListItem selectedItem in lstSelectedAsset.Items)
                    {
                        AssetBooking bookAsset = new AssetBooking();
                        bookAsset.Status = true;
                        bookAsset.AssetID = int.Parse(selectedItem.Value);

                        detail.AssetBookings.Add(bookAsset);
                    }
                }

                bookServ.Save(detail);

                lblMessage.Text = "Booking created successful, your reference number is <b>" + detail.RefNum + "</b>"; 
            }
            catch (Exception ex)
            {
                lblMessage.Text = "Fail to create booking. " + ex.Message;
            }
        }
 public bool Delete(Booking entity)
 {
     throw new NotImplementedException();
 }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                BookingComponent bookServ = new BookingComponent();

                Booking detail = new Booking();

                detail.ID = int.Parse(lblID.Text);
                detail.IsCanceled = false;
                //detail.UserID = 3;
                detail.UserID = 3;
                detail.RefNum = txtRefNum.Text.Trim();
                detail.StartDate = calStartDate.SelectedDate;
                detail.EndDate = calEndDate.SelectedDate;

                if (ddlRoom.SelectedIndex > 0)
                    detail.RoomID = int.Parse(ddlRoom.SelectedValue);
                else
                    detail.RoomID = 0;

                if (lstSelectedAsset.Items.Count > 0)
                {
                    //detail.AssetBooked = new List<AssetBooking>();

                    foreach (ListItem selectedItem in lstSelectedAsset.Items)
                    {
                        AssetBooking bookAsset = new AssetBooking();
                        bookAsset.Status = true;
                        bookAsset.AssetID = int.Parse(selectedItem.Value);

                        detail.AssetBookings.Add(bookAsset);
                    }
                }

                bookServ.Save(detail);
                lblMessage.Text = "Update successful";
            }
            catch (Exception)
            {
                lblMessage.Text = "Update fail";
            }
        }
 public void CancelBooking(Booking booking)
 {
     try
     {
         using (var session = NHibernateHelper.OpenSession(connString))
         {
             var update = session.CreateSQLQuery("USP_CANCEL_BOOKING :ID")
                 .SetParameter("ID", booking.ID)
                 .UniqueResult();
         }
     }
     catch (Exception)
     {
         throw;
     }
 }
        public void EditBooking(Booking booking)
        {
            try
            {
                bookingRepository.Update(booking);
            }
            catch (Exception)
            {

                throw;
            }
        }
        // TODO: find out if this method is really needed, doesn't seem to make sense
        public IEnumerable<Booking> ViewBooking(Booking booking)
        {
            try
            {
                using (var session = NHibernateHelper.OpenSession(connString))
                {
                    var bookingList = session.Query<Booking>().Where(x => x.RefNum == booking.RefNum).ToList();

                    return bookingList.AsQueryable<Booking>();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public void Update(Booking booking)
        {
            try
            {
                using (var session = NHibernateHelper.OpenSession(connString))
                {
                    var book = session.CreateSQLQuery("EXEC USP_EDIT_BOOKING :ID, :RoomID, :StartDate, :EndDate, :ModifiedBy")
                           .SetParameter("ID", booking.ID)
                           .SetParameter("RoomID", booking.RoomID, NHibernateUtil.Int32)
                           .SetParameter("StartDate", booking.StartDate)
                           .SetParameter("EndDate", booking.EndDate)
                           .SetParameter("ModifiedBy", booking.ModifiedBy)
                           .UniqueResult();

                    foreach (AssetBooking asset in booking.AssetBookings)
                    {
                        var assetBooking = session.CreateSQLQuery("EXEC USP_SAVE_ASSET_BOOKING :BookingID, :AssetID, :Status")
                       .SetParameter("BookingID", booking.ID)
                       .SetParameter("AssetID", asset.AssetID)
                       .SetParameter("Status", asset.Status)
                       .UniqueResult();
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
 public List<string> getBookedItem(Booking booking)
 {
     List<string> bookedItems = bookingRepository.getBookedItems(booking.ID, booking.StartDate, booking.EndDate).ToList();
     return bookedItems;
 }
 public IEnumerable<Booking> CheckAssetAvailability(Booking booking)
 {
     IBookingComponent component = new BookingComponent();
     var clashes = component.CheckAssetAvailability(booking);
     return clashes;
 }
        private void MakeBooking()
        {
            // Fill in the blanks
            _booking.RoomID = _room.ID;
            _booking.StartDate = StartDate.Add(StartTime);
            _booking.EndDate = EndDate.Add(EndTime);
            _booking.UserID = StateManager.CurrentUser.ID;

            if (_booking.ID > 0)
                _booking.ModifiedBy = StateManager.CurrentUser.ID;

            // Assets
            _booking.AssetBookings = new List<AssetBooking>();
            foreach (var asset in AssetList)
            {
                if (asset.IsSelected)
                {
                    _booking.AssetBookings.Add(new AssetBooking()
                    {
                        AssetID = asset.Asset.ID,
                        Status = true
                    });
                }
            }

            MessengerInstance.Send(new LoadingMessage("Saving booking..."));

            Exception exceptionResult = null;
            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += (object sender, DoWorkEventArgs e) =>
            {
                try
                {
                    _booking = _bookingService.SaveBooking(_booking);
                }
                catch (Exception ex)
                {
                    exceptionResult = ex;
                }
            };
            worker.RunWorkerCompleted += (object sender, RunWorkerCompletedEventArgs e) =>
            {
                if (exceptionResult != null)
                {
                    if (exceptionResult is FaultException<RoomClashFault>)
                    {
                        var clashFault = ((FaultException<RoomClashFault>)exceptionResult).Detail;
                        IsConflicting = true;
                        BookingConflicts = new ObservableCollection<Booking>(clashFault.Clashes);
                        MessageBox.Show(@"That room is no longer available for the chosen time. 
Please choose a different room or time.", 
                            "Room no longer available", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    }
                    else if (exceptionResult is FaultException<AssetClashFault>)
                    {
                        var clashFault = ((FaultException<AssetClashFault>)exceptionResult).Detail;
                        MessageBox.Show(@"Some of the assets are no longer available for the chosen time. Please choose a different asset or time.",
                            "Assets no longer available", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    }
                    else
                    {
                        MessageBox.Show(exceptionResult.Message, "Error creating booking", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                    MessengerInstance.Send(new LoadingMessage(false));
                    return;
                }
                if (_isNewBooking)
                {
                    MessageBox.Show(
                        String.Format(@"Your booking has been made!
Your booking reference number is: {0}", _booking.RefNum), 
                            "Booking created", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                else
                {
                    MessageBox.Show("Your booking has been updated.", "Booking updated", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                MessengerInstance.Send(new LoadingMessage(false));

                // Go back to bookings list
                Cancel();
            };
            worker.RunWorkerAsync();

        }
        public void CancelBooking(Booking booking)
        {
            try
            {
                if (booking.ID > 0)
                {
                    bookingRepository.CancelBooking(booking);
                }
                else
                {

                }
                //return true;
            }
            catch (Exception)
            {

                throw;
            }

        }
        private void CheckAvailability()
        {
            // Execute only if all required fields have been filled and are validated
            if (!IsValid)
            {
                return;
            }
            var booking = new Booking()
            {
                ID = Booking.ID,
                StartDate = StartDateTime,
                EndDate = EndDateTime,
                RoomID = Room.ID,
                AssetBookings = (from asset in AssetList
                                select new AssetBooking() { AssetID = asset.Asset.ID }).ToList()
            };
            

            List<Booking> roomResults = null;
            List<Booking> assetResults = null;

            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += (object sender, DoWorkEventArgs e) =>
            {
                roomResults = new List<Booking>(_bookingService.CheckRoomAvailability(booking));
                assetResults = new List<Booking>(_bookingService.CheckAssetAvailability(booking));
            };
            worker.RunWorkerCompleted += (object sender, RunWorkerCompletedEventArgs e) =>
            {
                bool hasRoomConflicts = false;
                bool hasAssetConflicts = false;
                
                // Handle room conflicts
                BookingConflicts = new ObservableCollection<Booking>(roomResults);
                if (roomResults.Count > 0)
                {
                    hasRoomConflicts = true;
                }

                // Handle asset conflicts
                // Remove all existing conflics from every asset
                foreach (var asset in AssetList)
                {
                    asset.Conflicts.Clear();
                }
                if (assetResults.Count > 0)
                {
                    if (BookingConflicts.Count > 0)
                    {
                        BookingConflicts.Union(new ObservableCollection<Booking>(assetResults));
                    }
                    else
                    {
                        BookingConflicts = new ObservableCollection<Booking>(assetResults);
                    }

                    foreach (Booking result in assetResults)
                    {
                        foreach (var item in result.AssetBookings)
                        {
                            var assetQuery = from assetListItem in AssetList
                                             where assetListItem.Asset.ID == item.AssetID
                                             select assetListItem;
                            var asset = assetQuery.FirstOrDefault();
                            if (asset != null)
                            {
                                asset.Conflicts.Add(item);
                                if (asset.IsSelected)
                                {
                                    hasAssetConflicts = true;
                                }
                            }
                        }
                    }
                }
                IsConflicting = hasRoomConflicts || hasAssetConflicts;

                RaisePropertyChanged("BookingConflicts");
                RaisePropertyChanged("IsConflicting");
            };
            worker.RunWorkerAsync();
        }
        public BookingsFormViewModel(Booking booking)
            : base()
        {
            _booking = booking;

            // Initialize fields
            if (IsInDesignMode)
            {
                // Hardcoded design time data
                RoomList = new ObservableCollection<Room>()
                {
                    new Room() { Name = "Winterfell", Location = "25th floor", Capacity = 10 },
                    new Room() { Name = "King's Landing", Location = "24th floor", Capacity = 8 }
                };

                _isConflicting = true;
            }
            else
            {
                _bookingService = new BookingServiceClient();
                _roomService = new RoomServiceClient();
                _assetService = new AssetComponent();
                _isConflicting = false;
                RefreshRooms();
                RefreshAssets();
            }

            if (_booking == null)
            {
                // New booking
                _isNewBooking = true;
                _booking = new Booking();

                // Default booking dates are today
                _startDate = DateTime.Today;
                _endDate = DateTime.Today;
                // Default booking start time is now + rounded up to next half hour
                var startHour = DateTime.Now.Hour;
                var startMinute = DateTime.Now.Minute;
                if (startMinute < 30 && startMinute > 0)
                {
                    startMinute = 30;
                }
                else if (startMinute > 30)
                {
                    startMinute = 0;
                    startHour++;
                }
                _startTime = new TimeSpan(startHour, startMinute, 0);
                // Default booking end time is one hour later
                _endTime = _startTime + TimeSpan.FromHours(1);
                getBookedItem();
            }
            else
            {
                // Edit booking
                _isNewBooking = false;

                _startDate = _booking.StartDate.Date;
                _startTime = _booking.StartDate.TimeOfDay;
                _endDate = _booking.EndDate.Date;
                _endTime = _booking.EndDate.TimeOfDay;
                // Since we do not have navigational properties on Booking and properly 
                // implemented Compare methods on Room, have to do it the ugly way
                foreach (var r in RoomList)
                {
                    if (r.ID == _booking.RoomID)
                    {
                        _room = r;
                        break;
                    }
                }

                // pre-select booked assets
                foreach (var bookedAsset in _booking.AssetBookings)
                {
                    var asset = AssetList.First(a => a.Asset.ID == bookedAsset.AssetID);
                    if (asset != null)
                    {
                        asset.IsSelected = true;
                    }
                }

            }

            // Generate TimeComboBoxitems from 00:00 to 23:30, in 30 minute increments
            _allTimeOptions = new ObservableCollection<TimeComboBoxItem>();
            for (var i = 0; i < 48; i++)
            {
                var hours = i / 2;
                var minutes = (i % 2 == 0) ? 0 : 30;
                _allTimeOptions.Add(new TimeComboBoxItem() { Time = new TimeSpan(hours, minutes, 0) });
            }

            // Wire up commands
            MakeBookingCommand = new RelayCommand(this.MakeBooking, () => IsValid && !IsConflicting);
            CancelCommand = new RelayCommand(this.Cancel);
            SelectedAssetsChangedCommand = new RelayCommand<SelectionChangedEventArgs>(this.SelectedAssetsChanged);

            // Subscribe to own PropertyChanging event, to AJAX-ly call BLL validations
            this.PropertyChanged += new PropertyChangedEventHandler(BookingsFormViewModel_PropertyChanged);
        }
 public List<Booking> CheckRoomAvailability(Booking booking)
 {
     List<Booking> conflicts = bookingRepository.CheckRoomAvailability(booking.ID, booking.StartDate, booking.EndDate, booking.RoomID).ToList();
     return conflicts;
 }
 public List<Booking> CheckAssetAvailability(Booking booking)
 {
     int[] assetIDs = booking.AssetBookings.Select(x => x.AssetID).ToArray();
     List<Booking> conflicts = bookingRepository.CheckAssetAvailability(booking.ID, booking.StartDate, booking.EndDate, assetIDs).ToList();
     return conflicts;
 }
 public IEnumerable<string> getBookedItem(Booking booking)
 {
     IBookingComponent component = new BookingComponent();
     var clashes = component.getBookedItem(booking);
     return clashes;
 }
 protected void btncancel_Click(object sender, EventArgs e)
 {
     IBookingComponent bookingservice = new BookingComponent();
     Booking booking = new Booking();
     try
     {
         booking.ID = int.Parse(lblID.Text);
         bookingservice.CancelBooking(booking);
         lblstatus.Text = "Your Booking has been successfully canceled.";
     }
     catch (Exception)
     {
         
         throw;
     }
 }