/// <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>
        /// 
        /// </summary>
        /// <param name="logonId"></param>
        /// <param name="criteria"></param>
        /// <returns></returns>
        public WorkTypeSearchReturnValue GetValuesOnWorkTypeSelected(Guid logonId, WorkTypeSearchCriteria criteria)
        {
            WorkTypeSearchReturnValue returnValue = new WorkTypeSearchReturnValue();
            string errorMessage = string.Empty;
            string warningMessage = string.Empty;
            bool isValid = false;

            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 the dataset
                    SrvMatter serviceMatter = new SrvMatter();
                    //Set the client id and call the  client validation method which will set the client ref
                    //Cli ref is required to get the ucn and houcn values which are set in SetDefaultsOnWorkType
                    serviceMatter.ClientId = criteria.ClientId;
                    serviceMatter.ValidateClientId(out errorMessage, out warningMessage);
                    serviceMatter.CurrentWorkTypeId = criteria.Id;
                    isValid = serviceMatter.ValidateCurrentWorkTypeId(out errorMessage, out warningMessage);

                    // TODO: Does not use the criteria: FilterString, OrganisationID, DepartmentId, DepartmentNo, IsPrivateClient, MatterTypeId

                    if (isValid)
                    {
                        serviceMatter.SetDefaultsOnWorkType();
                        returnValue.IsPublicFunded = serviceMatter.IsPublicFunding;
                        returnValue.DisbLimit = serviceMatter.WorkTypeDisbLimit;
                        returnValue.OverallLimit = serviceMatter.WorkTypeOverallLimit;
                        returnValue.Quote = serviceMatter.WorkTypeQuote;
                        returnValue.TimeLimit = serviceMatter.WorkTypeTimeLimit;
                        returnValue.WipLimit = serviceMatter.WorkTypeWipLimit;
                        returnValue.ChargeRateDescriptionId = serviceMatter.ChargeDescriptionId;
                        returnValue.Franchised = serviceMatter.WorkCategoryFranchised;
                        returnValue.WorkCategoryUFN = serviceMatter.WorkCategoryUFN;
                        returnValue.ClientHOUCN = serviceMatter.ClientHOUCN;
                        returnValue.ClientUCN = serviceMatter.ClientUCN;
                    }
                    else
                    {
                        returnValue.Success = false;
                        returnValue.Message = errorMessage;
                    }

                }
                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>
        /// Toggles UCN,UFN,HOUCN and sets other defaults based on the selected work type.
        /// </summary>
        private void SetWorkTypeDefaults()
        {
            Guid memberId = (Guid)Session[SessionName.MemberId];
            Guid organisationId = (Guid)Session[SessionName.OrganisationId];
            Guid clientId;
            if (memberId != DataConstants.DummyGuid)
            {
                clientId = memberId;
            }
            else
            {
                clientId = organisationId;
            }

            if (_ddlWorkType.SelectedValue != string.Empty)
            {
                MatterServiceClient matterService = null;
                try
                {
                    WorkTypeSearchCriteria searchCriteria = new WorkTypeSearchCriteria();
                    searchCriteria.Id = new Guid(_ddlWorkType.SelectedValue);
                    searchCriteria.ClientId = clientId;

                    matterService = new MatterServiceClient();
                    WorkTypeSearchReturnValue returnValue = matterService.GetValuesOnWorkTypeSelected(_logonSettings.LogonId, searchCriteria);

                    if (returnValue.Success)
                    {
                        //set matter LA Flag to worktype IsLa status, Department to worktype dept and Charge Description to Worktype chargeDesc
                        _chkPublicFunding.Checked = returnValue.IsPublicFunded;

                        _chkSQM.Checked = returnValue.Franchised;

                        if (returnValue.IsPublicFunded)
                        {
                            int clientTypeId = (int)ViewState[ClientType];
                            switch (returnValue.WorkCategoryUFN)
                            {
                                case 1:
                                    #region UFN Only.
                                    if (clientTypeId == 1)
                                    {
                                        _trUFN.Visible = true;

                                        _ccUFNDate.DateText = DateTime.Now.ToString("dd/MM/yyyy");
                                        UFNDateTextChanged();
                                        _trHOUCN.Visible = false;
                                        _trUCN.Visible = false;
                                        _chkPublicFunding.Visible = true;
                                        _chkPublicFunding.Enabled = true;
                                        _chkSQM.Enabled = true;
                                    }
                                    else
                                    {
                                        _trUFN.Visible = false;
                                        _trHOUCN.Visible = false;
                                        _trUCN.Visible = false;
                                    }
                                    #endregion
                                    break;

                                case 2:
                                    #region HO UCN & UCN.
                                    if (clientTypeId == 1)
                                    {
                                        _trUFN.Visible = false;
                                        _trHOUCN.Visible = true;
                                        _trUCN.Visible = true;

                                        if (returnValue.ClientHOUCN != string.Empty)
                                        {
                                            _txtHOUCN.ReadOnly = true;
                                            _txtHOUCN.Text = returnValue.ClientHOUCN;
                                        }
                                        else
                                        {
                                            _txtHOUCN.ReadOnly = false;
                                            _txtHOUCN.Text = string.Empty;
                                        }

                                        if (returnValue.ClientUCN != BlankUCN & !string.IsNullOrEmpty(returnValue.ClientUCN))
                                        {
                                            _txtUCN.Text = returnValue.ClientUCN;
                                        }
                                    }
                                    else
                                    {
                                        _trUFN.Visible = false;
                                        _trHOUCN.Visible = false;
                                        _trUCN.Visible = false;
                                    }
                                    #endregion
                                    break;

                                case 3:
                                    #region UFN, HO UCN & UCN.
                                    if (clientTypeId == 1)
                                    {
                                        _trUFN.Visible = true;

                                        _ccUFNDate.DateText = DateTime.Now.ToString("dd/MM/yyyy");
                                        UFNDateTextChanged();
                                        _trHOUCN.Visible = true;
                                        _trUCN.Visible = true;

                                        if (!string.IsNullOrEmpty(returnValue.ClientHOUCN))
                                        {
                                            _txtHOUCN.ReadOnly = true;
                                            _txtHOUCN.Text = returnValue.ClientHOUCN;
                                        }
                                        else
                                        {
                                            _txtHOUCN.ReadOnly = false;
                                            _txtHOUCN.Text = string.Empty;
                                        }

                                        if (returnValue.ClientUCN != BlankUCN & !string.IsNullOrEmpty(returnValue.ClientUCN))
                                        {
                                            _txtUCN.Text = returnValue.ClientUCN;
                                        }
                                    }
                                    else
                                    {
                                        _trUFN.Visible = false;
                                        _trHOUCN.Visible = false;
                                        _trUCN.Visible = false;
                                    }
                                    #endregion
                                    break;

                                default:
                                    _trUFN.Visible = false;
                                    _trHOUCN.Visible = false;
                                    _trUCN.Visible = false;
                                    break;
                            }

                            _chkSQM.Visible = true;
                            _ddlCourtType.Enabled = false;
                        }
                        else
                        {
                            _trUFN.Visible = false;
                            _trHOUCN.Visible = false;
                            _trUCN.Visible = false;
                            _chkPublicFunding.Visible = false;
                            _chkPublicFunding.Enabled = false;
                            _chkSQM.Visible = false;
                            _chkSQM.Enabled = false;
                            _chkSQM.Checked = false;
                            _ddlCourtType.Enabled = true;
                        }

                        GetChargeRates(_chkPublicFunding.Checked);

                        //Set the default charge rate for the worktype
                        if (returnValue.ChargeRateDescriptionId != Guid.Empty && returnValue.ChargeRateDescriptionId != DataConstants.DummyGuid)
                        {
                            foreach (ListItem chargeRate in _ddlChargeRate.Items)
                            {
                                if (GetChargeRateValueOnIndex(chargeRate.Value, 0) == returnValue.ChargeRateDescriptionId.ToString())
                                {
                                    chargeRate.Selected = true;
                                    break;
                                }
                            }
                        }
                    }
                    else
                    {
                        throw new Exception(returnValue.Message);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    if (matterService != null)
                    {
                        if (matterService.State != System.ServiceModel.CommunicationState.Faulted)
                            matterService.Close();
                    }
                }
            }
        }
 /// <summary>
 /// Worktype search 
 /// </summary>
 /// <param name="oHostSecurityToken">HostSecurityToken obtained when security provider of IWS is called</param>
 /// <param name="collectionRequest"></param>
 /// <param name="criteria"></param>
 /// <returns></returns>
 public WorkTypeSearchReturnValue WorkTypeSearch(HostSecurityToken oHostSecurityToken,
                                          CollectionRequest collectionRequest,
                                          WorkTypeSearchCriteria criteria)
 {
     WorkTypeSearchReturnValue returnValue = null;
     if (Functions.ValidateIWSToken(oHostSecurityToken))
     {
         oMatterService = new MatterService();
         returnValue = oMatterService.WorkTypeSearch(Functions.GetLogonIdFromToken(oHostSecurityToken), collectionRequest, criteria);
     }
     else
     {
         returnValue = new WorkTypeSearchReturnValue();
         returnValue.Success = false;
         returnValue.Message = "Invalid Token";
     }
     return returnValue;
 }
        /// <summary>
        /// Gets the work types based on the selected branch and department.
        /// </summary>
        private void GetWorkTypes()
        {
            //Matter type is required to get the work types
            if (_ddlMatterType.SelectedValue != string.Empty)
            {
                Guid memberId = (Guid)Session[SessionName.MemberId];
                bool isMember = false;
                if (memberId != DataConstants.DummyGuid)
                {
                    isMember = true;
                }

                //Check if a department is selected
                if (_ddlDepartment.SelectedValue != string.Empty)
                {
                    MatterServiceClient matterService = null;
                    try
                    {
                        int clientTypeId = (int)ViewState[ClientType];
                        bool privateClient = true;
                        switch (clientTypeId)
                        {
                            case 1: // Standard Client.
                                if (isMember == false)
                                {
                                    privateClient = false;
                                }
                                else
                                {
                                    privateClient = true;
                                }
                                break;

                            case 2: // LSC Client.
                                privateClient = true;
                                break;

                            case 3: // Firm Client.
                                privateClient = false;
                                break;

                            default:
                                privateClient = true;
                                break;
                        }

                        CollectionRequest collectionRequest = new CollectionRequest();

                        WorkTypeSearchCriteria searchCriteria = new WorkTypeSearchCriteria();
                        searchCriteria.DepartmentId = Convert.ToInt32(_ddlDepartment.SelectedValue);
                        searchCriteria.OrganisationID = new Guid(GetBranchValueOnIndex(_ddlBranch.SelectedValue, 1));
                        searchCriteria.IsPrivateClient = privateClient;
                        searchCriteria.MatterTypeId = Convert.ToInt32(_ddlMatterType.SelectedValue);

                        matterService = new MatterServiceClient();
                        WorkTypeSearchReturnValue returnValue = matterService.WorkTypeSearch(_logonSettings.LogonId,
                                                collectionRequest, searchCriteria);

                        //Store the previous selected value. This will prevent the worktype from being reset if its valid
                        string prevValue = _ddlWorkType.SelectedValue;

                        if (returnValue.Success)
                        {
                            _ddlWorkType.DataSource = returnValue.WorkTypes.Rows;
                            _ddlWorkType.DataTextField = "Description";
                            _ddlWorkType.DataValueField = "Id";
                            _ddlWorkType.DataBind();

                            if (_ddlWorkType.Items.FindByValue(prevValue) != null)
                            {
                                _ddlWorkType.SelectedValue = prevValue;
                            }
                        }
                        else
                        {
                            throw new Exception(returnValue.Message);
                        }

                        AddDefaultToDropDownList(_ddlWorkType);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                    finally
                    {
                        if (matterService != null)
                        {
                            if (matterService.State != System.ServiceModel.CommunicationState.Faulted)
                                matterService.Close();
                        }
                    }
                }
                else
                {
                    //No dept selected. Reset Worktypes
                    _ddlWorkType.Items.Clear();
                }
            }
        }