public TaskReturnValue GetMemberTaskDetails(Guid logonId, Int32 taskId)
        {
            TaskReturnValue returnValue = new TaskReturnValue();

            try
            {
                // Get the logged on user from the current logons and add their
                // ApplicationSettings the list of concurrent sessions.
                Host.LoadLoggedOnUser(logonId);
                try
                {
                    Functions.RestrictRekoopIntegrationUser(UserInformation.Instance.DbUid);
                    switch (UserInformation.Instance.UserType)
                    {
                        case DataConstants.UserType.Staff:
                            // Can do everything
                            break;
                        case DataConstants.UserType.Client:
                        case DataConstants.UserType.ThirdParty:
                            throw new Exception("Access denied");
                        default:
                            throw new Exception("Access denied");
                    }

                    string attendeesNames = string.Empty;
                    string attendeesIds = string.Empty;

                    Task taskDetails = new Task();
                    SrvBookingEntry bookingEntryData = new SrvBookingEntry();
                    bookingEntryData.OccurrenceData.Id = taskId;

                    bookingEntryData.Load(bookingEntryData.OccurrenceData.Id);

                    this.GetBookingMembers(bookingEntryData.OccurrenceData.Id, ref attendeesNames, ref attendeesIds);

                    taskDetails.AttendeesName = attendeesNames;
                    taskDetails.Attendees = attendeesIds;

                    if (bookingEntryData.OccurrenceData.Id != 0)
                    {
                        taskDetails.Id = bookingEntryData.OccurrenceData.Id;

                        DsMattersForBooking.MatterForBookingDataTable dsMattersForBooking = bookingEntryData.DsBookingsMatters.MatterForBooking;
                        if (dsMattersForBooking.Rows.Count > 0)
                        {
                            taskDetails.ProjectId = new Guid(dsMattersForBooking[0].ProjectId.ToString());
                        }
                        else
                        {
                            taskDetails.ProjectId = DataConstants.DummyGuid;
                        }

                        //taskDetails.StartTime = bookingEntryData.OccurrenceData.StartTime;
                        //taskDetails.EndTime = bookingEntryData.OccurrenceData.EndTime;
                        taskDetails.TypeId = bookingEntryData.OccurrenceData.BookingTypeId;
                        taskDetails.DueDate = bookingEntryData.OccurrenceData.DueDate;
                        taskDetails.Subject = bookingEntryData.OccurrenceData.Text;
                        taskDetails.Notes = bookingEntryData.OccurrenceData.OccurrenceNotes;

                        if (bookingEntryData.OccurrenceData.Progress == 100)
                        {
                            taskDetails.IsCompleted = true;
                        }
                        else
                        {
                            taskDetails.IsCompleted = false;
                        }
                        taskDetails.IsPublic = bookingEntryData.OccurrenceData.IsOccurrencePublic;

                        taskDetails.IsPrivate = bookingEntryData.OccurrenceData.IsPrivateBooking;

                        if (bookingEntryData.OccurrenceData.ReminderDate != Convert.ToDateTime("01/01/1753"))
                        {
                            taskDetails.IsReminderSet = true;
                            taskDetails.ReminderDate = bookingEntryData.OccurrenceData.ReminderDate;
                            taskDetails.ReminderTime = bookingEntryData.OccurrenceData.ReminderTime;
                            taskDetails.ReminderBeforeTime = bookingEntryData.OccurrenceData.ReminderMinutesBefore.ToString();
                        }
                        else
                        {
                            taskDetails.IsReminderSet = false;
                            taskDetails.ReminderTime = string.Empty;
                            taskDetails.ReminderBeforeTime = "0";
                        }
                        taskDetails.ReminderType = "On";

                    }
                    returnValue.Task = taskDetails;
                }
                finally
                {
                    // Remove the logged on user's ApplicationSettings from the
                    // list of concurrent sessions
                    Host.UnloadLoggedOnUser();
                }
            }
            catch (System.Data.SqlClient.SqlException)
            {
                returnValue.Success = false;
                returnValue.Message = Functions.SQLErrorMessage;
            }
            catch (Exception Ex)
            {
                returnValue.Success = false;
                returnValue.Message = Ex.Message;
            }
            return returnValue;
        }
 /// <summary>
 /// Sets the Booking Members Data.
 /// </summary>
 /// <param name="diaryViewMembers">The diary view members.</param>
 private void SetBookingMembersData(DiaryViewMembersDts diaryViewMembers, ref SrvBookingEntry bookingEntryData)
 {
     SrvBookingMemberData bookingMemberData = null;
     bookingEntryData.BookingMemberData.Clear();
     for (int i = 0; i < diaryViewMembers.DiaryViewMembers.Rows.Count; i++)
     {
         bookingMemberData = new SrvBookingMemberData();
         bookingMemberData.MemberId = diaryViewMembers.DiaryViewMembers[i].MemberID;
         bookingMemberData.MemberCode = diaryViewMembers.DiaryViewMembers[i].MemberCode;
         bookingMemberData.MemberDiaryDisplay = diaryViewMembers.DiaryViewMembers[i].MemberDiaryDisplay;
         bookingMemberData.MemberDiaryPosition = diaryViewMembers.DiaryViewMembers[i].MemberDiaryPosition;
         bookingMemberData.MemberDisplayName = diaryViewMembers.DiaryViewMembers[i].MemberDisplayName;
         bookingMemberData.MemberType = diaryViewMembers.DiaryViewMembers[i].MemberType;
         bookingMemberData.MemberTypeId = diaryViewMembers.DiaryViewMembers[i].MemberTypeID;
         bookingMemberData.MemberTypePerson = diaryViewMembers.DiaryViewMembers[i].MemberTypePerson;
         bookingEntryData.BookingMemberData.Add(bookingMemberData);
     }
     bookingEntryData.IsbookingMembersChanged = true;
 }
        public AppointmentReturnValue GetAppointmentDetails(Guid logonId, Int32 appointmentId)
        {
            AppointmentReturnValue returnValue = new AppointmentReturnValue();

            try
            {
                // Get the logged on user from the current logons and add their
                // ApplicationSettings the list of concurrent sessions.
                Host.LoadLoggedOnUser(logonId);
                try
                {
                    Functions.RestrictRekoopIntegrationUser(UserInformation.Instance.DbUid);
                    switch (UserInformation.Instance.UserType)
                    {
                        case DataConstants.UserType.Staff:
                            // Can do everything
                            break;
                        case DataConstants.UserType.Client:
                        case DataConstants.UserType.ThirdParty:
                            throw new Exception("Access denied");
                        default:
                            throw new Exception("Access denied");
                    }

                    string attendeesNames = string.Empty;
                    string attendeesIds = string.Empty;

                    Appointment appointmentDetails = new Appointment();
                    SrvBookingEntry bookingEntryData = new SrvBookingEntry();
                    bookingEntryData.OccurrenceData.Id = appointmentId;

                    bookingEntryData.Load(bookingEntryData.OccurrenceData.Id);

                    this.GetBookingMembers(bookingEntryData.OccurrenceData.Id, ref attendeesNames, ref attendeesIds);

                    appointmentDetails.AttendeesName = attendeesNames;
                    appointmentDetails.Attendees = attendeesIds;

                    if (bookingEntryData.OccurrenceData.Id != 0)
                    {
                        appointmentDetails.Id = bookingEntryData.OccurrenceData.Id;

                        appointmentDetails.VenueId = bookingEntryData.OccurrenceData.VenueId;

                        DsServiceSearch dsServiceSearch = SrvServiceLookup.ServiceSearch(bookingEntryData.OccurrenceData.VenueId);
                        if (dsServiceSearch.uvw_ServicesSearch.Count > 0)
                        {
                            appointmentDetails.VenueText = dsServiceSearch.uvw_ServicesSearch[0].OrgName + " - " + dsServiceSearch.uvw_ServicesSearch[0].IndustryName;
                        }
                        else
                        {
                            appointmentDetails.VenueText = "Not Set";
                        }

                        DsMattersForBooking.MatterForBookingDataTable dsMattersForBooking = bookingEntryData.DsBookingsMatters.MatterForBooking;
                        if (dsMattersForBooking.Rows.Count > 0)
                        {
                            appointmentDetails.ProjectId = new Guid(dsMattersForBooking[0].ProjectId.ToString());
                        }
                        else
                        {
                            appointmentDetails.ProjectId = DataConstants.DummyGuid;
                        }

                        appointmentDetails.StartTime = bookingEntryData.OccurrenceData.StartTime;
                        appointmentDetails.EndTime = bookingEntryData.OccurrenceData.EndTime;
                        appointmentDetails.StartDate = bookingEntryData.OccurrenceData.StartDate;
                        appointmentDetails.Subject = bookingEntryData.OccurrenceData.Text;
                        appointmentDetails.Notes = bookingEntryData.OccurrenceData.OccurrenceNotes;

                        if (bookingEntryData.OccurrenceData.ReminderDate != Convert.ToDateTime("01/01/1753"))
                        {
                            appointmentDetails.IsReminderSet = true;
                            if (bookingEntryData.OccurrenceData.ReminderMinutesBefore == 0)
                            {
                                appointmentDetails.ReminderType = "On";
                            }
                            else
                            {
                                appointmentDetails.ReminderType = "Before";
                            }

                            appointmentDetails.ReminderBeforeTime = bookingEntryData.OccurrenceData.ReminderMinutesBefore.ToString();
                            appointmentDetails.ReminderDate = bookingEntryData.OccurrenceData.ReminderDate;
                            appointmentDetails.ReminderTime = bookingEntryData.OccurrenceData.ReminderTime;
                        }
                        else
                        {
                            appointmentDetails.IsReminderSet = false;
                            appointmentDetails.ReminderType = "On";
                            appointmentDetails.ReminderBeforeTime = "15 minutes";
                            appointmentDetails.ReminderTime = "";
                        }
                    }
                    returnValue.Appointment = appointmentDetails;
                }
                finally
                {
                    // Remove the logged on user's ApplicationSettings from the
                    // list of concurrent sessions
                    Host.UnloadLoggedOnUser();
                }
            }
            catch (System.Data.SqlClient.SqlException)
            {
                returnValue.Success = false;
                returnValue.Message = Functions.SQLErrorMessage;
            }
            catch (Exception Ex)
            {
                returnValue.Success = false;
                returnValue.Message = Ex.Message;
            }
            return returnValue;
        }
 /// <summary>
 /// Load the Booking Status by Id
 /// </summary>
 /// <param name="bookingEntryData"></param>
 /// <param name="statusId"></param>
 private void LoadBookingStatusById(ref SrvBookingEntry bookingEntryData, int statusId)
 {
     for (int i = 0; i < bookingEntryData.DiaryParamsDataSet.OccurrenceStatus.Count; i++)
     {
         if (bookingEntryData.DiaryParamsDataSet.OccurrenceStatus[i].OccStatusID == statusId)
         {
             bookingEntryData.OccurrenceData.Status = bookingEntryData.DiaryParamsDataSet.OccurrenceStatus[i].OccStatusID;
         }
     }
 }
 private void LoadBookingTypes(ref SrvBookingEntry bookingEntryData)
 {
     for (int i = 0; i < bookingEntryData.DiaryParamsDataSet.BookingTypes.Count; i++)
     {
         if (bookingEntryData.DiaryParamsDataSet.BookingTypes[i].BTDescription == "Appointment")
         {
             bookingEntryData.OccurrenceData.BookingTypeId = bookingEntryData.DiaryParamsDataSet.BookingTypes[i].BookingTypeID;
         }
     }
 }
 private void LoadBookingPriority(ref SrvBookingEntry bookingEntryData)
 {
     for (int i = 0; i < bookingEntryData.DiaryParamsDataSet.OccurrencePriorities.Count; i++)
     {
         if (bookingEntryData.DiaryParamsDataSet.OccurrencePriorities[i].OPDefault)
         {
             bookingEntryData.OccurrenceData.Priority = bookingEntryData.DiaryParamsDataSet.OccurrencePriorities[i].OPCode;
         }
     }
 }
        private void AddMatter(Guid projectId, ref SrvBookingEntry bookingEntryData)
        {
            try
            {
                var enquiryRepo = PmsInfrastructure.Container.Instance.Resolve<IEnquiryRepository>();
                var isActiveEnquiry = enquiryRepo.IsActiveEnquiry(projectId);

                DsMattersForBooking dsBookingMatter1 = SrvMatterLookup.GetMatterForBooking(projectId);
                DsMattersForBooking dsBookingsMatters = new DsMattersForBooking();

                if (dsBookingMatter1.MatterForBooking.Rows.Count == 0 && !isActiveEnquiry)
                    throw new ApplicationException("The matter could not be found");

                if (isActiveEnquiry)
                {
                    dsBookingsMatters.MatterForBooking.AddMatterForBookingRow(projectId.ToString(),
                    string.Empty,
                    string.Empty,
                    string.Empty,
                    DateTime.Now,
                    string.Empty,
                    enquiryRepo.GetPrimaryClientForEnquiry(projectId).ToString(),
                    string.Empty,
                    DataConstants.BlankDate,
                    string.Empty,
                    string.Empty,
                    string.Empty);
                }
                else
                {
                    dsBookingsMatters.MatterForBooking.AddMatterForBookingRow(dsBookingMatter1.MatterForBooking[0].ProjectId,
                    dsBookingMatter1.MatterForBooking[0].matRef,
                    dsBookingMatter1.MatterForBooking[0].matDescription,
                    dsBookingMatter1.MatterForBooking[0].matKeyDescription,
                    dsBookingMatter1.MatterForBooking[0].matOpenDate,
                    dsBookingMatter1.MatterForBooking[0].feeRef,
                    dsBookingMatter1.MatterForBooking[0].matPartnerMemId,
                    dsBookingMatter1.MatterForBooking[0].matUFN,
                    dsBookingMatter1.MatterForBooking[0].matClosedDate,
                    dsBookingMatter1.MatterForBooking[0].matBranchRef,
                    dsBookingMatter1.MatterForBooking[0].WorkTypeCode,
                    dsBookingMatter1.MatterForBooking[0].matDeptRef);
                }

                Collection<SrvBookingMatter> bookingMatterTableIndividual = new Collection<SrvBookingMatter>();
                AddMatterData(ref bookingMatterTableIndividual, dsBookingsMatters);
                bookingEntryData.BookingMatterTable = bookingMatterTableIndividual;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public TaskReturnValue SaveTask(Guid logonId, Task taskDetails)
        {
            TaskReturnValue returnValue = new TaskReturnValue();

            try
            {
                // Get the logged on user from the current logons acnd add their
                // ApplicationSettings the list of concurrent sessions.
                Host.LoadLoggedOnUser(logonId);

                try
                {
                    Functions.RestrictRekoopIntegrationUser(UserInformation.Instance.DbUid);
                    if (taskDetails.ProjectId == Guid.Empty || taskDetails.ProjectId == DataConstants.DummyGuid)
                    {
                        // Non matter task
                        switch (UserInformation.Instance.UserType)
                        {
                            case DataConstants.UserType.Staff:
                                // Can add/edit subject to permissions
                                break;
                            case DataConstants.UserType.Client:
                            case DataConstants.UserType.ThirdParty:
                                if (!UserSecuritySettings.GetUserSecuitySettings(273))
                                {
                                    throw new Exception("Access denied");
                                }
                                break;

                            default:
                                throw new Exception("Access denied");
                        }
                    }
                    else
                        // Matter task
                        switch (UserInformation.Instance.UserType)
                        {
                            case DataConstants.UserType.Staff:
                                // Can add/edit subject to permissions
                                break;
                            case DataConstants.UserType.Client:
                            case DataConstants.UserType.ThirdParty:
                                if (!SrvMatterCommon.WebAllowedToAccessMatter(taskDetails.ProjectId)
                                    || !UserSecuritySettings.GetUserSecuitySettings(273))
                                {
                                    throw new Exception("Access denied");
                                }
                                break;
                            default:
                                throw new Exception("Access denied");
                        }

                    SrvBookingEntry bookingEntryData = new SrvBookingEntry();
                    bookingEntryData.OccurrenceData.Id = taskDetails.Id;

                    var brClients = new BrClients();
                    if (!string.IsNullOrEmpty(taskDetails.ClientId) && !taskDetails.IsContactTask)
                    {
                        var client = brClients.GetClientFromID(new Guid(taskDetails.ClientId));
                        ClientMatterBooking.AddClientMatterToBooking(bookingEntryData, client.Clients[0].memId, client.Clients[0].orgId, DataConstants.DummyGuid);
                    }

                    bookingEntryData.Load(bookingEntryData.OccurrenceData.Id);

                    if (bookingEntryData.OccurrenceData.Id != 0)
                    {
                        // Editing a task
                        bookingEntryData.ActionEditMode = ActionEditMode.Amend;

                        //check that task is public and throw an access denied error if not
                        switch (UserInformation.Instance.UserType)
                        {
                            case DataConstants.UserType.Staff:
                                // Can add/edit subject to permissions
                                break;
                            case DataConstants.UserType.Client:
                            case DataConstants.UserType.ThirdParty:
                                //Must check that task is public and throw an access denied error if not
                                if (!taskDetails.IsPublic)
                                    throw new Exception("Access denied");
                                break;
                            default:
                                throw new Exception("Unknown UserType");
                        }

                    }
                    else
                    {
                        // Adding a new task
                        bookingEntryData.OccurrenceData.BookingText = taskDetails.Subject;
                        bookingEntryData.OccurrenceData.BookingColour = (System.Drawing.Color.Black);

                        // If the starttime/Est time is null, it will not be listed in the search tasks.
                        // To fix this issue, added the below code
                        // Ref:2757
                        if (string.IsNullOrEmpty(bookingEntryData.OccurrenceData.StartTime))
                        {
                            bookingEntryData.OccurrenceData.StartTime = ":";
                        }
                        if (string.IsNullOrEmpty(bookingEntryData.OccurrenceData.EstimatedTime))
                        {
                            bookingEntryData.OccurrenceData.EstimatedTime = ":";
                        }
                    }

                    if (UserInformation.Instance.UserType == DataConstants.UserType.Staff)
                    {
                        // Ensure staff have permission
                        if (bookingEntryData.ActionEditMode == ActionEditMode.Create)
                        {
                            // Create new bookings
                            if (!UserSecuritySettings.GetUserSecuitySettings(100))
                                throw new Exception("You do not have sufficient permissions to carry out this request");
                        }
                        else
                        {
                            // Edit existing bookings
                            if (!UserSecuritySettings.GetUserSecuitySettings(102))
                                throw new Exception("You do not have sufficient permissions to carry out this request");
                        }
                    }

                    DiaryViewMembersDts diaryViewMembers = this.GetDiaryViewMembersDts(taskDetails.Attendees);
                    this.SetBookingMembersData(diaryViewMembers, ref bookingEntryData);

                    #region Add Matter to Task
                    // Adding Matter to the Appointment
                    Guid oldProjectId = DataConstants.DummyGuid;
                    if (bookingEntryData.OccurrenceData.Id != 0)
                    {
                        DsMattersForBooking.MatterForBookingDataTable dsMattersForBooking = bookingEntryData.DsBookingsMatters.MatterForBooking;
                        if (bookingEntryData.DsBookingsMatters.MatterForBooking.Rows.Count > 0)
                        {
                            if (taskDetails.ProjectId != null)
                            {
                                oldProjectId = new Guid(dsMattersForBooking[0].ProjectId.ToString());

                                // If New Matter is same as that of the Old Matter, then don't add any new matters
                                if (oldProjectId != taskDetails.ProjectId)
                                {
                                    // Check if old matter been replaced by new matter is already present in the list or not
                                    // If New Matter is been replaced, then remove Old Matter
                                    // If New Matter been added is already present in the list of existing matters, then throw error
                                    if (!(bookingEntryData.DsBookingsMatters.MatterForBooking.Select(string.Format("ProjectId = '{0}'", taskDetails.ProjectId.ToString())).Length > 0))
                                    {
                                        // Remove Old Matter
                                        if (bookingEntryData.DsBookingsMatters.MatterForBooking.FindByProjectId(oldProjectId.ToString()) != null)
                                        {
                                            bookingEntryData.DsBookingsMatters.MatterForBooking.RemoveMatterForBookingRow(bookingEntryData.DsBookingsMatters.MatterForBooking.FindByProjectId(oldProjectId.ToString()));
                                            Collection<SrvBookingMatter> bookingMatterTableIndividual = bookingEntryData.BookingMatterTable;
                                            this.AddMatterData(ref bookingMatterTableIndividual, bookingEntryData.DsBookingsMatters);
                                        }
                                    }
                                    else if (bookingEntryData.DsBookingsMatters.MatterForBooking.Select(string.Format("ProjectId = '{0}'", taskDetails.ProjectId.ToString())).Length > 1)
                                    {
                                        throw new Exception("This matter is already present for this appointment");
                                    }
                                }
                            }
                        }
                    }

                    // string.IsNullOrEmpty(taskDetails.ClientId) will return false if we are adding the task to a client
                    if (taskDetails.ProjectId != Guid.Empty && string.IsNullOrEmpty(taskDetails.ClientId))
                    {
                        if (taskDetails.ProjectId != DataConstants.DummyGuid)
                        {
                            this.AddMatter(taskDetails.ProjectId, ref bookingEntryData);
                        }
                    }

                    #endregion

                    this.LoadBookingPriority(ref bookingEntryData);

                    bookingEntryData.OccurrenceData.OccurrenceNotes = taskDetails.Notes;
                    bookingEntryData.OccurrenceData.Text = taskDetails.Subject;
                    bookingEntryData.OccurrenceData.DueDate = taskDetails.DueDate;
                    bookingEntryData.OccurrenceData.BookingTypeId = taskDetails.TypeId;
                    bookingEntryData.OccurrenceData.IsOccurrencePublic = taskDetails.IsPublic;
                    bookingEntryData.RecurrenceData.IsTaskEntry = true;
                    bookingEntryData.OccurrenceData.TaskStartDate = Convert.ToDateTime("01/01/1753");

                    if (taskDetails.IsCompleted)
                    {
                        bookingEntryData.OccurrenceData.EndDate = DateTime.Now;
                        // Set Status Default to "Completed"
                        this.LoadBookingStatus(ref bookingEntryData, "Completed");
                        bookingEntryData.OccurrenceData.Progress = 100;
                    }
                    else
                    {
                        bookingEntryData.OccurrenceData.EndDate = DataConstants.BlankDate;
                        // Set Status Default to "Not Set"
                        this.LoadBookingStatus(ref bookingEntryData, "Not Set");
                        bookingEntryData.OccurrenceData.Progress = 0;
                    }

                    // If the status id is sent then set the status based on the id.
                    if (taskDetails.StatusId > 0)
                    {
                        this.LoadBookingStatusById(ref bookingEntryData, taskDetails.StatusId);
                    }

                    bookingEntryData.BookingDates = Convert.ToString(taskDetails.DueDate);

                    bookingEntryData.OccurrenceData.IsPrivateBooking = taskDetails.IsPrivate;

                    if (taskDetails.IsReminderSet)
                    {
                        bookingEntryData.OccurrenceData.ReminderDate = taskDetails.ReminderDate;
                        bookingEntryData.OccurrenceData.ReminderTime = taskDetails.ReminderTime;
                    }
                    else
                    {
                        bookingEntryData.OccurrenceData.ReminderDate = Convert.ToDateTime("01/01/1753");
                        bookingEntryData.OccurrenceData.ReminderTime = "09:00";
                    }

                    bookingEntryData.OccurrenceData.ReminderMinutesBefore = 0;
                    bookingEntryData.OccurrenceData.ReminderFutureAction = 0;
                    bookingEntryData.ReminderRepeatForOccurrences = false;

                    string errorMessage = string.Empty;
                    bool returnValueRows = false;

                    returnValueRows = bookingEntryData.Save(out errorMessage);
                    if (returnValueRows == false)
                    {
                        if (errorMessage != string.Empty)
                        {
                            returnValue.Success = false;
                            returnValue.Message = errorMessage;
                        }
                    }
                    else
                    {
                        taskDetails.Id = bookingEntryData.OccurrenceData.Id;
                        returnValue.Task = taskDetails;
                    }

                }
                finally
                {
                    // Remove the logged on user's ApplicationSettings from the
                    // list of concurrent sessions
                    Host.UnloadLoggedOnUser();
                }
            }
            catch (System.Data.SqlClient.SqlException)
            {
                returnValue.Success = false;
                returnValue.Message = Functions.SQLErrorMessage;
            }
            catch (Exception Ex)
            {
                returnValue.Success = false;
                returnValue.Message = Ex.Message;
            }
            return returnValue;
        }
        public ReturnValue DeleteBooking(Guid logonId, DeleteData deleteData)
        {
            ReturnValue returnValue = new ReturnValue();

            try
            {
                // Get the logged on user from the current logons and add their
                // ApplicationSettings the list of concurrent sessions.
                Host.LoadLoggedOnUser(logonId);

                try
                {
                    Functions.RestrictRekoopIntegrationUser(UserInformation.Instance.DbUid);
                    switch (UserInformation.Instance.UserType)
                    {
                        case DataConstants.UserType.Staff:
                            // Ensure we have permission
                            if (!UserSecuritySettings.GetUserSecuitySettings(103))
                                throw new Exception("You do not have sufficient permissions to carry out this request");
                            break;
                        case DataConstants.UserType.Client:
                        case DataConstants.UserType.ThirdParty:
                            throw new Exception("Access denied");
                        default:
                            throw new Exception("Access denied");
                    }

                    BookingDeleteData bookingDeleteData = new BookingDeleteData();
                    bookingDeleteData.OccurrenceID = deleteData.OccurenceId;
                    bookingDeleteData.MemberID = Convert.ToString(UserInformation.Instance.UserMemberId);
                    bookingDeleteData.IsBookingATask = deleteData.IsBookingATask;
                    bookingDeleteData.BlockBookingDeleteDataSet = new BookingDeleteDts();
                    bookingDeleteData.GroupBookingDeleteDataSet = new BookingDeleteDts();

                    try
                    {
                        string occurrenceMember;
                        DiaryMemberSearchItem diaryMembers = this.GetDiaryMemberDetails(deleteData.MemberId);

                        if (diaryMembers.IsGroup)
                        {
                            DiaryBookingsDts dsOccurrence = SrvOccurrenceLookup.GetOccurrenceById(deleteData.OccurenceId);
                            if (dsOccurrence.Occurrence.Rows.Count == 1)
                            {
                                occurrenceMember = dsOccurrence.Occurrence[0].MemberID.ToString();
                            }
                            else
                            {
                                occurrenceMember = Guid.Empty.ToString();
                            }
                        }
                        else
                        {
                            occurrenceMember = deleteData.MemberId;
                        }

                        // Firstly get the block bookings
                        bookingDeleteData.BlockBookingDeleteDataSet = SrvBookingEntryLookup.GetDiaryBookingsForDelete(occurrenceMember, deleteData.OccurenceId, 1);

                        if (bookingDeleteData.BlockBookingDeleteDataSet != null)
                        {
                            // Now get group booking
                            bookingDeleteData.GroupBookingDeleteDataSet = SrvBookingEntryLookup.GetDiaryBookingsForDelete(occurrenceMember, deleteData.OccurenceId, 2);
                        }

                        if (bookingDeleteData.GroupBookingDeleteDataSet != null)
                        {
                            BookingDeleteDts tempDts = SrvBookingEntryLookup.GetBookingMembersForDelete(deleteData.OccurenceId);
                            foreach (BookingDeleteDts.BookingMembersDeleteRow dr in tempDts.BookingMembersDelete.Rows)
                            {
                                bookingDeleteData.GroupBookingDeleteDataSet.BookingMembersDelete.AddBookingMembersDeleteRow(dr.MemberID, dr.MemberDisplayName);
                            }
                        }

                        bookingDeleteData.IsBlockBooking = (bookingDeleteData.BlockBookingDeleteDataSet.BookingDelete.Rows.Count > 1);
                        bookingDeleteData.IsGroupBooking = (bookingDeleteData.GroupBookingDeleteDataSet.BookingMembersDelete.Rows.Count > 1);

                        if (bookingDeleteData.IsBlockBooking)
                        {
                            for (int i = 0; i < bookingDeleteData.GroupBookingDeleteDataSet.BookingDelete.Rows.Count; i++)
                            {
                                bookingDeleteData.GroupBookingDeleteDataSet.BookingDelete.Rows[i]["DeleteFlag"] = 1;
                            }
                        }
                        else if (bookingDeleteData.IsGroupBooking)
                        {
                            for (int i = 0; i < bookingDeleteData.GroupBookingDeleteDataSet.BookingDelete.Rows.Count; i++)
                            {
                                bookingDeleteData.GroupBookingDeleteDataSet.BookingDelete.Rows[i]["DeleteFlag"] = 1;
                            }
                        }

                        // Delete Occurrences
                        SrvBookingEntry srvBooking = new SrvBookingEntry();
                        string occurrenceIDs = string.Empty;
                        foreach (DataRow dr in bookingDeleteData.GroupBookingDeleteDataSet.BookingDelete.Rows)
                        {
                            if ((bool)dr["DeleteFlag"])
                            {
                                occurrenceIDs += (dr["OccurrenceID"].ToString() + ",");
                            }
                        }

                        if (!string.IsNullOrEmpty(occurrenceIDs))
                        {
                            occurrenceIDs = occurrenceIDs.Substring(0, occurrenceIDs.Length - 1);
                            string[] strOccurerenceIds = occurrenceIDs.Split(',');
                            int[] occurerenceIds = new int[strOccurerenceIds.Length];

                            for (int i = 0; i < strOccurerenceIds.Length; i++)
                            {
                                occurerenceIds[i] = Convert.ToInt32(strOccurerenceIds[i]);
                            }

                            if (!srvBooking.Delete(occurerenceIds, deleteData.CategoryCode, deleteData.ReasonCode, deleteData.CancellationText))
                            {
                                throw new Exception("Some of the supplied occurrences are already cancelled!");
                            }
                        }
                        else
                        {
                            throw new Exception("Please provide valid Occurrence Ids.");
                        }

                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message);
                    }
                }
                finally
                {
                    // Remove the logged on user's ApplicationSettings from the
                    // list of concurrent sessions
                    Host.UnloadLoggedOnUser();
                }
            }
            catch (System.Data.SqlClient.SqlException)
            {
                returnValue.Success = false;
                returnValue.Message = Functions.SQLErrorMessage;
            }
            catch (Exception Ex)
            {
                returnValue.Success = false;
                returnValue.Message = Ex.Message;
            }

            return returnValue;
        }
        public AppointmentReturnValue SaveAppointment(Guid logonId, Appointment appointmentDetails)
        {
            AppointmentReturnValue returnValue = new AppointmentReturnValue();

            try
            {
                // Get the logged on user from the current logons and add their
                // ApplicationSettings the list of concurrent sessions.
                Host.LoadLoggedOnUser(logonId);
                try
                {
                    Functions.RestrictRekoopIntegrationUser(UserInformation.Instance.DbUid);
                    switch (UserInformation.Instance.UserType)
                    {
                        case DataConstants.UserType.Staff:
                            // Can add/edit subject to permissions
                            break;
                        case DataConstants.UserType.Client:
                        case DataConstants.UserType.ThirdParty:
                            throw new Exception("Access denied");
                        default:
                            throw new Exception("Access denied");
                    }

                    SrvBookingEntry bookingEntryData = new SrvBookingEntry();
                    bookingEntryData.OccurrenceData.Id = appointmentDetails.Id;

                    bookingEntryData.Load(bookingEntryData.OccurrenceData.Id);

                    if (bookingEntryData.OccurrenceData.Id != 0)
                    {
                        bookingEntryData.ActionEditMode = ActionEditMode.Amend;
                    }

                    // Ensure we have permission
                    if (bookingEntryData.ActionEditMode == ActionEditMode.Create)
                    {
                        // Create new bookings
                        if (!UserSecuritySettings.GetUserSecuitySettings(100))
                            throw new Exception("You do not have sufficient permissions to carry out this request");
                    }
                    else
                    {
                        // Edit existing bookings
                        if (!UserSecuritySettings.GetUserSecuitySettings(102))
                            throw new Exception("You do not have sufficient permissions to carry out this request");
                    }

                    DiaryViewMembersDts diaryViewMembers = this.GetDiaryViewMembersDts(appointmentDetails.Attendees);
                    this.SetBookingMembersData(diaryViewMembers, ref bookingEntryData);

                    if (bookingEntryData.ActionEditMode == ActionEditMode.Create)
                    {
                        // Add the first attendee as the organiser
                        bookingEntryData.OrganiserId = new Guid(diaryViewMembers.DiaryViewMembers[0].MemberID);
                    }

                    #region Add Matter to Appointment
                    // Adding Matter to the Appointment
                    Guid oldProjectId = DataConstants.DummyGuid;
                    if (bookingEntryData.OccurrenceData.Id != 0)
                    {
                        DsMattersForBooking.MatterForBookingDataTable dsMattersForBooking = bookingEntryData.DsBookingsMatters.MatterForBooking;
                        if (bookingEntryData.DsBookingsMatters.MatterForBooking.Rows.Count > 0)
                        {
                            if (appointmentDetails.ProjectId != null)
                            {
                                oldProjectId = new Guid(dsMattersForBooking[0].ProjectId.ToString());

                                // If New Matter is same as that of the Old Matter, then don't add any new matters
                                if (oldProjectId != appointmentDetails.ProjectId)
                                {
                                    // Check if old matter been replaced by new matter is already present in the list or not
                                    // If New Matter is been replaced, then remove Old Matter
                                    // If New Matter been added is already present in the list of existing matters, then throw error
                                    if (!(bookingEntryData.DsBookingsMatters.MatterForBooking.Select(string.Format("ProjectId = '{0}'", appointmentDetails.ProjectId.ToString())).Length > 0))
                                    {
                                        // Remove Old Matter
                                        if (bookingEntryData.DsBookingsMatters.MatterForBooking.FindByProjectId(oldProjectId.ToString()) != null)
                                        {
                                            bookingEntryData.DsBookingsMatters.MatterForBooking.RemoveMatterForBookingRow(bookingEntryData.DsBookingsMatters.MatterForBooking.FindByProjectId(oldProjectId.ToString()));
                                            Collection<SrvBookingMatter> bookingMatterTableIndividual = bookingEntryData.BookingMatterTable;
                                            this.AddMatterData(ref bookingMatterTableIndividual, bookingEntryData.DsBookingsMatters);
                                        }
                                    }
                                    else if (bookingEntryData.DsBookingsMatters.MatterForBooking.Select(string.Format("ProjectId = '{0}'", appointmentDetails.ProjectId.ToString())).Length > 1)
                                    {
                                        throw new Exception("This matter is already present for this appointment");
                                    }
                                }
                            }
                        }
                    }
                    if (appointmentDetails.ProjectId != null)
                    {
                        if (appointmentDetails.ProjectId != DataConstants.DummyGuid)
                        {
                            this.AddMatter(appointmentDetails.ProjectId, ref bookingEntryData);
                        }
                    }
                    #endregion

                    if (appointmentDetails.Id == 0)
                    {
                        bookingEntryData.OccurrenceData.BookingText = appointmentDetails.Subject;
                        bookingEntryData.OccurrenceData.BookingColour = (System.Drawing.Color.Black);
                    }
                    else
                    {
                        bookingEntryData.OccurrenceData.StartDate = appointmentDetails.StartDate;
                    }

                    #region Date & Time Calculations
                    TimeSpan tsStartTime;
                    TimeSpan tsEndTime;
                    try
                    {
                        tsStartTime = TimeSpan.Parse(appointmentDetails.StartTime);
                        tsEndTime = TimeSpan.Parse(appointmentDetails.EndTime);
                        DateTime dtStartDate = appointmentDetails.StartDate;
                        //If the end time is smaller than the start time
                        //then the appointment must have spanned midnight
                        //and therefore the enddate should be amended to
                        //include the extra day.
                        if (tsEndTime < tsStartTime)
                        {
                            bookingEntryData.OccurrenceData.EndDate = dtStartDate.AddDays(1);
                        }
                        else
                        {
                            bookingEntryData.OccurrenceData.EndDate = dtStartDate;
                        }
                    }
                    catch
                    {
                        bookingEntryData.OccurrenceData.EndDate = DateTime.Now;
                    }
                    bookingEntryData.OccurrenceData.DueDate = DateTime.Now;
                    bookingEntryData.OccurrenceData.StartTime = appointmentDetails.StartTime;
                    bookingEntryData.OccurrenceData.EndTime = appointmentDetails.EndTime;

                    if (string.IsNullOrEmpty(appointmentDetails.StartTime))
                    {
                        appointmentDetails.StartTime = ":";
                    }
                    if (string.IsNullOrEmpty(appointmentDetails.EndTime))
                    {
                        appointmentDetails.EndTime = ":";
                    }

                    appointmentDetails.StartTime = SrvBookingEntryCommon.EnsureTimeFormat(appointmentDetails.StartTime);
                    appointmentDetails.EndTime = SrvBookingEntryCommon.EnsureTimeFormat(appointmentDetails.EndTime);
                    if (!SrvBookingEntryCommon.IsValidTime(Convert.ToString(appointmentDetails.StartDate), appointmentDetails.StartTime, true))
                    {
                        throw new Exception("Invalid Start Time");
                    }
                    if (!SrvBookingEntryCommon.IsValidTime(Convert.ToString(appointmentDetails.StartDate), appointmentDetails.EndTime, true))
                    {
                        throw new Exception("Invalid End Time");
                    }

                    bookingEntryData.OccurrenceData.EstimatedTime = SrvBookingEntryCommon.CalculateDuration(appointmentDetails.StartTime, "", appointmentDetails.EndTime);

                    #endregion

                    this.LoadBookingPriority(ref bookingEntryData);

                    bookingEntryData.OccurrenceData.IsOccurrenceProvisional = false;
                    bookingEntryData.OccurrenceData.IsOccurrenceIgnoredBook = false;
                    bookingEntryData.OccurrenceData.OccurrenceNotes = appointmentDetails.Notes;
                    bookingEntryData.OccurrenceData.Text = appointmentDetails.Subject;
                    bookingEntryData.OccurrenceData.IsPrivateBooking = false;

                    // Set Status Default to "Not Set"
                    this.LoadBookingStatus(ref bookingEntryData, "Not Set");

                    // Set Type Default to "Appointment"
                    this.LoadBookingTypes(ref bookingEntryData);

                    bookingEntryData.BookingDates = Convert.ToString(appointmentDetails.StartDate);
                    bookingEntryData.RecurrenceData.IsSaturdayInclude = false;
                    bookingEntryData.RecurrenceData.IsSundayInclude = false;

                    #region Set Reminder details
                    if (appointmentDetails.IsReminderSet)
                    {
                        if (appointmentDetails.ReminderType == "Before")
                        {
                            bookingEntryData.OccurrenceData.ReminderDate = appointmentDetails.ReminderDate;
                            bookingEntryData.OccurrenceData.ReminderTime = appointmentDetails.ReminderTime;
                            bookingEntryData.OccurrenceData.ReminderMinutesBefore = Convert.ToInt16(appointmentDetails.ReminderBeforeTime);
                        }
                        else
                        {
                            bookingEntryData.OccurrenceData.ReminderDate = appointmentDetails.ReminderDate;
                            bookingEntryData.OccurrenceData.ReminderTime = appointmentDetails.ReminderTime;
                            bookingEntryData.OccurrenceData.ReminderMinutesBefore = 0;
                        }
                    }
                    else
                    {
                        bookingEntryData.OccurrenceData.ReminderDate = Convert.ToDateTime("01/01/1753");
                        bookingEntryData.OccurrenceData.ReminderTime = "09:00";
                        bookingEntryData.OccurrenceData.ReminderMinutesBefore = 0;
                    }

                    bookingEntryData.OccurrenceData.ReminderFutureAction = 0;
                    #endregion

                    bookingEntryData.OccurrenceData.TaskStartDate = Convert.ToDateTime("01/01/1753");
                    bookingEntryData.ReminderRepeatForOccurrences = false;
                    bookingEntryData.OccurrenceData.VenueId = appointmentDetails.VenueId;

                    string errorMessage = string.Empty;
                    bool returnValueRows = false;

                    returnValueRows = bookingEntryData.Save(out errorMessage);
                    if (returnValueRows == false)
                    {
                        if (errorMessage != string.Empty)
                        {
                            returnValue.Success = false;
                            returnValue.Message = errorMessage;
                        }
                    }
                    else
                    {
                        appointmentDetails.Id = bookingEntryData.OccurrenceData.Id;
                        returnValue.Appointment = appointmentDetails;
                    }

                }
                finally
                {
                    // Remove the logged on user's ApplicationSettings from the
                    // list of concurrent sessions
                    Host.UnloadLoggedOnUser();
                }
            }
            catch (System.Data.SqlClient.SqlException)
            {
                returnValue.Success = false;
                returnValue.Message = Functions.SQLErrorMessage;
            }
            catch (Exception Ex)
            {
                returnValue.Success = false;
                returnValue.Message = Ex.Message;
            }
            return returnValue;
        }