Example #1
0
        private StringBuilder GetDataFileContent(
            DataListCreator dataListCreator
            )
        {
            List <List <double> > dataList = dataListCreator();

            StringBuilder dataFileContent = new StringBuilder();

            for (int i = 0; i < dataList[0].Count; i++)
            {
                WriteLine(dataList, dataFileContent, i);
            }

            return(dataFileContent);
        }
        /// <summary>
        /// Gets the address types.
        /// </summary>
        /// <param name="logonId">Logon id obtained when logging on to the logon service.</param>
        /// <param name="collectionRequest">Information about the collection being requested.</param>
        /// <param name="criteria">Address Type search criteria.</param>
        /// <returns></returns>
        public AddressTypeReturnValue GetAddressTypes(Guid logonId, CollectionRequest collectionRequest,
                AddressTypeSearchCriteria criteria)
        {
            AddressTypeReturnValue returnValue = new AddressTypeReturnValue();

            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:
                        case DataConstants.UserType.Client:
                        case DataConstants.UserType.ThirdParty:
                            // Can do everything
                            break;
                        default:
                            throw new Exception("Access denied");
                    }

                    // Create a data list creator for a list of address types
                    DataListCreator<AddressType> dataListCreator = new DataListCreator<AddressType>();

                    // Declare an inline event (annonymous delegate) to read the dataset
                    dataListCreator.ReadDataSet += delegate(object Sender, ReadDataSetEventArgs e)
                    {

                        if (criteria.MemberId != DataConstants.DummyGuid)
                        {
                            e.DataSet = SrvAddressLookup.GetAddressTypes(1, 2);
                        }
                        else if (criteria.OrganisationId != DataConstants.DummyGuid)
                        {
                            e.DataSet = SrvAddressLookup.GetAddressTypes(1, 3);
                        }

                        foreach (DataRow r in e.DataSet.Tables[0].Rows)
                        {
                            if (Boolean.Parse(r["AddressTypeArchived"].ToString()))
                            {
                                r.Delete();
                            }
                        }
                        e.DataSet.Tables[0].AcceptChanges();

                    };

                    // Create the data list
                    returnValue.AddressTypes = dataListCreator.Create(logonId,
                        // Give the query a name so it can be cached
                        "AddressTypes",
                        // Tell it the query criteria used so if the cache is accessed
                        // again it knows if it is the same query
                        criteria.ToString(),
                        collectionRequest,
                        // Import mappings to map the dataset row fields to the data
                        // list entity properties
                        new ImportMapping[] {
                            new ImportMapping("Description", "AddressTypeDescription"),
                            new ImportMapping("Id", "AddressTypeID"),
                            }
                        );
                }
                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>
        /// Get extended info for the Roles.
        /// </summary>
        /// <param name="logonId">Logon id obtained when logging on to the logon service.</param>
        /// <param name="criteria">RoleExtendedInfo search criteria</param>
        /// <param name="collectionRequest">Information about the collection being requested.</param>
        /// <returns></returns>
        public RoleExtendedInfoReturnValue RoleExtendedInfoSearch(Guid logonId, RoleExtendedInfoSearchCriteria criteria,
                                                CollectionRequest collectionRequest)
        {
            RoleExtendedInfoReturnValue returnValue = new RoleExtendedInfoReturnValue();

            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:
                        case DataConstants.UserType.Client:
                        case DataConstants.UserType.ThirdParty:
                            // Can do everything
                            break;
                        default:
                            throw new Exception("Access denied");
                    }

                    // Create a data list creator for a list of extended role info
                    DataListCreator<RoleExtendedInfoSearchItem> dataListCreator = new DataListCreator<RoleExtendedInfoSearchItem>();

                    // Declare an inline event (annonymous delegate) to read the dataset
                    dataListCreator.ReadDataSet += delegate(object Sender, ReadDataSetEventArgs e)
                    {
                        e.DataSet = SrvRoleExtendedInfoLookup.GetExtendedInformationByRoleID(criteria.AssociationRoleId);
                    };

                    // Create the data list
                    returnValue.RoleExtendedInfo = dataListCreator.Create(logonId,
                        // Give the query a name so it can be cached
                        "RoleExtendedInfoSearch",
                        // Tell it the query criteria used so if the cache is accessed
                        // again it knows if it is the same query
                        criteria.ToString(),
                        collectionRequest,
                        // Import mappings to map the dataset row fields to the data
                        // list entity properties
                        new ImportMapping[] {
                            new ImportMapping("TypeId", "RolExtInfoTypeId"),
                            new ImportMapping("TypeName", "RolExtInfoTypeName"),
                            new ImportMapping("UserCanEdit", "RolExtInfoUserCanEdit"),
                            new ImportMapping("SourceText", "RolExtInfoSourceText"),
                            new ImportMapping("DataType", "RolExtInfoDataType")
                            }
                        );
                }
                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>
        /// Search for contacts.
        /// </summary>
        /// <param name="logonId">Logon id obtained when logging on to the logon service.</param>
        /// <param name="collectionRequest">Information about the collection being requested.</param>
        /// <param name="criteria">Contact search criteria.</param>
        /// <returns></returns>
        public ContactSearchReturnValue ContactSearch(Guid logonId, CollectionRequest collectionRequest, ContactSearchCriteria criteria)
        {
            ContactSearchReturnValue returnValue = new ContactSearchReturnValue();

            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");
                    }
                    // Create a data list creator for a list of contacts
                    DataListCreator<ContactSearchItem> dataListCreator = new DataListCreator<ContactSearchItem>();

                    // Declare an inline event (annonymous delegate) to read the dataset
                    dataListCreator.ReadDataSet += delegate(object Sender, ReadDataSetEventArgs e)
                    {
                        e.DataSet = SrvContactLookup.WebContactSearch(criteria.ContactName,
                                                                      criteria.Organisation,
                                                                      criteria.HouseNumber,
                                                                      criteria.POBox,
                                                                      criteria.PostCode,
                                                                      criteria.Town);
                        if (criteria.OrderBy != string.Empty)
                        {
                            DataTable dt = Functions.SortDataTable(e.DataSet.Tables[0], criteria.OrderBy);
                            e.DataSet.Tables.Remove("Table");
                            e.DataSet.Tables.Add(dt);
                        }
                    };

                    // Create the data list
                    returnValue.Contacts = dataListCreator.Create(logonId,
                        // Give the query a name so it can be cached
                        "ContactSearch",
                        // Tell it the query criteria used so if the cache is accessed
                        // again it knows if it is the same query
                        criteria.ToString(),
                        collectionRequest,
                        // Import mappings to map the dataset row fields to the data
                        // list entity properties
                        new ImportMapping[] {
                            new ImportMapping("OrganisationId", "orgId"),
                            new ImportMapping("MemberId", "memId"),
                            new ImportMapping("Name", "Name"),
                            new ImportMapping("Address", "Address"),
                            new ImportMapping("Town", "Town"),
                            new ImportMapping("PostCode", "PostCode")
                            }
                        );
                }
                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>
        /// This method get the work type for a specified department
        /// </summary>
        /// <param name="logonId">Login id</param>
        /// <param name="collectionRequest">Collection request</param>
        /// <param name="criteria">Search criteria for WorkType</param>
        /// <returns></returns>
        public WorkTypeSearchReturnValue GetWorkTypesForDepartment(Guid logonId, CollectionRequest collectionRequest,
           WorkTypeSearchCriteria criteria)
        {
            WorkTypeSearchReturnValue returnValue = new WorkTypeSearchReturnValue();

            try
            {
                Host.LoadLoggedOnUser(logonId);
                try
                {
                    Functions.RestrictRekoopIntegrationUser(UserInformation.Instance.DbUid);
                    switch (UserInformation.Instance.UserType)
                    {
                        case DataConstants.UserType.Staff:
                        case DataConstants.UserType.Client:
                        case DataConstants.UserType.ThirdParty:
                            // Can do everything
                            break;
                        default:
                            throw new Exception("Access denied");
                    }

                    // Create a data list creator for a list of matters
                    DataListCreator<WorkTypeSearchItem> dataListCreator = new DataListCreator<WorkTypeSearchItem>();

                    // Declare an inline event (annonymous delegate) to read the
                    // dataset if it is required
                    dataListCreator.ReadDataSet += delegate(object sender, ReadDataSetEventArgs e)
                    {
                        // Create the dataset
                        // TODO: Does not use the criteria: Id, FilterString, OrganisationID, DepartmentId, IsPrivateClient, MatterTypeId, ClientId
                        e.DataSet = SrvWorkTypeLookup.GetWorkTypesByDepartment(criteria.DepartmentNo);

                        DataTable dt = Functions.SortDataTable(e.DataSet.Tables[0], "WorkTypeDescription");
                        e.DataSet.Tables.Remove(e.DataSet.Tables[0]);
                        e.DataSet.Tables.Add(dt);
                    };

                    // Create the data list
                    returnValue.WorkTypes = dataListCreator.Create(logonId,
                        // Give the query a name so it can be cached
                        "WorkTypeSearchForDepartment",
                        // Tell it the query criteria used so if the cache is accessed
                        // again it knows if it is the same query
                        criteria.ToString(),
                        collectionRequest,
                        // Import mappings to map the dataset row fields to the data
                        // list entity properties
                        new ImportMapping[] {
                            new ImportMapping("Id", "WorkTypeID"),
                            new ImportMapping("Description", "WorkTypeDescription"),
                            new ImportMapping("IsArchived", "WorkTypeArchived"),
                            new ImportMapping("Code","WorkTypeCode")
                            }
                        );
                }
                finally
                {
                    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>
        /// Get a list of matters
        /// </summary>
        /// <param name="logonId">Logon id obtained when logging on to the logon service</param>
        /// <param name="collectionRequest">Information about the collection being requested</param>
        /// <param name="criteria">Search criteria as enterred on the web page</param>
        /// <returns></returns>
        public MatterSearchReturnValue MatterSearch(Guid logonId, CollectionRequest collectionRequest,
                                MatterSearchCriteria criteria)
        {
            MatterSearchReturnValue returnValue = new MatterSearchReturnValue();

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

                try
                {
                    switch (UserInformation.Instance.UserType)
                    {
                        case DataConstants.UserType.Staff:
                        case DataConstants.UserType.Client:
                        case DataConstants.UserType.ThirdParty:
                            // Matter search will filter data that they are allowed to see
                            break;
                        default:
                            throw new Exception("Access denied");
                    }

                    // Create a data list creator for a list of matters
                    DataListCreator<MatterSearchItem> dataListCreator = new DataListCreator<MatterSearchItem>();

                    // Declare an inline event (annonymous delegate) to read the
                    // dataset if it is required
                    dataListCreator.ReadDataSet += delegate(object Sender, ReadDataSetEventArgs e)
                    {
                        // Create the dataset
                        e.DataSet = SrvMatterCommon.WebMatterSearch(criteria.MemberId,
                                                                    criteria.OrganisationId,
                                                                    criteria.MatterId,
                                                                    criteria.MatterDescription,
                                                                    criteria.KeyDescription,
                                                                    criteria.DepartmentCode,
                                                                    criteria.BranchCode,
                                                                    criteria.FeeEarner,
                                                                    criteria.WorkTypeCode,
                                                                    criteria.OpenedDateFrom,
                                                                    criteria.OpenedDateTo,
                                                                    criteria.ClosedDateFrom,
                                                                    criteria.ClosedDateTo,
                                                                    criteria.MatterReference,
                                                                    criteria.MatterPreviousReference,
                                                                    criteria.UFN);

                        if (criteria.OrderBy != string.Empty)
                        {
                            DataTable dt = Functions.SortDataTable(e.DataSet.Tables[0], criteria.OrderBy);
                            e.DataSet.Tables.Remove("Table");
                            e.DataSet.Tables.Add(dt);
                        }
                    };

                    // Create the data list
                    returnValue.Matters = dataListCreator.Create(logonId,
                        // Give the query a name so it can be cached
                        "MatterSearch",
                        // Tell it the query criteria used so if the cache is accessed
                        // again it knows if it is the same query
                        criteria.ToString(),
                        collectionRequest,
                        // Import mappings to map the dataset row fields to the data
                        // list entity properties
                        new ImportMapping[] {
                            new ImportMapping("Id", "ProjectId"),
                            new ImportMapping("Reference", "MatterReference"),
                            new ImportMapping("Description", "MatterDescription"),
                            new ImportMapping("KeyDescription","MatterKeyDescription"),
                            new ImportMapping("DepartmentCode","DepartmentCode"),
                            new ImportMapping("DepartmentName","Department"),
                            new ImportMapping("BranchCode","BranchCode"),
                            new ImportMapping("BranchName","BranchName"),
                            new ImportMapping("FeeEarnerName","FeeEarner"),
                            new ImportMapping("WorkTypeCode","WorkTypeCode"),
                            new ImportMapping("WorkType","WorkType"),
                            new ImportMapping("OpenedDate","OpenedDate"),
                            new ImportMapping("ClosedDate","ClosedDate")
                            }
                        );
                }
                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>
        /// Gets offices balances by project id.
        /// </summary>
        /// <param name="logonId">Logon id obtained when logging on to the logon service</param>
        /// <param name="collectionRequest">Gets collection of office balances by project id</param>
        /// <param name="projectId">Project id required to get office balances details</param>
        /// <returns>Retrieves office balances by project id</returns>
        public BalancesSearchReturnValue GetOfficeBalancesDetails(Guid logonId, CollectionRequest collectionRequest, Guid projectId)
        {
            BalancesSearchReturnValue returnValue = new BalancesSearchReturnValue();

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

                    // Create a data list creator for a list of deposit made by client
                    DataListCreator<BalancesSearchItem> dataListCreator = new DataListCreator<BalancesSearchItem>();

                    // Declare an inline event (annonymous delegate) to read the
                    // dataset if it is required
                    dataListCreator.ReadDataSet += delegate(object Sender, ReadDataSetEventArgs e)
                    {
                        DataSet dsOfficeBalances = this.GetOfficeBalances(projectId);

                        // Creates new dataset of same schema as of office balances
                        DataSet dsNewOfficeBalances = dsOfficeBalances.Clone();

                        DataView dvOfficeBalances = new DataView(dsOfficeBalances.Tables["OfficeBalances"]);
                        if (dvOfficeBalances.Count != 0)
                        {
                            string columnOrderByPostingDate = Convert.ToString(dsOfficeBalances.Tables["OfficeBalances"].Columns["PostingDate"]);
                            dvOfficeBalances.Sort = columnOrderByPostingDate + " " + "asc";

                            decimal debit = decimal.Zero;
                            decimal credit = decimal.Zero;
                            decimal balance = decimal.Zero;

                            foreach (DataRowView officeBalancesRowView in dvOfficeBalances)
                            {
                                int postingId = Convert.ToInt32(officeBalancesRowView.Row["PostingId"].ToString().Trim());
                                DateTime postingDate = (DateTime)officeBalancesRowView.Row["PostingDate"];
                                string postingReference = (string)officeBalancesRowView.Row["PostingReference"].ToString();
                                string postingType = (string)officeBalancesRowView.Row["PostingType"].ToString(); ;
                                string postingDescription = (string)officeBalancesRowView.Row["PostingDescription"].ToString();
                                string postingBank = (string)officeBalancesRowView.Row["PostingBank"].ToString();
                                string postingBankRef = (string)officeBalancesRowView.Row["PostingBankRef"].ToString();
                                debit = (decimal)officeBalancesRowView.Row["Debit"];
                                credit = (decimal)officeBalancesRowView.Row["Credit"];
                                balance = balance + debit - credit;
                                balance = Decimal.Round(balance, 2);

                                // Adds deposit details to dataset after calculations
                                dsNewOfficeBalances.Tables["OfficeBalances"].Rows.Add(postingId,
                                                                                     postingDate,
                                                                                     postingReference,
                                                                                     postingType,
                                                                                     postingDescription,
                                                                                     postingBank,
                                                                                     postingBankRef,
                                                                                     debit.ToString("0.00"),
                                                                                     credit.ToString("0.00"),
                                                                                     balance.ToString("0.00"));
                            }
                        }

                        e.DataSet = dsNewOfficeBalances;
                    };

                    // Create the data list
                    returnValue.Balances = dataListCreator.Create(logonId,
                        // Give the query a name so it can be cached
                        "GetOfficeBalancesDetails",
                        // Tell it the query criteria used so if the cache is accessed
                        // again it knows if it is the same query
                        projectId.ToString(),
                        collectionRequest,
                        // Import mappings to map the dataset row fields to the data
                        // list entity properties
                        new ImportMapping[] {
                                            new ImportMapping("PostingId", "PostingId"),
                                            new ImportMapping("PostingDate", "PostingDate"),
                                            new ImportMapping("PostingReference", "PostingReference"),
                                            new ImportMapping("PostingType", "PostingType"),
                                            new ImportMapping("PostingDescription","PostingDescription"),
                                            new ImportMapping("PostingBank", "PostingBank"),
                                            new ImportMapping("PostingBankRef", "PostingBankRef"),
                                            new ImportMapping("Debit","Debit"),
                                            new ImportMapping("Credit","Credit"),
                                            new ImportMapping("Balance","Balance")
                            }
                        );

                    returnValue.Success = true;
                }
                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>
        /// 
        /// </summary>
        /// <param name="logonId"></param>
        /// <param name="collectionRequest"></param>
        /// <param name="criteria"></param>
        /// <returns></returns>
        public BranchSearchReturnValue BranchSearch(Guid logonId, CollectionRequest collectionRequest)
        {
            BranchSearchReturnValue returnValue = new BranchSearchReturnValue();

            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:
                        case DataConstants.UserType.Client:
                        case DataConstants.UserType.ThirdParty:
                            // Can do everything
                            break;
                        default:
                            throw new Exception("Access denied");
                    }

                    // Create a data list creator for a list of matters
                    DataListCreator<BranchSearchItem> dataListCreator = new DataListCreator<BranchSearchItem>();

                    // Declare an inline event (annonymous delegate) to read the
                    // dataset if it is required
                    dataListCreator.ReadDataSet += delegate(object Sender, ReadDataSetEventArgs e)
                    {
                        // Create the dataset
                        //e.DataSet = service layer routine to do the query
                        e.DataSet = SrvBranchLookup.GetBranchLookup();

                        DataTable dt = Functions.SortDataTable(e.DataSet.Tables[0], "OrgName");
                        e.DataSet.Tables.Remove(e.DataSet.Tables[0]);
                        e.DataSet.Tables.Add(dt);

                        foreach (DataRow r in e.DataSet.Tables[0].Rows)
                        {
                            r["branchRef"] = r["branchRef"].ToString().Trim();
                            r["OrgName"] = r["branchRef"].ToString().Trim() + " - " + r["OrgName"];
                        }
                    };

                    // Create the data list
                    returnValue.Branches = dataListCreator.Create(logonId,
                        // Give the query a name so it can be cached
                        "BranchSearch",
                        // Tell it the query criteria used so if the cache is accessed
                        // again it knows if it is the same query
                        null,
                        collectionRequest,
                        // Import mappings to map the dataset row fields to the data
                        // list entity properties
                        new ImportMapping[] {
                            new ImportMapping("OrganisationId", "OrgID"),
                            new ImportMapping("Reference", "branchRef"),
                            new ImportMapping("Name", "OrgName"),
                            new ImportMapping("IsLondonRate", "branchLondonRate")
                            }
                        );
                }
                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 DiaryParameterReturnValue GetTaskTypes(Guid logonId, CollectionRequest collectionRequest)
        {
            DiaryParameterReturnValue returnValue = new DiaryParameterReturnValue();

            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:
                        case DataConstants.UserType.Client:
                        case DataConstants.UserType.ThirdParty:
                            // Can do everything
                            break;
                        default:
                            throw new Exception("Access denied");
                    }

                    // Create a data list creator for a list of banks
                    DataListCreator<DiaryParameterSearchItem> dataListCreator = new DataListCreator<DiaryParameterSearchItem>();

                    // Declare an inline event (annonymous delegate) to read the
                    // dataset if it is required
                    dataListCreator.ReadDataSet += delegate(object Sender, ReadDataSetEventArgs e)
                    {
                        DataSet dsTaskType = new DataSet();
                        DataColumn dcBookingTypeID = new DataColumn("BookingTypeID", typeof(System.Int32));
                        DataColumn dcBTDescription = new DataColumn("BTDescription");
                        DataTable dtTaskType = new DataTable();
                        dtTaskType.Columns.Add(dcBookingTypeID);
                        dtTaskType.Columns.Add(dcBTDescription);

                        DiaryParamsDts dts = SrvDiaryParameterLookup.GetDiaryParameter();
                        foreach (DiaryParamsDts.TaskTypesRow dr in dts.TaskTypes.Rows)
                        {
                            //if (!dr.CRDefault)
                            {
                                DataRow drNew = dtTaskType.NewRow();
                                drNew["BookingTypeID"] = dr.BookingTypeID;
                                drNew["BTDescription"] = dr.BTDescription;
                                dtTaskType.Rows.Add(drNew);
                            }
                        }
                        dsTaskType.Tables.Add(dtTaskType);

                        e.DataSet = dsTaskType;
                    };

                    // Create the data list
                    returnValue.DiaryParamters = dataListCreator.Create(logonId,
                        // Give the query a name so it can be cached
                        "TaskTypeSearch",
                        // Tell it the query criteria used so if the cache is accessed
                        // again it knows if it is the same query
                        string.Empty,
                        collectionRequest,
                        // Import mappings to map the dataset row fields to the data
                        // list entity properties
                        new ImportMapping[] {
                            new ImportMapping("Id", "BookingTypeID"),
                            new ImportMapping("Description", "BTDescription")
                            }
                        );
                }
                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>
        /// Loads disbursement details by project id
        /// </summary>
        /// <param name="logonId">Logon id obtained when logging on to the logon service</param>
        /// <param name="accounts">Retrieves project id to load disbursement details.</param>
        /// <returns>Loads disbursement details by project id</returns>
        public DisbursementsSearchReturnValue GetDisbursementsDetails(Guid logonId, CollectionRequest collectionRequest, Guid projectId)
        {
            DisbursementsSearchReturnValue returnValue = new DisbursementsSearchReturnValue();

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

                    // Create a data list creator for a list of matters
                    DataListCreator<DisbursementSearchItem> dataListCreator = new DataListCreator<DisbursementSearchItem>();

                    // Declare an inline event (annonymous delegate) to read the
                    // dataset if it is required
                    dataListCreator.ReadDataSet += delegate(object Sender, ReadDataSetEventArgs e)
                    {
                        DsDisbLedgerTransactions dsDisbLedgerTransactions = SrvDisbLedgerLookup.GetDisbursementsLedgerTransactions(projectId);

                        DataSet dsDisbursements = new DataSet();
                        dsDisbursements.Tables.Add("Disbursements");
                        dsDisbursements.Tables["Disbursements"].Columns.Add("PostingId", typeof(int));
                        dsDisbursements.Tables["Disbursements"].Columns.Add("PostingDate", typeof(DateTime));
                        dsDisbursements.Tables["Disbursements"].Columns.Add("PostingReference", typeof(string));
                        dsDisbursements.Tables["Disbursements"].Columns.Add("PostingDisbursementType", typeof(string));
                        dsDisbursements.Tables["Disbursements"].Columns.Add("PostingDescription", typeof(string));
                        dsDisbursements.Tables["Disbursements"].Columns.Add("PostingPaid", typeof(string));
                        dsDisbursements.Tables["Disbursements"].Columns.Add("PostingVAT", typeof(string));
                        dsDisbursements.Tables["Disbursements"].Columns.Add("Amount", typeof(decimal));
                        dsDisbursements.Tables["Disbursements"].Columns.Add("BillingStatus", typeof(string));
                        dsDisbursements.Tables["Disbursements"].Columns.Add("Claimed", typeof(decimal));
                        dsDisbursements.Tables["Disbursements"].Columns.Add("Balance", typeof(decimal));

                        DataView dvDisbursements = new DataView(dsDisbLedgerTransactions.uvw_DisbLedgerTransactions);
                        if (dvDisbursements.Count != 0)
                        {
                            string columnOrderByPostingDate = Convert.ToString(dsDisbLedgerTransactions.uvw_DisbLedgerTransactions.Columns["postingDetailsDate"]);
                            dvDisbursements.Sort = columnOrderByPostingDate + " " + "asc";

                            string postingPaid = string.Empty;
                            string unbilledStatus = "Billed";
                            decimal balance = decimal.Zero;
                            decimal unbilled = decimal.Zero;
                            decimal claimed = decimal.Zero;
                            decimal amount = decimal.Zero;

                            foreach (DataRowView disbursementRowView in dvDisbursements)
                            {
                                int postingId = Convert.ToInt32(disbursementRowView.Row["PostingId"].ToString().Trim());
                                DateTime postingDate = (DateTime)disbursementRowView.Row["PostingDetailsDate"];
                                string postingReference = (string)disbursementRowView.Row["PostingDetailsRef"].ToString();
                                string postingDisbursementType = (string)disbursementRowView.Row["DisbTypeDescription"].ToString();
                                string postingDescription = (string)disbursementRowView.Row["PostingDetailsDescription"].ToString();
                                int disbursementStatusId = ((int)disbursementRowView.Row["DisbStatusId"]);

                                switch (disbursementStatusId)
                                {
                                    case 1:
                                        postingPaid = "P";
                                        break;
                                    case 2:
                                        postingPaid = "U";
                                        break;
                                    case 3:
                                        postingPaid = "C";
                                        break;
                                    case 4:
                                        postingPaid = "I";
                                        break;
                                    case 5:
                                        postingPaid = "X";
                                        break;
                                    case 6:
                                        postingPaid = "x";
                                        break;
                                    case 7:
                                        postingPaid = "P";
                                        break;
                                }

                                string postingVAT = string.Empty;
                                int VATRateId = ((int)disbursementRowView.Row["VatRateId"]);
                                if (VATRateId == 1)
                                {
                                    postingVAT = "N";
                                }
                                else
                                {
                                    postingVAT = "V";
                                }

                                amount = (decimal)disbursementRowView.Row["DisbLedgerMasterAmount"] + (decimal)disbursementRowView.Row["DisbLedgerMasterVatAmount"];
                                unbilled = (decimal)disbursementRowView.Row["DisbLedgerMasterAmount"] + (decimal)disbursementRowView.Row["DisbLedgerMasterVatAmount"] - (decimal)disbursementRowView.Row["BillDisbAllocAmount"];
                                claimed = (decimal)disbursementRowView.Row["ClaimedDisbs"];

                                balance = balance + unbilled;
                                amount = Decimal.Round(amount, 2);
                                unbilled = Decimal.Round(unbilled, 2);
                                claimed = Decimal.Round(claimed, 2);
                                balance = Decimal.Round(balance, 2);

                                unbilledStatus = (unbilled != Decimal.Zero ? unbilled.ToString("0.00") : "Billed");

                                dsDisbursements.Tables["Disbursements"].Rows.Add(postingId,
                                                                                 postingDate,
                                                                                 postingReference,
                                                                                 postingDisbursementType,
                                                                                 postingDescription,
                                                                                 postingPaid,
                                                                                 postingVAT,
                                                                                 amount.ToString("0.00"),
                                                                                 unbilledStatus,
                                                                                 claimed.ToString("0.00"),
                                                                                 balance.ToString("0.00"));
                            }
                        }

                        e.DataSet = dsDisbursements;
                    };

                    // Create the data list
                    returnValue.Disbursements = dataListCreator.Create(logonId,
                        // Give the query a name so it can be cached
                        "GetDisbursementsDetails",
                        // Tell it the query criteria used so if the cache is accessed
                        // again it knows if it is the same query
                        projectId.ToString(),
                        collectionRequest,
                        // Import mappings to map the dataset row fields to the data
                        // list entity properties
                        new ImportMapping[] {
                                            new ImportMapping("PostingId", "PostingId"),
                                            new ImportMapping("PostingDate", "PostingDate"),
                                            new ImportMapping("PostingReference", "PostingReference"),
                                            new ImportMapping("PostingType", "PostingDisbursementType"),
                                            new ImportMapping("PostingDescription","PostingDescription"),
                                            new ImportMapping("PostingPaid", "PostingPaid"),
                                            new ImportMapping("PostingVAT","PostingVAT"),
                                            new ImportMapping("Amount","Amount"),
                                            new ImportMapping("BillingStatus","BillingStatus"),
                                            new ImportMapping("Balance","Balance"),
                                            new ImportMapping("Claimed","Claimed")
                            }
                        );

                    returnValue.Success = true;
                }
                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 DiaryMemberSearchReturnValue GetDiaryMembers(Guid logonId, CollectionRequest collectionRequest)
        {
            DiaryMemberSearchReturnValue returnValue = new DiaryMemberSearchReturnValue();

            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:
                            // TODO later this should just be restricted to staff only
                            //Clients and Third Party users can create public tasks
                            //throw new Exception("Access denied");
                            break;
                        default:
                            throw new Exception("Access denied");
                    }

                    // Create a data list creator for a list of banks
                    DataListCreator<DiaryMemberSearchItem> dataListCreator = new DataListCreator<DiaryMemberSearchItem>();

                    // Declare an inline event (annonymous delegate) to read the
                    // dataset if it is required
                    dataListCreator.ReadDataSet += delegate(object Sender, ReadDataSetEventArgs e)
                    {
                        DiaryViewMembersDts dsMembers = SrvDiaryBookingMemberLookup.GetAllDiaryMembers();

                        DataView dvMembers = new DataView(dsMembers.Tables[0]);
                        //dvMembers.RowFilter = " (DocDescription <> 'PLACEHOLDER_FOLDER')";
                        dvMembers.Sort = "MemberDisplayName asc";

                        DataSet dsMembers1 = new DataSet();
                        dsMembers1.Tables.Add(dvMembers.ToTable());
                        e.DataSet = dsMembers1;
                    };

                    // Create the data list
                    returnValue.DiaryMembers = dataListCreator.Create(logonId,
                        // Give the query a name so it can be cached
                        "DiaryMemberSearch",
                        // Tell it the query criteria used so if the cache is accessed
                        // again it knows if it is the same query
                        string.Empty,
                        collectionRequest,
                        // Import mappings to map the dataset row fields to the data
                        // list entity properties
                        new ImportMapping[] {
                            new ImportMapping("MemberID", "MemberID"),
                            new ImportMapping("MemberDisplayName", "MemberDisplayName"),
                            new ImportMapping("MemberCode", "MemberCode")
                            }
                        );
                }
                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 AppointmentSearchReturnValue AppointmentSearch(Guid logonId, CollectionRequest collectionRequest,
                                AppointmentSearchCriteria criteria)
        {
            AppointmentSearchReturnValue returnValue = new AppointmentSearchReturnValue();

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

                    // Create a data list creator for a list of matters
                    DataListCreator<Appointment> dataListCreator = new DataListCreator<Appointment>();

                    // Declare an inline event (annonymous delegate) to read the
                    // dataset if it is required
                    dataListCreator.ReadDataSet += delegate(object Sender, ReadDataSetEventArgs e)
                    {
                        DiaryMemberSearchItem diaryMembers = this.GetDiaryMemberDetails(criteria.MemberID);
                        string UsersChosenMemberID = criteria.MemberID;
                        DateTime usersDiaryDate = DateTime.Today;
                        int CurrentDiaryDays = 1;
                        bool ShowCancelled = false;
                        bool ShowTasks = false;
                        bool ExcludeEmptyDiaryDaysForUsers = true;
                        bool ExcludeEmptyDiaryDaysForGroups = true;
                        string memberIds;
                        string[] usersChosenMemberIDs = new string[] { };
                        int usersDiaryDaysView = 7;

                        DiaryViewDts dvDiary = new DiaryViewDts();

                        if (criteria.Date == DataConstants.BlankDate)
                        {
                            usersDiaryDate = DateTime.Today;
                        }
                        else
                        {
                            usersDiaryDate = Convert.ToDateTime(criteria.Date);
                        }

                        if (!diaryMembers.IsGroup)
                        {
                            UsersChosenMemberID = diaryMembers.MemberID;
                            dvDiary = SrvBookingEntryLookup.GetDiaryBookingsForMember(UsersChosenMemberID, usersDiaryDate,
                                CurrentDiaryDays, ShowCancelled, ShowTasks, usersDiaryDaysView, ExcludeEmptyDiaryDaysForUsers);
                        }
                        else
                        {
                            usersChosenMemberIDs = this.ResolveGroupMembers(int.Parse(diaryMembers.MemberID));
                            memberIds = string.Join(",", usersChosenMemberIDs);

                            dvDiary = SrvBookingEntryLookup.GetDiaryBookingsForMembers(memberIds, usersDiaryDate, CurrentDiaryDays, ShowCancelled, ShowTasks, usersDiaryDaysView, ExcludeEmptyDiaryDaysForGroups);
                        }

                        // Add New Column Editable
                        dvDiary.Tables[0].Columns.Add("isEdit");

                        for (int i = 0; i < dvDiary.Tables[0].Rows.Count; i++)
                        {
                            dvDiary.Tables[0].Rows[i]["isEdit"] = this.IsOccurrenceViewableBy(Convert.ToInt32(dvDiary.Tables[0].Rows[i]["OccurrenceID"]));
                        }

                        e.DataSet = dvDiary;

                        if (criteria.OrderBy != string.Empty)
                        {
                            DataTable dt = Functions.SortDataTable(e.DataSet.Tables[0], criteria.OrderBy);
                            e.DataSet.Tables.Remove("DiaryEntries");
                            e.DataSet.Tables.Add(dt);
                        }
                    };

                    returnValue.Appointments = dataListCreator.Create(logonId,
                                                "AppointmentSearch",
                        // Tell it the query criteria used so if the cache is accessed
                        // again it knows if it is the same query
                                            criteria.ToString(),
                                            collectionRequest,
                        // Import mappings to map the dataset row fields to the data
                        // list entity properties
                                            new ImportMapping[] {
                                                new ImportMapping("Id", "OccurrenceID"),
                                                new ImportMapping("StartDate", "Date"),
                                                new ImportMapping("Subject", "OccSpecificText"),
                                                new ImportMapping("StartTime", "StartTime"),
                                                new ImportMapping("EndTime", "EndTime"),
                                                new ImportMapping("Notes", "OccurrenceNoteText"),
                                                new ImportMapping("VenueText", "VenueDescription"),
                                                new ImportMapping("Duration", "EstTime"),
                                                new ImportMapping("IsEditable", "isEdit")
                                                // More fields are required here but the service layer query may not be
                                                // providing them.  This is enough for a test.
                                                }
                                            );
                }
                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 TaskSearchReturnValue MemberTaskSearch(Guid logonId, CollectionRequest collectionRequest,
                                TaskSearchCriteria criteria)
        {
            TaskSearchReturnValue returnValue = new TaskSearchReturnValue();

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

                    // Create a data list creator for a list of matters
                    DataListCreator<Task> dataListCreator = new DataListCreator<Task>();

                    // Declare an inline event (annonymous delegate) to read the
                    // dataset if it is required
                    dataListCreator.ReadDataSet += delegate(object Sender, ReadDataSetEventArgs e)
                    {
                        DiaryMemberSearchItem diaryMembers = this.GetDiaryMemberDetails(criteria.MemberID);
                        string UsersChosenMemberID = criteria.MemberID;
                        DateTime usersDiaryDate = DateTime.Today;
                        bool ShowCancelled = false;
                        string memberIds;
                        string[] usersChosenMemberIDs = new string[] { };
                        DateTime taskFromDate = usersDiaryDate;
                        DateTime taskToDate = usersDiaryDate;

                        TimeSpan timeSpan = taskToDate - taskFromDate;
                        int taskNoOfDays = (timeSpan.Days + 1);

                        int taskBookingID = 0;
                        int statusID = 0;
                        string occurrencePriority = string.Empty;
                        int dateFilter = 0;
                        int incItems = 1;
                        int progress = 0;

                        DiaryViewDts dvDiary = new DiaryViewDts();

                        if (criteria.StartDate != DataConstants.BlankDate)
                        {
                            taskFromDate = Convert.ToDateTime(criteria.StartDate);
                        }

                        if (!diaryMembers.IsGroup)
                        {
                            UsersChosenMemberID = diaryMembers.MemberID;
                            dvDiary = SrvBookingEntryLookup.GetAllTasksForMember(UsersChosenMemberID, taskFromDate,
                                ShowCancelled, taskNoOfDays, taskBookingID, statusID, occurrencePriority, dateFilter, incItems, progress);
                        }
                        else
                        {
                            usersChosenMemberIDs = this.ResolveGroupMembers(int.Parse(diaryMembers.MemberID));
                            memberIds = string.Join(",", usersChosenMemberIDs);

                            dvDiary = SrvBookingEntryLookup.GetAllTasksForMember(memberIds, taskFromDate,
                                ShowCancelled, taskNoOfDays, taskBookingID, statusID, occurrencePriority, dateFilter, incItems, progress);
                        }

                        // Add New Column Editable
                        dvDiary.DiaryEntries.Columns.Add("isEdit");
                        // Add New Column Matters
                        dvDiary.DiaryEntries.Columns.Add("OccurrenceMatter");
                        // Add New Column IsLimitation
                        dvDiary.DiaryEntries.Columns.Add("IsLimitationTask", typeof(Boolean));
                        // Add New Column NewRecordedDueDate for filtering
                        dvDiary.DiaryEntries.Columns.Add("NewRecordedDueDate", typeof(DateTime));

                        System.Collections.ArrayList listIds = new System.Collections.ArrayList();
                        foreach (DiaryViewDts.DiaryEntriesRow row in dvDiary.DiaryEntries.Rows)
                        {
                            row["isEdit"] = this.IsOccurrenceViewableBy(row.OccurrenceID);
                            row["IsLimitationTask"] = this.IsALimitationTask(Convert.ToInt32(row.BookingTypeID));

                            if (!listIds.Contains(row.BookingID))
                            {
                                listIds.Add(row.BookingID);
                            }

                            if (row["RecordedDueDate"].ToString() != "")
                            {
                                row["NewRecordedDueDate"] = Convert.ToDateTime(row["RecordedDueDate"]);
                            }
                        }

                        StringBuilder ids = new StringBuilder();
                        foreach (int bookingId in listIds)
                        {
                            ids.Append(bookingId.ToString());
                            ids.Append(",");
                        }

                        DiaryViewMattersDts matterDts = new DiaryViewMattersDts();
                        if (ids.Length > 0)
                        {
                            ids.Length--;

                            matterDts = SrvBookingEntryLookup.GetMattersForBookings(ids.ToString());
                        }

                        foreach (DiaryViewDts.DiaryEntriesRow row in dvDiary.DiaryEntries.Rows)
                        {
                            DiaryViewMattersDts.BookingMatterRow[] matterRows;
                            matterRows = (DiaryViewMattersDts.BookingMatterRow[])matterDts.BookingMatter.Select(string.Format("BookingID = {0}", row.BookingID));
                            StringBuilder sb = new StringBuilder();
                            foreach (DiaryViewMattersDts.BookingMatterRow matterRow in matterRows)
                            {
                                sb.AppendFormat("{0}$({1}-{2})  {3}~", matterRow.ProjectID, matterRow.MatterRef.Substring(0, 6), matterRow.MatterRef.Substring(6, 4), matterRow.matDescription);
                            }
                            if (sb.Length > 0)
                            {
                                string matters = sb.ToString().Substring(0, sb.Length - 1);
                                row["OccurrenceMatter"] = matters;
                            }
                        }

                        DataView dvDiaryView = new DataView(dvDiary.Tables[0]);
                        string filter = string.Empty;

                        switch (criteria.Status)
                        {
                            case "Outstanding":
                                filter += " (OccStatusDesc <> 'Completed') and ";
                                break;
                            case "Completed":
                                filter += " (OccStatusDesc = 'Completed') and ";
                                break;
                        }

                        bool isStartDate = false;

                        if (criteria.StartDate != DataConstants.BlankDate)
                        {
                            filter += " ((NewRecordedDueDate >= #" + Convert.ToDateTime(criteria.StartDate).ToString("yyyy-MM-dd") + "#) ";
                            isStartDate = true;
                        }
                        if (criteria.ToDate != DataConstants.BlankDate)
                        {
                            if (isStartDate)
                            {
                                filter += " and ";
                            }

                            filter += "(NewRecordedDueDate <= #" + Convert.ToDateTime(criteria.ToDate).ToString("yyyy-MM-dd") + "#)";

                            if (isStartDate)
                            {
                                filter += ") ";
                            }

                            filter += " and ";

                        }
                        else
                        {
                            filter += ") and ";
                        }

                        if (!string.IsNullOrEmpty(filter))
                        {
                            filter = filter.Trim().Substring(0, filter.Trim().Length - 3);
                        }

                        dvDiaryView.RowFilter = filter;

                        DataSet dsFiltered = new DataSet();
                        dsFiltered.Tables.Add(dvDiaryView.ToTable());

                        e.DataSet = dsFiltered;

                        if (criteria.OrderBy != string.Empty)
                        {
                            DataTable dt = Functions.SortDataTable(e.DataSet.Tables[0], criteria.OrderBy);
                            e.DataSet.Tables.Remove("DiaryEntries");
                            e.DataSet.Tables.Add(dt);
                        }
                    };

                    returnValue.Tasks = dataListCreator.Create(logonId,
                                                "TaskSearch",
                        // Tell it the query criteria used so if the cache is accessed
                        // again it knows if it is the same query
                                            criteria.ToString(),
                                            collectionRequest,
                        // Import mappings to map the dataset row fields to the data
                        // list entity properties
                                            new ImportMapping[] {
                                                new ImportMapping("Id", "OccurrenceID"),
                                                new ImportMapping("RecordedDueDate", "RecordedDueDate"),
                                                new ImportMapping("Subject", "OccSpecificText"),
                                                new ImportMapping("StatusDesc", "OccStatusDesc"),
                                                new ImportMapping("Progress", "OccProgress"),
                                                new ImportMapping("Notes", "OccurrenceNoteText"),
                                                new ImportMapping("Matters", "OccurrenceMatter"),
                                                new ImportMapping("IsEditable", "isEdit"),
                                                new ImportMapping("IsLimitationTask", "IsLimitationTask")
                                                // More fields are required here but the service layer query may not be
                                                // providing them.  This is enough for a test.
                                                }
                                            );
                }
                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 TaskSearchReturnValue MatterTaskSearch(Guid logonId, CollectionRequest collectionRequest, TaskSearchCriteria criteria)
        {
            TaskSearchReturnValue returnValue = new TaskSearchReturnValue();

            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:
                            if (!SrvMatterCommon.WebAllowedToAccessMatter(criteria.ProjectID))
                                throw new Exception("Access denied");

                            break;
                        default:
                            throw new Exception("Access denied");
                    }

                    // Create a data list creator for a list of matters
                    DataListCreator<Task> dataListCreator = new DataListCreator<Task>();

                    // Declare an inline event (annonymous delegate) to read the
                    // dataset if it is required
                    dataListCreator.ReadDataSet += delegate(object Sender, ReadDataSetEventArgs e)
                    {
                        DsOccurencesForProject dvDiary = new DsOccurencesForProject();

                        dvDiary = SrvOccurenceLookup.GetOccurencesForProject(criteria.ProjectID);

                        // Add New Column Editable
                        dvDiary.uvw_OccurencesForProject.Columns.Add("isEdit");
                        dvDiary.uvw_OccurencesForProject.Columns.Add("AttendeeName");
                        dvDiary.uvw_OccurencesForProject.Columns.Add("IsLimitationTask", typeof(Boolean));
                        // Add New Column NewOccDueDate for filtering
                        dvDiary.uvw_OccurencesForProject.Columns.Add("NewOccDueDate", typeof(DateTime));

                        foreach (IRIS.Law.PmsCommonData.Diary.DsOccurencesForProject.uvw_OccurencesForProjectRow row in dvDiary.uvw_OccurencesForProject)
                        {
                            row["isEdit"] = this.IsOccurrenceViewableBy(Convert.ToInt32(row.OccurrenceID));
                            row["IsLimitationTask"] = this.IsALimitationTask(Convert.ToInt32(row.BookingTypeID));
                            row["AttendeeName"] = CommonFunctions.MakeFullName(row.PersonTitle, row.PersonName, row.PersonSurname);

                            if (row["OccDueDate"].ToString() != "")
                            {
                                row["NewOccDueDate"] = Convert.ToDateTime(row["OccDueDate"]);
                            }
                        }

                        DataView dvDiaryView = new DataView(dvDiary.Tables[0]);
                        string filter = string.Empty;

                        switch (criteria.Status)
                        {
                            case "Outstanding":
                                filter += " (OccStatus <> 'Completed') and ";
                                break;
                            case "Completed":
                                filter += " (OccStatus = 'Completed') and ";
                                break;
                        }

                        // Filter only BookingType which is of Task
                        // BookingTypeID: 4 - Key Date, 5 - Limitation Date, 12 - Standard Task
                        CollectionRequest collection = new CollectionRequest();
                        DiaryParameterReturnValue taskTypes = this.GetTaskTypes(logonId, collection);
                        string bookingTypeId = string.Empty;
                        for (int i = 0; i < taskTypes.DiaryParamters.Rows.Count; i++)
                        {
                            bookingTypeId += taskTypes.DiaryParamters.Rows[i].Id.ToString() + ",";
                        }
                        if (bookingTypeId.Length > 0)
                        {
                            bookingTypeId = bookingTypeId.Trim().Substring(0, bookingTypeId.Trim().Length - 1);
                        }
                        if (!string.IsNullOrEmpty(bookingTypeId))
                        {
                            filter += " (BookingTypeID in (" + bookingTypeId + ")) and ";
                        }
                        //filter += " (BookingTypeID in (4, 5, 12)) and ";

                        //if (criteria.StartDate != DataConstants.BlankDate)
                        //{
                        //    filter += " (OccDueDate = '" + criteria.StartDate.ToString() + "') and ";
                        //}

                        bool isStartDate = false;

                        if (criteria.StartDate != DataConstants.BlankDate)
                        {
                            filter += " ((NewOccDueDate >= #" + Convert.ToDateTime(criteria.StartDate).ToString("yyyy-MM-dd") + "#) ";
                            isStartDate = true;
                        }
                        if (criteria.ToDate != DataConstants.BlankDate)
                        {
                            if (isStartDate)
                            {
                                filter += " and ";
                            }

                            filter += "(NewOccDueDate <= #" + Convert.ToDateTime(criteria.ToDate).ToString("yyyy-MM-dd") + "#)";

                            if (isStartDate)
                            {
                                filter += ") ";
                            }

                            filter += " and ";

                        }
                        else
                        {
                            filter += ") and ";
                        }

                        if (!string.IsNullOrEmpty(criteria.MemberID))
                        {
                            DiaryMemberSearchItem diaryMembers = this.GetDiaryMemberDetails(criteria.MemberID);
                            string memberIds = string.Empty;
                            if (!diaryMembers.IsGroup)
                            {
                                memberIds += "Convert('" + criteria.MemberID + "', 'System.Guid'), ";
                            }
                            else
                            {
                                string[] usersChosenMemberIDs = this.ResolveGroupMembers(int.Parse(diaryMembers.MemberID));
                                if (usersChosenMemberIDs.Length > 0)
                                {
                                    for (int i = 0; i < usersChosenMemberIDs.Length; i++)
                                    {
                                        memberIds += "Convert('" + usersChosenMemberIDs[i] + "', 'System.Guid'),";
                                    }
                                }
                            }

                            if (!string.IsNullOrEmpty(memberIds))
                            {
                                memberIds = memberIds.Trim().Substring(0, memberIds.Trim().Length - 1);
                                filter += " (MemberID in (" + memberIds + ")) and ";
                            }
                        }
                        //If user is client or third party then can only return public tasks.
                        switch (UserInformation.Instance.UserType)
                        {
                            case DataConstants.UserType.Staff:
                                // Can do everything
                                break;
                            case DataConstants.UserType.Client:
                            case DataConstants.UserType.ThirdParty:
                                // Return only Public tasks
                                if (!string.IsNullOrEmpty(filter))
                                {
                                    filter += " (OccIsPublic = 1) and ";
                                }
                                break;
                            default:
                                throw new Exception("Unknown UserType");
                        }

                        if (!string.IsNullOrEmpty(filter))
                        {
                            filter = filter.Trim().Substring(0, filter.Trim().Length - 3);
                        }

                        dvDiaryView.RowFilter = filter;
                        dvDiaryView.Sort = "OccDueDate desc";

                        DataSet dsFiltered = new DataSet();
                        dsFiltered.Tables.Add(dvDiaryView.ToTable());

                        e.DataSet = dsFiltered;

                        if (criteria.OrderBy != string.Empty)
                        {
                            DataTable dt = Functions.SortDataTable(e.DataSet.Tables[0], criteria.OrderBy);
                            e.DataSet.Tables.Remove("uvw_OccurencesForProject");
                            e.DataSet.Tables.Add(dt);
                        }
                    };

                    returnValue.Tasks = dataListCreator.Create(logonId,
                                            "TaskMatterSearch",
                        // Tell it the query criteria used so if the cache is accessed
                        // again it knows if it is the same query
                                            criteria.ToString(),
                                            collectionRequest,
                        // Import mappings to map the dataset row fields to the data
                        // list entity properties
                                            new ImportMapping[] {
                                                new ImportMapping("Id", "OccurrenceID"),
                                                new ImportMapping("DueDate", "OccDueDate"),
                                                new ImportMapping("Subject", "OccSpecificText"),
                                                new ImportMapping("StatusDesc", "OccStatus"),
                                                //new ImportMapping("Progress", "OccProgress"),
                                                new ImportMapping("AttendeesName", "AttendeeName"),
                                                //new ImportMapping("Matters", "OccurrenceMatter"),
                                                new ImportMapping("IsEditable", "isEdit"),
                                                new ImportMapping("IsLimitationTask", "IsLimitationTask")
                                                // More fields are required here but the service layer query may not be
                                                // providing them.  This is enough for a test.
                                                }
                                            );
                }
                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>
        /// Loads all the bills by project id
        /// </summary>
        /// <param name="logonId">Logon id obtained when logging on to the logon service</param>
        /// <param name="projectId">To load all the bills</param>
        /// <returns>Loads all the bills by project id</returns>
        public TimeLedgerSearchReturnValue GetTimeLedger(Guid logonId, CollectionRequest collectionRequest, string timeFilter, Guid projectId)
        {
            TimeLedgerSearchReturnValue returnValue = new TimeLedgerSearchReturnValue();

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

                    // Create a data list creator for a list of bills
                    DataListCreator<TimeLedgerSearchItem> dataListCreator = new DataListCreator<TimeLedgerSearchItem>();

                    // Declare an inline event (annonymous delegate) to read the
                    // dataset if it is required
                    dataListCreator.ReadDataSet += delegate(object Sender, ReadDataSetEventArgs e)
                    {
                        NetTimeTransactionsReturnValue totalTimeTransactions = new NetTimeTransactionsReturnValue();
                        DsTimeTransactions dsTimeTransactions = SrvTimeLookup.GetTimeTransactions(projectId, timeFilter, false);

                        DataSet dsAllTimeTransactions = new DataSet();
                        dsAllTimeTransactions.Tables.Add("AllTimeTransactions");
                        dsAllTimeTransactions.Tables["AllTimeTransactions"].Columns.Add("TimeId", typeof(int));
                        dsAllTimeTransactions.Tables["AllTimeTransactions"].Columns.Add("TimeDate", typeof(DateTime));
                        dsAllTimeTransactions.Tables["AllTimeTransactions"].Columns.Add("TimeType", typeof(string));
                        dsAllTimeTransactions.Tables["AllTimeTransactions"].Columns.Add("FeeEarnerReference", typeof(string));
                        dsAllTimeTransactions.Tables["AllTimeTransactions"].Columns.Add("Time", typeof(string));
                        dsAllTimeTransactions.Tables["AllTimeTransactions"].Columns.Add("TotalTimeElapsed", typeof(int));
                        dsAllTimeTransactions.Tables["AllTimeTransactions"].Columns.Add("Cost", typeof(decimal));
                        dsAllTimeTransactions.Tables["AllTimeTransactions"].Columns.Add("CostBalance", typeof(decimal));
                        dsAllTimeTransactions.Tables["AllTimeTransactions"].Columns.Add("Charge", typeof(decimal));
                        dsAllTimeTransactions.Tables["AllTimeTransactions"].Columns.Add("ChargeBalance", typeof(decimal));

                        int timeElapsed = 0;
                        decimal cost = decimal.Zero;
                        decimal costBalance = decimal.Zero;
                        decimal charge = decimal.Zero;
                        decimal chargeBalance = decimal.Zero;

                        DataView dvAllTimeTransactions = new DataView(dsTimeTransactions.uvw_TimeTransactions);
                        if (dvAllTimeTransactions.Count != 0)
                        {
                            string columnOrderByPostingDate = Convert.ToString(dsTimeTransactions.uvw_TimeTransactions.Columns["TimeDate"]);
                            dvAllTimeTransactions.Sort = columnOrderByPostingDate + " " + "asc";

                            foreach (DataRowView allTimeTransactionsRowView in dvAllTimeTransactions)
                            {
                                int timeId = Convert.ToInt32(allTimeTransactionsRowView.Row["TimeId"].ToString());

                                DateTime timeDate = (DateTime)allTimeTransactionsRowView.Row["TimeDate"];
                                string timeType = (string)allTimeTransactionsRowView.Row["TimeTypeDescription"].ToString();
                                string time = this.ConvertUnits((int)allTimeTransactionsRowView.Row["TimeElapsed"], ApplicationSettings.Instance.TimeUnits);
                                timeElapsed = timeElapsed + (int)allTimeTransactionsRowView.Row["TimeElapsed"];
                                int totalTimeElapsed = timeElapsed;
                                string feeEarnerReference = (string)allTimeTransactionsRowView.Row["feeRef"].ToString();
                                cost = (decimal)allTimeTransactionsRowView.Row["TimeCost"];
                                charge = (decimal)allTimeTransactionsRowView.Row["TimeCharge"];
                                costBalance = costBalance + cost;
                                chargeBalance = chargeBalance + charge;
                                cost = Decimal.Round(cost, 2);
                                charge = Decimal.Round(charge, 2);
                                chargeBalance = Decimal.Round(chargeBalance, 2);
                                costBalance = Decimal.Round(costBalance, 2);

                                if ((Convert.ToDecimal(allTimeTransactionsRowView.Row["ClaimedChargeAmount"]) == Convert.ToDecimal(allTimeTransactionsRowView.Row["TimeCharge"])) &&
                                    (Convert.ToDecimal(allTimeTransactionsRowView.Row["ClaimedCostAmount"]) == Convert.ToDecimal(allTimeTransactionsRowView.Row["TimeCost"])) &&
                                    (Convert.ToInt32(allTimeTransactionsRowView.Row["ClaimedCount"]) > 0))
                                {
                                    // Adds time transaction details to dataset after calculations
                                    dsAllTimeTransactions.Tables["AllTimeTransactions"].Rows.Add(timeId,
                                                                                                 timeDate.ToShortDateString(),
                                                                                                 timeType,
                                                                                                 feeEarnerReference,
                                                                                                 time,
                                                                                                 totalTimeElapsed,
                                                                                                 cost.ToString("0.00"),
                                                                                                 costBalance.ToString("0.00"),
                                                                                                 charge.ToString("0.00"),
                                                                                                 chargeBalance.ToString("0.00"));

                                }
                                else if ((int)allTimeTransactionsRowView.Row["WoffCount"] > 0)
                                {
                                    // Time is wrtten off!
                                    // Adds time transaction details to dataset after calculations
                                    dsAllTimeTransactions.Tables["AllTimeTransactions"].Rows.Add(timeId,
                                                                                                 timeDate.ToShortDateString(),
                                                                                                 timeType,
                                                                                                 feeEarnerReference,
                                                                                                 time,
                                                                                                 totalTimeElapsed,
                                                                                                 cost.ToString("0.00"),
                                                                                                 costBalance.ToString("0.00"),
                                                                                                 charge.ToString("0.00"),
                                                                                                 chargeBalance.ToString("0.00"));

                                }
                                else if ((Convert.ToDecimal(allTimeTransactionsRowView.Row["BillTimeChargeAllocAmount"]) >= Convert.ToDecimal(allTimeTransactionsRowView.Row["TimeCharge"])) &&
                                         (Convert.ToDecimal(allTimeTransactionsRowView.Row["BillTimeCostAllocAmount"]) >= Convert.ToDecimal(allTimeTransactionsRowView.Row["TimeCost"])) &&
                                         (Convert.ToInt32(allTimeTransactionsRowView.Row["BilledCount"]) > 0))
                                {
                                    //there has been some allocations done so the time must be billed
                                    dsAllTimeTransactions.Tables["AllTimeTransactions"].Rows.Add(timeId,
                                                                                                 timeDate.ToShortDateString(),
                                                                                                 timeType,
                                                                                                 feeEarnerReference,
                                                                                                 time,
                                                                                                 totalTimeElapsed,
                                                                                                 cost.ToString("0.00"),
                                                                                                 costBalance.ToString("0.00"),
                                                                                                 charge.ToString("0.00"),
                                                                                                 chargeBalance.ToString("0.00"));
                                }
                                else
                                {
                                    // no time allocations doen so time must be unbilled
                                    //create listview items
                                    //there has been some allocations done so the time must be billed
                                    dsAllTimeTransactions.Tables["AllTimeTransactions"].Rows.Add(timeId,
                                                                                                 timeDate.ToShortDateString(),
                                                                                                 timeType,
                                                                                                 feeEarnerReference,
                                                                                                 time,
                                                                                                 totalTimeElapsed,
                                                                                                 cost.ToString("0.00"),
                                                                                                 costBalance.ToString("0.00"),
                                                                                                 charge.ToString("0.00"),
                                                                                                 chargeBalance.ToString("0.00"));
                                }
                            }

                            if (dsAllTimeTransactions.Tables["AllTimeTransactions"].Rows.Count > 0)
                            {
                                int rowCount = dsAllTimeTransactions.Tables["AllTimeTransactions"].Rows.Count;
                                timeElapsed = (int)dsAllTimeTransactions.Tables["AllTimeTransactions"].Rows[rowCount - 1]["TotalTimeElapsed"];
                                chargeBalance = (decimal)dsAllTimeTransactions.Tables["AllTimeTransactions"].Rows[rowCount - 1]["ChargeBalance"];
                                costBalance = (decimal)dsAllTimeTransactions.Tables["AllTimeTransactions"].Rows[rowCount - 1]["CostBalance"];

                                if (timeFilter.Trim() == "All")
                                {
                                    totalTimeTransactions.TotalCharge = chargeBalance;
                                    totalTimeTransactions.TotalCost = costBalance;
                                    totalTimeTransactions.TotalTimeElapsed = this.ConvertUnits(timeElapsed, ApplicationSettings.Instance.TimeUnits);
                                }

                                // These properties need to be set for time filter for "All" and rest of the time filters
                                totalTimeTransactions.FilterTime = this.ConvertUnits(timeElapsed, ApplicationSettings.Instance.TimeUnits);
                                totalTimeTransactions.FilterCost = costBalance;
                                totalTimeTransactions.FilterCharge = chargeBalance;

                                returnValue.TotalTimeTransactions = totalTimeTransactions;
                            }
                        }

                        e.DataSet = dsAllTimeTransactions;
                    };

                    // Create the data list
                    returnValue.TimeTransactions = dataListCreator.Create(logonId,
                        // Give the query a name so it can be cached
                        "GetTimeLedger",
                        // Tell it the query criteria used so if the cache is accessed
                        // again it knows if it is the same query
                        projectId.ToString(),
                        collectionRequest,
                        // Import mappings to map the dataset row fields to the data
                        // list entity properties
                        new ImportMapping[] {
                                            new ImportMapping("TimeId", "TimeId"),
                                            new ImportMapping("TimeDate", "TimeDate"),
                                            new ImportMapping("TimeType", "TimeType"),
                                            new ImportMapping("FeeEarnerReference", "FeeEarnerReference"),
                                            new ImportMapping("Time","Time"),
                                            new ImportMapping("Cost","Cost"),
                                            new ImportMapping("CostBalance","CostBalance"),
                                            new ImportMapping("Charge","Charge"),
                                            new ImportMapping("ChargeBalance","ChargeBalance"),
                                            new ImportMapping("TotalTimeElapsed", "TotalTimeElapsed")
                            }
                        );
                }
                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>
        /// Search departments based on the organisation ID
        /// </summary>
        /// <param name="logonId">The logon id</param>
        /// <param name="collectionRequest">Collection request value</param>
        /// <param name="criteria">Department search criteria</param>
        /// <returns>Collection of department search item</returns>
        public DepartmentSearchReturnValue DepartmentSearch(Guid logonId, CollectionRequest collectionRequest,
            DepartmentSearchCriteria criteria)
        {
            DepartmentSearchReturnValue returnValue = new DepartmentSearchReturnValue();

            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:
                        case DataConstants.UserType.Client:
                        case DataConstants.UserType.ThirdParty:
                            // Can do everything
                            break;
                        default:
                            throw new Exception("Access denied");
                    }

                    // Create a data list creator for a list of matters
                    DataListCreator<DepartmentSearchItem> dataListCreator = new DataListCreator<DepartmentSearchItem>();

                    // Declare an inline event (annonymous delegate) to read the
                    // dataset if it is required
                    dataListCreator.ReadDataSet += delegate(object Sender, ReadDataSetEventArgs e)
                    {
                        if (criteria.AllDepartment)
                        {
                            // Create the dataset for department search to get all departments
                            e.DataSet = SrvDepartmentLookup.GetDepartments();
                        }
                        else
                        {
                            // Create the dataset
                            e.DataSet = SrvDepartmentLookup.GetDepartments(criteria.OrganisationId, criteria.IncludeArchived);
                        }

                        DataTable dt = Functions.SortDataTable(e.DataSet.Tables[0], "deptName");
                        e.DataSet.Tables.Remove(e.DataSet.Tables[0]);
                        e.DataSet.Tables.Add(dt);
                    };

                    // Create the data list
                    returnValue.Departments = dataListCreator.Create(logonId,
                        // Give the query a name so it can be cached
                        "DepartmentSearch",
                        // Tell it the query criteria used so if the cache is accessed
                        // again it knows if it is the same query
                        criteria.ToString(),
                        collectionRequest,
                        // Import mappings to map the dataset row fields to the data
                        // list entity properties
                        new ImportMapping[] {
                            new ImportMapping("Id", "deptID"),
                            new ImportMapping("No", "deptNo"),
                            new ImportMapping("Name", "deptName"),
                            new ImportMapping("IsArchived", "deptArchived")
                            }
                        );
                }
                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 TimeTransactionReturnValue GetTimeTransaction(Guid logonId, Guid projectId)
        {
            TimeTransactionReturnValue returnValue = new TimeTransactionReturnValue();

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

                    // Create a data list creator for a list
                    DataListCreator<TimeTransaction> dataListCreator = new DataListCreator<TimeTransaction>();

                    Collection<SrvTimeTransaction> transactions =
                            SrvDraftBillCommon.GetTimeTransaction(projectId);

                    returnValue.Transactions = dataListCreator.Create<SrvTimeTransaction>(transactions,
                        new ImportMapping[] {
                            new ImportMapping("Date", "TimeDate"),
                            new ImportMapping("FeeEarner", "FeeReference"),
                            new ImportMapping("Description", "TimeTypeDescription"),
                            new ImportMapping("Charge", "TimeCharge"),
                            new ImportMapping("Cost", "TimeCost"),
                            new ImportMapping("TimeId", "TimeId"),
                            new ImportMapping("Time", "TimeElapsed")
                            });
                }
                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>
        /// Get details about multiple matters.
        /// NOTE: the MatterSearchItem's returned only contain the ID, Reference and Description.  The other search fields
        /// are not returned but these could be added later.
        /// </summary>
        /// <param name="logonId">Logon id obtained when logging on to the logon service.</param>
        /// <param name="ProjectIds">Array of project ids</param>
        /// <returns></returns>
        public MatterSearchReturnValue GetMultipleMatterDetails(Guid logonId, Guid[] ProjectIds)
        {
            MatterSearchReturnValue returnValue = new MatterSearchReturnValue();

            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:
                            // This is inefficient but this most likely will not be used and if it is they won't be looking for many records
                            foreach (Guid ProjectId in ProjectIds)
                            {
                                if (!SrvMatterCommon.WebAllowedToAccessMatter(ProjectId))
                                    throw new Exception("Access denied");
                            }

                            break;
                        default:
                            throw new Exception("Access denied");
                    }

                    DataListCreator<MatterSearchItem> dataListCreator = new DataListCreator<MatterSearchItem>();

                    returnValue.Matters = new DataList<MatterSearchItem>();

                    returnValue.Matters.FirstRowNumber = 0;

                    foreach (IRIS.Law.PmsCommonData.DsMatter.MatterRow Row in SrvMatterCommon.GetMultipleMatters(ProjectIds).Tables[0].Rows)
                    {
                        MatterSearchItem Item = new MatterSearchItem();

                        Item.Id = Row.ProjectId;
                        Item.Reference = Row.matRef;
                        Item.Description = Row.matDescription;

                        returnValue.Matters.TotalRowCount++;
                        returnValue.Matters.Rows.Add(Item);
                    }
                }
                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>
        /// Gets unauthorised office cheque requests
        /// </summary>Function.RestrictRekoopIntegrationUser(UserInformation.Instance.DbUid)
        /// <param name="logonId">Logon id obtained when logging on to the logon service</param>
        /// <param name="collectionRequest">List of unauthorised client cheque requests</param>
        /// <param name="searchCriteria">IsAuthorised and IsPosted flags should be false to get list of 
        /// unauthorised office cheque requests</param>
        /// <returns>Returns list of unauthorised office cheque requests</returns>
        public ChequeAuthorisationReturnValue GetUnauthorisedOfficeChequeRequests(Guid logonId, CollectionRequest collectionRequest, ChequeAuthorisationSearchCriteria searchCriteria)
        {
            ChequeAuthorisationReturnValue returnValue = new ChequeAuthorisationReturnValue();

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

                    // Create a data list creator for a list of bills
                    DataListCreator<ChequeAuthorisationSearchItem> dataListCreator = new DataListCreator<ChequeAuthorisationSearchItem>();

                    // Declare an inline event (annonymous delegate) to read the
                    // dataset if it is required
                    dataListCreator.ReadDataSet += delegate(object Sender, ReadDataSetEventArgs e)
                    {
                        DsOfficeChequeRequestsDetails dsOfficeChequeRequestsDetails = SrvOfficeChequeRequestLookup.GetOfficeChequeRequestDetails(searchCriteria.IsAuthorised, searchCriteria.IsPosted);

                        DataSet dsUnauthorisedOfficeChequeRequests = new DataSet();
                        dsUnauthorisedOfficeChequeRequests.Tables.Add("UnauthorisedOfficeChequeRequests");
                        dsUnauthorisedOfficeChequeRequests.Tables["UnauthorisedOfficeChequeRequests"].Columns.Add("OfficeChequeRequestId", typeof(int));
                        dsUnauthorisedOfficeChequeRequests.Tables["UnauthorisedOfficeChequeRequests"].Columns.Add("ProjectId", typeof(Guid));
                        dsUnauthorisedOfficeChequeRequests.Tables["UnauthorisedOfficeChequeRequests"].Columns.Add("OfficeChequeRequestDate", typeof(DateTime));
                        dsUnauthorisedOfficeChequeRequests.Tables["UnauthorisedOfficeChequeRequests"].Columns.Add("UserName", typeof(string));
                        dsUnauthorisedOfficeChequeRequests.Tables["UnauthorisedOfficeChequeRequests"].Columns.Add("MatterReference", typeof(string));
                        dsUnauthorisedOfficeChequeRequests.Tables["UnauthorisedOfficeChequeRequests"].Columns.Add("FeeEarnerReference", typeof(string));
                        dsUnauthorisedOfficeChequeRequests.Tables["UnauthorisedOfficeChequeRequests"].Columns.Add("OfficeChequeRequestDescription", typeof(string));
                        dsUnauthorisedOfficeChequeRequests.Tables["UnauthorisedOfficeChequeRequests"].Columns.Add("OfficeChequeRequestAmount", typeof(decimal));
                        dsUnauthorisedOfficeChequeRequests.Tables["UnauthorisedOfficeChequeRequests"].Columns.Add("VATRateReferernce", typeof(string));
                        dsUnauthorisedOfficeChequeRequests.Tables["UnauthorisedOfficeChequeRequests"].Columns.Add("VATRateAmount", typeof(decimal));
                        dsUnauthorisedOfficeChequeRequests.Tables["UnauthorisedOfficeChequeRequests"].Columns.Add("OfficeChequeRequestBank", typeof(string));
                        dsUnauthorisedOfficeChequeRequests.Tables["UnauthorisedOfficeChequeRequests"].Columns.Add("IsOfficeChequeRequestAnticipated", typeof(bool));

                        foreach (DataRow unauthorisedClientChequeRequestRow in dsOfficeChequeRequestsDetails.uvw_OfficeChequeRequestsDetails.Rows)
                        {
                            int officeChequeRequestId = Convert.ToInt32(unauthorisedClientChequeRequestRow["OfficeChequeRequestsId"].ToString());
                            DateTime officeChequeRequestDate = (DateTime)unauthorisedClientChequeRequestRow["OfficeChequeRequestsDate"];
                            string userName = (string)unauthorisedClientChequeRequestRow["userName"];
                            Guid projectId = (Guid)unauthorisedClientChequeRequestRow["ProjectId"];
                            string matterReference = (string)unauthorisedClientChequeRequestRow["matRef"];
                            string feeEarnerReference = (string)unauthorisedClientChequeRequestRow["feeRef"];
                            string officeChequeRequestDescription = (string)unauthorisedClientChequeRequestRow["OfficeChequeRequestsDesc"];
                            decimal officeChequeRequestAmount = (decimal)unauthorisedClientChequeRequestRow["OfficeChequeRequestsAmount"];
                            bool isOfficeChequeRequestAnticipated = (bool)unauthorisedClientChequeRequestRow["OfficeChequeRequestIsAnticipated"];
                            string vatRateReference = (string)unauthorisedClientChequeRequestRow["VATRateRef"];
                            decimal vatRateAmount = (decimal)unauthorisedClientChequeRequestRow["OfficeChequeRequestsVATAmount"];

                            officeChequeRequestAmount = Decimal.Round(officeChequeRequestAmount, 2);
                            vatRateAmount = Decimal.Round(vatRateAmount, 2);

                            // Gets the bank name by bank id
                            int bankId = Convert.ToInt32(unauthorisedClientChequeRequestRow["BankId"]);
                            string clientChequeRequestBankName = this.GetBankByBankId(bankId);

                            // Adds unauthorised office cheque requests after manipulating dataset.
                            dsUnauthorisedOfficeChequeRequests.Tables["UnauthorisedOfficeChequeRequests"].Rows.Add(officeChequeRequestId,
                                                                                                                    projectId,
                                                                                                                    officeChequeRequestDate,
                                                                                                                    userName,
                                                                                                                    matterReference,
                                                                                                                    feeEarnerReference,
                                                                                                                    officeChequeRequestDescription,
                                                                                                                    officeChequeRequestAmount.ToString(),
                                                                                                                    vatRateReference,
                                                                                                                    vatRateAmount.ToString(),
                                                                                                                    clientChequeRequestBankName,
                                                                                                                    isOfficeChequeRequestAnticipated);
                        }

                        e.DataSet = dsUnauthorisedOfficeChequeRequests;
                    };

                    // Create the data list
                    returnValue.ChequeRequests = dataListCreator.Create(logonId,
                        // Give the query a name so it can be cached
                        "GetUnauthorisedOfficeChequeRequests",
                        // Tell it the query criteria used so if the cache is accessed
                        // again it knows if it is the same query
                        searchCriteria.ToString(),
                        collectionRequest,
                        // Import mappings to map the dataset row fields to the data
                        // list entity properties
                        new ImportMapping[] {
                                            new ImportMapping("UserName", "UserName"),
                                            new ImportMapping("ProjectId", "ProjectId"),
                                            new ImportMapping("MatterReference","MatterReference"),
                                            new ImportMapping("FeeEarnerReference","FeeEarnerReference"),
                                            new ImportMapping("ChequeRequestId", "OfficeChequeRequestId"),
                                            new ImportMapping("BankName","OfficeChequeRequestBank"),
                                            new ImportMapping("ChequeRequestDate", "OfficeChequeRequestDate"),
                                            new ImportMapping("ChequeRequestAmount","OfficeChequeRequestAmount"),
                                            new ImportMapping("VATRate", "VATRateReferernce"),
                                            new ImportMapping("VATAmount","VATRateAmount"),
                                            new ImportMapping("ChequeRequestDescription","OfficeChequeRequestDescription"),
                                            new ImportMapping("IsChequeRequestAnticipated","IsOfficeChequeRequestAnticipated")
                            }
                        );
                }
                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>
        /// Gets the associations for the matter.
        /// </summary>
        /// <param name="logonId">Logon id obtained when logging on to the logon service.</param>
        /// <param name="collectionRequest">The collection request.</param>
        /// <param name="criteria">The criteria.</param>
        /// <returns></returns>
        public MatterAssociationReturnValue MatterAssociationSearch(Guid logonId, CollectionRequest collectionRequest,
                                                                    MatterAssociationSearchCriteria criteria)
        {
            MatterAssociationReturnValue returnValue = new MatterAssociationReturnValue();

            try
            {
                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");
                    }

                    // Create a data list creator for a list of associations
                    DataListCreator<MatterAssociationSearchItem> dataListCreator = new DataListCreator<MatterAssociationSearchItem>();

                    // Declare an inline event (annonymous delegate) to read the
                    // dataset if it is required
                    dataListCreator.ReadDataSet += delegate(object sender, ReadDataSetEventArgs e)
                    {
                        DataSet dataSet = SrvAssociationLookup.GetMatterAssociations(criteria.ProjectId, criteria.ApplicationId);
                        // Perform Sorting on Role
                        DataView dvContacts = new DataView(dataSet.Tables[0]);
                        dvContacts.Sort = "AssociationRoleDescription asc";

                        DataSet dsSorted = new DataSet();
                        dsSorted.Tables.Add(dvContacts.ToTable());
                        e.DataSet = dsSorted;

                        e.DataSet.Tables[0].Columns.Add("Email");
                        e.DataSet.Tables[0].Columns.Add("WorkTel");
                    };

                    // Create the data list
                    DataList<MatterAssociationSearchItem> matterAssociations = dataListCreator.Create(logonId,
                        // Give the query a name so it can be cached
                        "MatterAssociationSearch",
                        // Tell it the query criteria used so if the cache is accessed
                        // again it knows if it is the same query
                        criteria.ToString(),
                        collectionRequest,
                        // Import mappings to map the dataset row fields to the data
                        // list entity properties
                        new ImportMapping[] {
                            new ImportMapping("Role", "AssociationRoleDescription"),
                            new ImportMapping("Title", "PersonTitle"),
                            new ImportMapping("Name", "PersonName"),
                            new ImportMapping("Surname", "PersonSurname"),
                            new ImportMapping("Description", "ProjectMapDescription"),
                            new ImportMapping("MemberId", "MemberId"),
                            new ImportMapping("OrgId", "OrgId")
                            }
                        );

                    DataSet dsMatterAssociations;

                    matterAssociations.Rows.ForEach(delegate(MatterAssociationSearchItem item)
                    {
                        if (item.MemberId == DataConstants.DummyGuid)
                        {
                            dsMatterAssociations = SrvAddressLookup.GetOrganisationAddresses(item.OrgId);
                        }
                        else
                        {
                            dsMatterAssociations = SrvAddressLookup.GetMemberAddresses(item.MemberId);
                        }
                        SrvAddress srvAddress;
                        int intCtr;

                        foreach (DataRow dr in dsMatterAssociations.Tables[0].Rows)
                        {

                            srvAddress = new SrvAddress();
                            if (item.MemberId == DataConstants.DummyGuid)
                            {
                                srvAddress.OrganisationId = item.OrgId;
                            }
                            else
                            {
                                srvAddress.MemberId = item.MemberId;
                            }
                            srvAddress.Load(int.Parse(dr["addressId"].ToString()));

                            for (intCtr = 0; intCtr < srvAddress.AdditionalInfoElements.Count; intCtr++)
                            {
                                AdditionalAddressElement additionalAddressElement = new AdditionalAddressElement();

                                if (srvAddress.AdditionalInfoElements[intCtr].AddressElTypeId == 8)
                                {
                                    item.WorkEmail = srvAddress.AdditionalInfoElements[intCtr].AddressElementText;
                                }

                                if (srvAddress.AdditionalInfoElements[intCtr].AddressElTypeId == 2)
                                {
                                    item.WorkTelephone = srvAddress.AdditionalInfoElements[intCtr].AddressElementText;
                                }

                            }
                        }
                    });

                    returnValue.Associations = matterAssociations;
                }
                finally
                {
                    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>
        /// Gets unposted draft bills 
        /// </summary>
        /// <param name="logonId">Logon id obtained when logging on to the logon service</param>
        /// <param name="collectionRequest">List of unposted draft bills</param>
        /// <returns>Returns list of unposted draft bills</returns>
        public DraftBillSearchReturnValue GetUnpostedDraftBills(Guid logonId, CollectionRequest collectionRequest)
        {
            DraftBillSearchReturnValue returnValue = new DraftBillSearchReturnValue();

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

                    // Create a data list creator for a list of bills
                    DataListCreator<DraftBillSearchItem> dataListCreator = new DataListCreator<DraftBillSearchItem>();

                    // Declare an inline event (annonymous delegate) to read the
                    // dataset if it is required
                    dataListCreator.ReadDataSet += delegate(object Sender, ReadDataSetEventArgs e)
                    {
                        DsDraftBills dsDraftBills = SrvDraftBillLookup.GetUnPostedDraftBills();

                        DataSet dsUnpostedDraftBills = new DataSet();
                        dsUnpostedDraftBills.Tables.Add("UnpostedDraftBills");
                        dsUnpostedDraftBills.Tables["UnpostedDraftBills"].Columns.Add("DraftBillId", typeof(int));
                        dsUnpostedDraftBills.Tables["UnpostedDraftBills"].Columns.Add("DraftBillDate", typeof(DateTime));
                        dsUnpostedDraftBills.Tables["UnpostedDraftBills"].Columns.Add("UserName", typeof(string));
                        dsUnpostedDraftBills.Tables["UnpostedDraftBills"].Columns.Add("MatterReference", typeof(string));
                        dsUnpostedDraftBills.Tables["UnpostedDraftBills"].Columns.Add("DraftBillDescription", typeof(string));

                        DataView dvUnpostedDraftBills = new DataView(dsDraftBills.DraftBills);
                        if (dvUnpostedDraftBills.Count != 0)
                        {
                            string columnOrderByDraftBillsDate = Convert.ToString(dsDraftBills.DraftBills.Columns["DraftBillsDate"]);
                            dvUnpostedDraftBills.Sort = columnOrderByDraftBillsDate + " " + "asc";

                            foreach (DataRowView unpostedDraftBillsRowView in dvUnpostedDraftBills)
                            {
                                int draftBillId = (int)unpostedDraftBillsRowView.Row["DraftBillsId"];

                                Guid projectId = (Guid)unpostedDraftBillsRowView.Row["ProjectId"];
                                Guid userMemberId = (Guid)unpostedDraftBillsRowView.Row["UserMemberId"];

                                // Gets matter reference by project id
                                string matterReference = SrvMatterCommon.GetMatterReference(projectId);

                                // Inserts "-" in between matter reference
                                matterReference = matterReference.Insert(6, "-");

                                // Gets user name by member id
                                DsSystemUsers dsSystemUsers = SrvUserLookup.GetUser(userMemberId.ToString());

                                string userName = string.Empty;
                                if (dsSystemUsers.uvw_SystemUsers.Count > 0)
                                {
                                    userName = dsSystemUsers.uvw_SystemUsers[0].name;
                                }
                                else
                                {
                                    DsPersonDealing dsPersonDealing = SrvMatterLookup.GetPersonDealingLookup();
                                    for (int index = 0; index < dsPersonDealing.uvw_PersonDealingLookup.Count; index++)
                                    {
                                        if (dsPersonDealing.uvw_PersonDealingLookup[index].MemberID == userMemberId)
                                        {
                                            userName = dsPersonDealing.uvw_PersonDealingLookup[index].name;
                                        }
                                    }
                                }

                                DateTime draftBillDate = (DateTime)unpostedDraftBillsRowView.Row["DraftBillsDate"];
                                string draftBillDescription = (string)unpostedDraftBillsRowView.Row["PostingDescDetails"];

                                // Create dataset for sorted unposted draft bills
                                dsUnpostedDraftBills.Tables["UnpostedDraftBills"].Rows.Add(draftBillId,
                                                                                            draftBillDate.ToShortDateString(),
                                                                                            userName,
                                                                                            matterReference,
                                                                                            draftBillDescription);

                            }
                        }

                        e.DataSet = dsUnpostedDraftBills;
                    };

                    // Create the data list
                    returnValue.UnpostedDraftBills = dataListCreator.Create(logonId,
                        // Give the query a name so it can be cached
                        "GetUnpostedDraftBills",
                        // Tell it the query criteria used so if the cache is accessed
                        // again it knows if it is the same query
                        string.Empty,
                        collectionRequest,
                        // Import mappings to map the dataset row fields to the data
                        // list entity properties
                        new ImportMapping[] {
                                            new ImportMapping("DraftBillId", "DraftBillId"),
                                            new ImportMapping("DraftBillDate", "DraftBillDate"),
                                            new ImportMapping("UserName", "UserName"),
                                            new ImportMapping("MatterReference", "MatterReference"),
                                            new ImportMapping("DraftBillDescription","DraftBillDescription")
                            }
                        );
                }
                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>
        /// Get details about multiple persons.
        /// </summary>
        /// <param name="logonId">Logon id obtained when logging on to the logon service.</param>
        /// <param name="MemberIds">Array of member ids</param>
        /// <returns></returns>
        public PersonSearchReturnValue GetMultiplePersonDetails(Guid logonId, Guid[] MemberIds)
        {
            PersonSearchReturnValue returnValue = new PersonSearchReturnValue();

            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:
                            // Can only access themself
                            if (MemberIds.Length != 1)
                                throw new Exception("Access denied");

                            if (!ApplicationSettings.Instance.IsUser(MemberIds[0], DataConstants.DummyGuid))
                                throw new Exception("Access denied");
                            break;
                        case DataConstants.UserType.ThirdParty:
                            // Can only access themself
                            if (MemberIds.Length != 1)
                                throw new Exception("Access denied");

                            if (!ApplicationSettings.Instance.IsUser(MemberIds[0], DataConstants.DummyGuid))
                                throw new Exception("Access denied");
                            break;
                        default:
                            throw new Exception("Access denied");
                    }

                    DataListCreator<PersonSearchItem> dataListCreator = new DataListCreator<PersonSearchItem>();

                    returnValue.Persons = new DataList<PersonSearchItem>();

                    returnValue.Persons.FirstRowNumber = 0;

                    foreach (IRIS.Law.PmsCommonData.DsPersons.PersonsRow Row in
                        SrvPersonLookup.GetMultiplePersons(MemberIds).Tables[0].Rows)
                    {
                        PersonSearchItem Item = new PersonSearchItem();

                        Item.MemberId = Row.MemberID;
                        Item.Title = Row.PersonTitle;
                        Item.Forename = Row.PersonName;
                        Item.Surname = Row.PersonSurname;

                        returnValue.Persons.TotalRowCount++;
                        returnValue.Persons.Rows.Add(Item);
                    }
                }
                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>
        /// Loads write off time transactions by project id
        /// </summary>
        /// <param name="logonId">Logon id obtained when logging on to the logon service</param>
        /// <param name="collectionRequest">Loads listof write off time transactions</param>
        /// <param name="projectId">To load write off transactions.</param>
        /// <returns>Loads write off time transactions</returns>
        public TimeLedgerSearchReturnValue GetWriteOffTimeTransactions(Guid logonId, CollectionRequest collectionRequest, Guid projectId)
        {
            TimeLedgerSearchReturnValue returnValue = new TimeLedgerSearchReturnValue();

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

                    // Create a data list creator for a list of bills
                    DataListCreator<TimeLedgerSearchItem> dataListCreator = new DataListCreator<TimeLedgerSearchItem>();

                    // Declare an inline event (annonymous delegate) to read the
                    // dataset if it is required
                    dataListCreator.ReadDataSet += delegate(object Sender, ReadDataSetEventArgs e)
                    {
                        DsTimeWoffGroupedTransactions dsTimeWoffGroupedTransactions = SrvTimeWoffLookup.GetTimeWoffGroupedTransactions(projectId);

                        DataSet dsTimeWriteOffTransactions = new DataSet();
                        dsTimeWriteOffTransactions.Tables.Add("TimeWriteOffTransactions");
                        dsTimeWriteOffTransactions.Tables["TimeWriteOffTransactions"].Columns.Add("Postingid", typeof(int));
                        dsTimeWriteOffTransactions.Tables["TimeWriteOffTransactions"].Columns.Add("PostingDate", typeof(DateTime));
                        dsTimeWriteOffTransactions.Tables["TimeWriteOffTransactions"].Columns.Add("PostingReference", typeof(string));
                        dsTimeWriteOffTransactions.Tables["TimeWriteOffTransactions"].Columns.Add("PostingDescription", typeof(string));
                        dsTimeWriteOffTransactions.Tables["TimeWriteOffTransactions"].Columns.Add("Time", typeof(string));
                        dsTimeWriteOffTransactions.Tables["TimeWriteOffTransactions"].Columns.Add("Charge", typeof(decimal));
                        dsTimeWriteOffTransactions.Tables["TimeWriteOffTransactions"].Columns.Add("Cost", typeof(decimal));
                        dsTimeWriteOffTransactions.Tables["TimeWriteOffTransactions"].Columns.Add("CostBalance", typeof(decimal));

                        DataView dvTimeWriteOffTransactions = new DataView(dsTimeWoffGroupedTransactions.uvw_TimeWoffGroupedTransactions);
                        if (dvTimeWriteOffTransactions.Count != 0)
                        {
                            string columnOrderByPostingDate = Convert.ToString(dsTimeWoffGroupedTransactions.uvw_TimeWoffGroupedTransactions.Columns["PostingDetailsDate"]);
                            dvTimeWriteOffTransactions.Sort = columnOrderByPostingDate + " " + "asc";

                            decimal chargeAmount = decimal.Zero;
                            decimal costAmount = decimal.Zero;

                            foreach (DataRowView timeWriteOffTransactionsRowView in dvTimeWriteOffTransactions)
                            {
                                if ((string)timeWriteOffTransactionsRowView.Row["PostingTypesRef"].ToString().Trim() == "TWO")
                                {
                                    int postingId = Convert.ToInt32(timeWriteOffTransactionsRowView.Row["PostingId"]);

                                    DateTime postingDate = (DateTime)timeWriteOffTransactionsRowView.Row["PostingDetailsDate"];
                                    string postingReference = (string)timeWriteOffTransactionsRowView.Row["PostingDetailsRef"].ToString();
                                    string postingDescription = (string)timeWriteOffTransactionsRowView.Row["PostingDetailsDescription"].ToString();
                                    chargeAmount = (decimal)timeWriteOffTransactionsRowView.Row["TimeWoffMasterChargeAmount"];
                                    costAmount = (decimal)timeWriteOffTransactionsRowView.Row["TimeWoffMasterCostAmount"];
                                    string time = this.ConvertUnits((int)timeWriteOffTransactionsRowView.Row["TimeWoffMintues"], ApplicationSettings.Instance.TimeUnits);

                                    //create datatable of time write off transactions
                                    dsTimeWriteOffTransactions.Tables["TimeWriteOffTransactions"].Rows.Add(postingId,
                                                                                                            postingDate.ToShortDateString(),
                                                                                                            postingReference,
                                                                                                            postingDescription,
                                                                                                            time,
                                                                                                            chargeAmount.ToString("0.00"),
                                                                                                            costAmount.ToString("0.00"));
                                }
                            }
                        }

                        e.DataSet = dsTimeWriteOffTransactions;
                    };

                    // Create the data list
                    returnValue.TimeTransactions = dataListCreator.Create(logonId,
                        // Give the query a name so it can be cached
                        "GetWriteOffTimeTransactions",
                        // Tell it the query criteria used so if the cache is accessed
                        // again it knows if it is the same query
                        projectId.ToString(),
                        collectionRequest,
                        // Import mappings to map the dataset row fields to the data
                        // list entity properties
                        new ImportMapping[] {
                                            new ImportMapping("PostingId", "PostingId"),
                                            new ImportMapping("PostingDate", "PostingDate"),
                                            new ImportMapping("PostingReference", "PostingReference"),
                                            new ImportMapping("Time", "Time"),
                                            new ImportMapping("Charge","Charge"),
                                            new ImportMapping("Cost","Cost"),
                                            new ImportMapping("PostingDescription","PostingDescription")
                            }
                        );
                }
                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>
        /// Search for association roles
        /// </summary>
        /// <param name="logonId">Logon id obtained when logging on to the logon service.</param>
        /// <param name="collectionRequest">Information about the collection being requested.</param>
        /// <param name="criteria">AssociationRole search criteria.</param>
        /// <returns></returns>
        public AssociationRoleSearchReturnValue AssociationRoleForRoleIdSearch(Guid logonId,
                    CollectionRequest collectionRequest, AssociationRoleSearchCriteria criteria)
        {
            AssociationRoleSearchReturnValue returnValue = new AssociationRoleSearchReturnValue();

            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:
                        case DataConstants.UserType.Client:
                        case DataConstants.UserType.ThirdParty:
                            // Can do everything
                            break;
                        default:
                            throw new Exception("Access denied");
                    }

                    // Create a data list creator for a list of association roles
                    DataListCreator<AssociationRoleSearchItem> dataListCreator = new DataListCreator<AssociationRoleSearchItem>();

                    // Declare an inline event (annonymous delegate) to read the dataset
                    dataListCreator.ReadDataSet += delegate(object Sender, ReadDataSetEventArgs e)
                    {
                        e.DataSet = SrvAssociationLookup.GetAssociationRoles(criteria.RoleId);
                    };

                    // Create the data list
                    returnValue.AssociationRole = dataListCreator.Create(logonId,
                        // Give the query a name so it can be cached
                        "AssociationRoleForRoleIdSearch",
                        // Tell it the query criteria used so if the cache is accessed
                        // again it knows if it is the same query
                        criteria.ToString(),
                        collectionRequest,
                        // Import mappings to map the dataset row fields to the data
                        // list entity properties
                        new ImportMapping[] {
                            new ImportMapping("AssociationRoleID", "AssociationRolesID"),
                            new ImportMapping("AssociationRoleDescription", "AssociationRoleDescription"),
                            new ImportMapping("AssociationRoleSearchClient", "AssociationRoleSearchClient"),
                            new ImportMapping("AssociationRoleSearchMatter", "AssociationRoleSearchMatter"),
                            new ImportMapping("AssociationRoleSearchGeneral", "AssociationRoleSearchGen"),
                            new ImportMapping("AssociationRoleSearchService", "AssociationRoleSearchServ"),
                            new ImportMapping("AssociationRoleSearchFeeEarner", "AssociationRoleSearchFeeEarner"),
                            new ImportMapping("AssociationRoleSpecialisedSearch", "AssociationRoleSpecialisedSearch")
                            }
                        );
                }
                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>
        /// Loads write off bills by project id
        /// </summary>
        /// <param name="logonId">Logon id obtained when logging on to the logon service</param>
        /// <param name="projectId">To load write off bills</param>
        /// <returns>Loads write off bills by project id</returns>
        public BillsLedgerReturnValue LoadWriteOffBills(Guid logonId, CollectionRequest collectionRequest, Guid projectId)
        {
            BillsLedgerReturnValue returnValue = new BillsLedgerReturnValue();

            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:
                            // Can view own bills
                            if (!SrvMatterCommon.WebAllowedToAccessMatter(projectId))
                                throw new Exception("Access denied");
                            break;
                        case DataConstants.UserType.ThirdParty:
                            throw new Exception("Access denied");
                        default:
                            throw new Exception("Access denied");
                    }

                    // Create a data list creator for a list of bills
                    DataListCreator<BillsLedgerSearchItem> dataListCreator = new DataListCreator<BillsLedgerSearchItem>();

                    // Declare an inline event (annonymous delegate) to read the
                    // dataset if it is required
                    dataListCreator.ReadDataSet += delegate(object Sender, ReadDataSetEventArgs e)
                    {
                        DsBillWoTransactions dsBillWoTransactions = SrvBillWoLedgerLookup.GetBillWoLedgerTransactions(projectId);

                        DataSet dsWriteOffBills = new DataSet();
                        dsWriteOffBills.Tables.Add("WriteOffBills");
                        dsWriteOffBills.Tables["WriteOffBills"].Columns.Add("PostingId", typeof(int));
                        dsWriteOffBills.Tables["WriteOffBills"].Columns.Add("PostingDate", typeof(DateTime));
                        dsWriteOffBills.Tables["WriteOffBills"].Columns.Add("PostingReference", typeof(string));
                        dsWriteOffBills.Tables["WriteOffBills"].Columns.Add("PostingType", typeof(string));
                        dsWriteOffBills.Tables["WriteOffBills"].Columns.Add("Debit", typeof(decimal));
                        dsWriteOffBills.Tables["WriteOffBills"].Columns.Add("Credit", typeof(decimal));
                        dsWriteOffBills.Tables["WriteOffBills"].Columns.Add("Paid", typeof(decimal));
                        dsWriteOffBills.Tables["WriteOffBills"].Columns.Add("OutStanding", typeof(decimal));
                        dsWriteOffBills.Tables["WriteOffBills"].Columns.Add("Balance", typeof(decimal));

                        DataView dvWriteOffBills = new DataView(dsBillWoTransactions.uvw_BillWoTransactions);
                        if (dvWriteOffBills.Count != 0)
                        {
                            string columnOrderByPostingDate = Convert.ToString(dsBillWoTransactions.uvw_BillWoTransactions.Columns["PostingDetailsDate"]);
                            dvWriteOffBills.Sort = columnOrderByPostingDate + " " + "asc";

                            int factor = 1;
                            string postingBank = string.Empty;
                            string postingType = string.Empty;
                            decimal debit = decimal.Zero;
                            decimal credit = decimal.Zero;
                            decimal balance = decimal.Zero;
                            decimal outStanding = decimal.Zero;
                            decimal paid = decimal.Zero;

                            foreach (DataRowView writeOfBillsRowView in dvWriteOffBills)
                            {
                                int postingId = Convert.ToInt32(writeOfBillsRowView.Row["PostingId"].ToString());
                                DateTime postingDate = (DateTime)writeOfBillsRowView.Row["PostingDetailsDate"];
                                string postingReference = (string)writeOfBillsRowView.Row["PostingDetailsRef"].ToString();
                                postingType = "Write Off";

                                if ((decimal)writeOfBillsRowView.Row["BillWoLedgerWorkingAmount"] < Decimal.Zero)
                                {
                                    // Credit note.
                                    credit = Math.Abs((decimal)writeOfBillsRowView.Row["BillWoLedgerWorkingAmount"]);
                                    debit = decimal.Zero;
                                    factor = -1;
                                }
                                else
                                {
                                    // Bill.
                                    debit = Math.Abs((decimal)writeOfBillsRowView.Row["BillWoLedgerWorkingAmount"]);
                                    credit = decimal.Zero;
                                    factor = 1;
                                }

                                paid = factor * Math.Abs((decimal)writeOfBillsRowView.Row["BillWoAmount"]);
                                outStanding = factor * (debit + credit - Math.Abs(paid));

                                balance = balance + outStanding;
                                outStanding = Decimal.Round(outStanding, 2);
                                debit = Decimal.Round(debit, 2);
                                credit = Decimal.Round(credit, 2);
                                balance = Decimal.Round(balance, 2);

                                // Adds deposit details to dataset after calculations
                                dsWriteOffBills.Tables["WriteOffBills"].Rows.Add(postingId,
                                                                             postingDate,
                                                                             postingReference,
                                                                             postingType,
                                                                             debit.ToString("0.00"),
                                                                             credit.ToString("0.00"),
                                                                             paid.ToString("0.00"),
                                                                             outStanding.ToString("0.00"),
                                                                             balance.ToString("0.00"));
                            }
                        }

                        e.DataSet = dsWriteOffBills;
                    };

                    // Create the data list
                    returnValue.Bills = dataListCreator.Create(logonId,
                        // Give the query a name so it can be cached
                        "LoadWriteOffBills",
                        // Tell it the query criteria used so if the cache is accessed
                        // again it knows if it is the same query
                        projectId.ToString(),
                        collectionRequest,
                        // Import mappings to map the dataset row fields to the data
                        // list entity properties
                        new ImportMapping[] {
                                            new ImportMapping("PostingId", "PostingId"),
                                            new ImportMapping("BillDate", "PostingDate"),
                                            new ImportMapping("BillReference", "PostingReference"),
                                            new ImportMapping("BillType", "PostingType"),
                                            new ImportMapping("Debit","Debit"),
                                            new ImportMapping("Credit","Credit"),
                                            new ImportMapping("Paid","Paid"),
                                            new ImportMapping("OutStanding","OutStanding"),
                                            new ImportMapping("Balance","Balance")
                            }
                        );
                }
                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>
        /// Get a list of ethnicity values that match the search criteria
        /// </summary>
        /// <param name="logonId">Logon id obtained when logging on to the logon service.</param>
        /// <param name="collectionRequest">Information about the collection being requested.</param>
        /// <param name="criteria">Ethnicity search criteria</param>
        /// <returns></returns>
        public EthnicitySearchReturnValue EthnicitySearch(Guid logonId, IRIS.Law.WebServiceInterfaces.CollectionRequest collectionRequest, EthnicitySearchCriteria criteria)
        {
            EthnicitySearchReturnValue returnValue = new EthnicitySearchReturnValue();

            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:
                        case DataConstants.UserType.Client:
                        case DataConstants.UserType.ThirdParty:
                            // Can do everything
                            break;
                        default:
                            throw new Exception("Access denied");
                    }

                    // Create a data list creator for a list of ethnicity values
                    DataListCreator<EthnicitySearchItem> dataListCreator = new DataListCreator<EthnicitySearchItem>();

                    // Declare an inline event (annonymous delegate) to read the dataset
                    dataListCreator.ReadDataSet += delegate(object Sender, ReadDataSetEventArgs e)
                    {
                        e.DataSet = SrvEthnicityLookup.GetEthnicity();

                        DataTable dt = Functions.SortDataTable(e.DataSet.Tables[0], "EthnicDesc");
                        e.DataSet.Tables.Remove(e.DataSet.Tables[0]);
                        e.DataSet.Tables.Add(dt);
                    };

                    // Create the data list
                    returnValue.Ethnicity = dataListCreator.Create(logonId,
                        // Give the query a name so it can be cached
                        "EthnicitySearch",
                        // Tell it the query criteria used so if the cache is accessed
                        // again it knows if it is the same query
                        criteria.ToString(),
                        collectionRequest,
                        // Import mappings to map the dataset row fields to the data
                        // list entity properties
                        new ImportMapping[] {
                            new ImportMapping("Id", "EthnicID"),
                            new ImportMapping("Description", "EthnicDesc"),
                            }
                        );
                }
                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 AnticipatedDisbursementLedgerReturnValue GetAnticipatedDisbursementLedgerVatableTransaction(Guid logonId, Guid projectId)
        {
            AnticipatedDisbursementLedgerReturnValue returnValue = new AnticipatedDisbursementLedgerReturnValue();

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

                    // Create a data list creator for a list
                    DataListCreator<AnticipatedDisbursementLedgerTransaction> dataListCreator = new DataListCreator<AnticipatedDisbursementLedgerTransaction>();

                    Collection<SrvAntiDisbsLedgerTransaction> transactions =
                            SrvDraftBillCommon.GetAntiDisbLedgerVatableTransactions(projectId);

                    returnValue.Transactions = dataListCreator.Create<SrvAntiDisbsLedgerTransaction>(transactions,
                        new ImportMapping[] {
                            new ImportMapping("Date", "PostingDetailsDate"),
                            new ImportMapping("Reference", "PostingDetailsReference"),
                            new ImportMapping("Description", "PostingDetailsDescription"),
                            new ImportMapping("Amount", "Amount"),
                            new ImportMapping("Billed", "Billed"),
                            new ImportMapping("UnBilled", "UnBilled"),
                            new ImportMapping("PostingId", "PostingId"),
                            new ImportMapping("VatRateId", "VatRateId"),
                            new ImportMapping("IsBilled", "IsBilled")
                            });
                }
                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>
        /// Get the address for the specified contact  
        /// </summary>
        /// <param name="logonId"></param>
        /// <param name="collectionRequest"></param>
        /// <param name="criteria"></param>
        /// <returns></returns>
        public AddressSearchReturnValue GetContactAddresses(Guid logonId, CollectionRequest collectionRequest,
                                        AddressSearchCriteria criteria)
        {
            AddressSearchReturnValue returnValue = new AddressSearchReturnValue();
            SrvAddress srvAddress;

            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:
                            if (!ApplicationSettings.Instance.IsUser(criteria.MemberId, criteria.OrganisationId))
                                throw new Exception("Access denied");
                            break;
                        default:
                            throw new Exception("Access denied");
                    }

                    DataListCreator<Address> dataListCreator = new DataListCreator<Address>();

                    // Declare an inline event (annonymous delegate) to read the
                    // dataset if it is required
                    dataListCreator.ReadDataSet += delegate(object Sender, ReadDataSetEventArgs e)
                    {
                        if (criteria.MemberId != DataConstants.DummyGuid)
                        {
                            e.DataSet = SrvAddressLookup.GetMemberAddresses(criteria.MemberId);
                        }
                        else if (criteria.OrganisationId != DataConstants.DummyGuid)
                        {
                            e.DataSet = SrvAddressLookup.GetOrganisationAddresses(criteria.OrganisationId);
                        }
                    };

                    // Create the data list
                    returnValue.Addresses = dataListCreator.Create(logonId,
                        // Give the query a name so it can be cached
                        "ClientAddresses",
                        // Tell it the query criteria used so if the cache is accessed
                        // again it knows if it is the same query
                        criteria.ToString(),
                        collectionRequest,
                        // Import mappings to map the dataset row fields to the data
                        // list entity properties
                        new ImportMapping[] {
                            new ImportMapping("Id", "AddressId"),
                            new ImportMapping("TypeId", "AddressTypeID"),
                            new ImportMapping("Line1", "AddressLine1"),
                            new ImportMapping("Line2", "AddressLine2"),
                            new ImportMapping("Line3", "AddressLine3"),
                            new ImportMapping("Town", "AddressTown"),
                            new ImportMapping("County", "AddressCounty"),
                            new ImportMapping("PostCode", "AddressPostCode"),
                            new ImportMapping("DXTown", "AddressDXTown"),
                            new ImportMapping("DXNumber", "AddressDX"),
                            new ImportMapping("Country", "AddressCountry"),
                            new ImportMapping("IsMailingAddress", "AddressMailingAddress"),
                            new ImportMapping("IsBillingAddress", "AddressBillingAddress"),
                            new ImportMapping("Comment", "AddressComment"),
                            new ImportMapping("OrganisationName", "AddressOrgName"),
                            new ImportMapping("Department", "AddressDept"),
                            new ImportMapping("PostBox", "AddressPoBox"),
                            new ImportMapping("SubBuilding", "AddressSubBldg"),
                            new ImportMapping("StreetNumber", "AddressStreetNo"),
                            new ImportMapping("HouseName", "AddressHouseName"),
                            new ImportMapping("DependantLocality", "AddressDepLocality"),
                            new ImportMapping("LastVerified", "AddressLastVerified"),
                            }
                        );

                    int intCtr;
                    foreach (Address address in returnValue.Addresses.Rows)
                    {
                        srvAddress = new SrvAddress();
                        srvAddress.MemberId = criteria.MemberId;
                        srvAddress.OrganisationId = criteria.OrganisationId;
                        srvAddress.Load(address.Id);
                        address.AdditionalAddressElements = new List<AdditionalAddressElement>();
                        for (intCtr = 0; intCtr < srvAddress.AdditionalInfoElements.Count; intCtr++)
                        {
                            AdditionalAddressElement additionalAddressElement = new AdditionalAddressElement();
                            additionalAddressElement.ElementComment = srvAddress.AdditionalInfoElements[intCtr].AddressElComment;
                            additionalAddressElement.ElementText = srvAddress.AdditionalInfoElements[intCtr].AddressElementText;
                            additionalAddressElement.TypeId = srvAddress.AdditionalInfoElements[intCtr].AddressElTypeId;
                            address.AdditionalAddressElements.Add(additionalAddressElement);
                        }
                    }
                }
                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>
        /// Gets client balance details by project id.
        /// </summary>
        /// <param name="logonId">Logon id obtained when logging on to the logon service</param>
        /// <param name="collectionRequest">Gets collection of client balances by project id</param>
        /// <param name="projectId">Project id required to get client balances details</param>
        /// <returns>Retrieves client balances by project id</returns>
        public BalancesSearchReturnValue GetClientBalancesDetails(Guid logonId, CollectionRequest collectionRequest, Guid projectId)
        {
            BalancesSearchReturnValue returnValue = new BalancesSearchReturnValue();

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

                    // Create a data list creator for a list of deposit made by client
                    DataListCreator<BalancesSearchItem> dataListCreator = new DataListCreator<BalancesSearchItem>();

                    // Declare an inline event (annonymous delegate) to read the
                    // dataset if it is required
                    dataListCreator.ReadDataSet += delegate(object Sender, ReadDataSetEventArgs e)
                    {
                        DsCledgerTransactions dsClientLedgerTransactions = SrvCledgerLookup.GetCledgerTransactions(projectId);

                        DataSet dsClientBalances = new DataSet();
                        dsClientBalances.Tables.Add("ClientBalances");
                        dsClientBalances.Tables["ClientBalances"].Columns.Add("PostingId", typeof(int));
                        dsClientBalances.Tables["ClientBalances"].Columns.Add("PostingDate", typeof(DateTime));
                        dsClientBalances.Tables["ClientBalances"].Columns.Add("PostingReference", typeof(string));
                        dsClientBalances.Tables["ClientBalances"].Columns.Add("PostingType", typeof(string));
                        dsClientBalances.Tables["ClientBalances"].Columns.Add("PostingDescription", typeof(string));
                        dsClientBalances.Tables["ClientBalances"].Columns.Add("PostingBank", typeof(string));
                        dsClientBalances.Tables["ClientBalances"].Columns.Add("PostingBankRef", typeof(string));
                        dsClientBalances.Tables["ClientBalances"].Columns.Add("Debit", typeof(decimal));
                        dsClientBalances.Tables["ClientBalances"].Columns.Add("Credit", typeof(decimal));
                        dsClientBalances.Tables["ClientBalances"].Columns.Add("Balance", typeof(decimal));

                        DataView dvClientBalances = new DataView(dsClientLedgerTransactions.uvw_CledgerTransactions);
                        if (dvClientBalances.Count != 0)
                        {
                            string columnOrderByPostingDate = Convert.ToString(dsClientLedgerTransactions.uvw_CledgerTransactions.Columns["PostingDetailsDate"]);
                            dvClientBalances.Sort = columnOrderByPostingDate + " " + "asc";

                            string postingBank = string.Empty;
                            string postingBankRef = string.Empty;
                            decimal debit = decimal.Zero;
                            decimal credit = decimal.Zero;
                            decimal balance = decimal.Zero;

                            foreach (DataRowView clientBalancesRowView in dvClientBalances)
                            {
                                bool addRecord = true;
                                if ((int)clientBalancesRowView.Row["bankTypeID"] != 1 && (int)clientBalancesRowView.Row["PostingTypeId"] != 3)
                                {
                                    if ((int)clientBalancesRowView.Row["PostingTypeId"] != 3)
                                    {
                                        addRecord = false;
                                    }
                                    if ((int)clientBalancesRowView.Row["PostingTypeId"] == 33)
                                    {
                                        addRecord = true;
                                    }
                                    if ((int)clientBalancesRowView.Row["PostingTypeId"] == 41)
                                    {
                                        addRecord = true;
                                    }
                                    if ((int)clientBalancesRowView.Row["PostingTypeId"] == 69 && (int)clientBalancesRowView.Row["bankTypeID"] == 0)
                                    {
                                        addRecord = true;
                                    }
                                }

                                if (addRecord)
                                {
                                    int postingId = Convert.ToInt32(clientBalancesRowView.Row["PostingId"].ToString().Trim());
                                    DateTime postingDate = (DateTime)clientBalancesRowView.Row["PostingDetailsDate"];
                                    string postingReference = (string)clientBalancesRowView.Row["PostingDetailsRef"].ToString();
                                    string postingType = (string)clientBalancesRowView.Row["PostingTypesRef"].ToString(); ;
                                    string postingDescription = (string)clientBalancesRowView.Row["PostingDetailsDescription"].ToString();

                                    if ((string)clientBalancesRowView.Row["bankRef"].ToString().Trim() == "0" ||
                                        (int)clientBalancesRowView.Row["bankTypeID"] == 3)
                                    {
                                        postingBank = "N/A";
                                        postingBankRef = "N/A";
                                    }
                                    else
                                    {
                                        int bankId = Convert.ToInt32(clientBalancesRowView.Row["bankId"]);
                                        postingBank = this.GetBankByBankId(bankId);
                                        postingBankRef = (string)clientBalancesRowView.Row["bankRef"].ToString();
                                    }
                                    if ((decimal)clientBalancesRowView.Row["CledgerMasterAmount"] < Decimal.Zero)
                                    {
                                        // Negative Posting Amount
                                        debit = 0 - (decimal)clientBalancesRowView.Row["CledgerMasterAmount"];
                                        credit = Decimal.Zero;
                                        balance = balance - debit;
                                    }
                                    else
                                    {
                                        // Positive Posting Amount
                                        credit = (decimal)clientBalancesRowView.Row["CledgerMasterAmount"];
                                        debit = Decimal.Zero;
                                        balance = balance + credit;
                                    }

                                    debit = Decimal.Round(debit, 2);
                                    credit = Decimal.Round(credit, 2);
                                    balance = Decimal.Round(balance, 2);

                                    // setup credit/debit/blance decimal to diaplsy as 0.00 in dataset
                                    string strDebit = string.Empty;
                                    string strCredit = string.Empty;
                                    string strBalance = string.Empty;

                                    if (debit == Decimal.Zero)
                                    {
                                        strDebit = "0.00";
                                    }
                                    else
                                    {
                                        strDebit = debit.ToString();
                                    }
                                    if (credit == Decimal.Zero)
                                    {
                                        strCredit = "0.00";
                                    }
                                    else
                                    {
                                        strCredit = credit.ToString();
                                    }
                                    if (balance == Decimal.Zero)
                                    {
                                        strBalance = "0.00";
                                    }
                                    else
                                    {
                                        strBalance = balance.ToString();
                                    }

                                    // Adds deposit details to dataset after calculations
                                    dsClientBalances.Tables["ClientBalances"].Rows.Add(postingId,
                                                                                         postingDate,
                                                                                         postingReference,
                                                                                         postingType,
                                                                                         postingDescription,
                                                                                         postingBank,
                                                                                         postingBankRef,
                                                                                         strDebit,
                                                                                         strCredit,
                                                                                         strBalance);
                                }
                            }
                        }

                        e.DataSet = dsClientBalances;
                    };

                    // Create the data list
                    returnValue.Balances = dataListCreator.Create(logonId,
                        // Give the query a name so it can be cached
                        "LoadClientBalancesDetails",
                        // Tell it the query criteria used so if the cache is accessed
                        // again it knows if it is the same query
                        projectId.ToString(),
                        collectionRequest,
                        // Import mappings to map the dataset row fields to the data
                        // list entity properties
                        new ImportMapping[] {
                                            new ImportMapping("PostingId", "PostingId"),
                                            new ImportMapping("PostingDate", "PostingDate"),
                                            new ImportMapping("PostingReference", "PostingReference"),
                                            new ImportMapping("PostingType", "PostingType"),
                                            new ImportMapping("PostingDescription","PostingDescription"),
                                            new ImportMapping("PostingBank", "PostingBank"),
                                            new ImportMapping("PostingBankRef", "PostingBankRef"),
                                            new ImportMapping("Debit","Debit"),
                                            new ImportMapping("Credit","Credit"),
                                            new ImportMapping("Balance","Balance")
                            }
                        );

                    returnValue.Success = true;
                }
                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>
        /// Get Document Types for Import Document
        /// </summary>
        /// <param name="logonId"></param>
        /// <param name="criteria"></param>
        /// <param name="collectionRequest"></param>
        /// <returns></returns>
        public DocumentTypeReturnValue GetDocumentTypes(Guid logonId, DocumentTypeSearchCriteria criteria, CollectionRequest collectionRequest)
        {
            DocumentTypeReturnValue returnValue = new DocumentTypeReturnValue();

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

                    // Create a data list creator for a list of matters
                    DataListCreator<DocumentTypeSearchItem> dataListCreator = new DataListCreator<DocumentTypeSearchItem>();

                    // Declare an inline event (annonymous delegate) to read the
                    // dataset if it is required
                    dataListCreator.ReadDataSet += delegate(object sender, ReadDataSetEventArgs e)
                    {
                        e.DataSet = SrvDocumentLookup.GetDocumentTypes(criteria.DocTypeIDs);
                    };

                    // Create the data list
                    returnValue.DocumentType = dataListCreator.Create(logonId,
                        // Give the query a name so it can be cached
                        "DocumentTypeSearch",
                        // Tell it the query criteria used so if the cache is accessed
                        // again it knows if it is the same query
                        criteria.ToString(),
                        collectionRequest,
                        // Import mappings to map the dataset row fields to the data
                        // list entity properties
                        new ImportMapping[] {
                            new ImportMapping("Id", "DocTypeID"),
                            new ImportMapping("Description", "DocTypeDescription")
                            }
                        );
                }
                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>
        /// 
        /// </summary>
        /// <param name="logonId"></param>
        /// <param name="collectionRequest"></param>
        /// <param name="criteria"></param>
        /// <returns></returns>
        public EarnerSearchReturnValue EarnerSearch(Guid logonId, CollectionRequest collectionRequest,
            EarnerSearchCriteria criteria)
        {
            EarnerSearchReturnValue returnValue = new EarnerSearchReturnValue();

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

                try
                {

                    switch (UserInformation.Instance.UserType)
                    {
                        case DataConstants.UserType.Staff:
                        case DataConstants.UserType.Client:
                        case DataConstants.UserType.ThirdParty:
                            // Can do everything
                            break;
                        default:
                            throw new Exception("Access denied");
                    }

                    // Create a data list creator for a list of matters
                    DataListCreator<EarnerSearchItem> dataListCreator = new DataListCreator<EarnerSearchItem>();

                    // Declare an inline event (annonymous delegate) to read the
                    // dataset if it is required
                    dataListCreator.ReadDataSet += delegate(object sender, ReadDataSetEventArgs e)
                    {
                        // TODO: Does not use criteria: FeeReference, EarnerId, UFNDate, UFNNumber
                        e.DataSet = SrvEarnerLookup.GetEarners(criteria.IncludeArchived, criteria.MultiOnly);

                        DataTable dt = Functions.SortDataTable(e.DataSet.Tables[0], "PersonSurname");
                        e.DataSet.Tables.Remove(e.DataSet.Tables[0]);
                        e.DataSet.Tables.Add(dt);
                    };

                    // Create the data list
                    returnValue.Earners = dataListCreator.Create(logonId,
                        // Give the query a name so it can be cached
                        "EarnerSearch",
                        // Tell it the query criteria used so if the cache is accessed
                        // again it knows if it is the same query
                        criteria.ToString(),
                        collectionRequest,
                        // Import mappings to map the dataset row fields to the data
                        // list entity properties
                        new ImportMapping[] {
                            new ImportMapping("Id", "MemberId"),
                            new ImportMapping("Reference", "feeRef"),
                            new ImportMapping("Title", "PersonTitle"),
                            new ImportMapping("Name","PersonName"),
                            new ImportMapping("SurName","PersonSurname")
                            }
                        );
                }
                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;
        }