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 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;
        }