/// <summary>
 /// Add a new matter
 /// </summary>
 /// <param name="oHostSecurityToken">HostSecurityToken obtained when security provider of IWS is called</param>
 /// <param name="matter">Matter details</param>
 /// <returns></returns>
 public MatterReturnValue AddMatter(HostSecurityToken oHostSecurityToken, Matter matter)
 {
     MatterReturnValue returnValue = null;
     if (Functions.ValidateIWSToken(oHostSecurityToken))
     {
         oMatterService = new MatterService();
         returnValue = oMatterService.AddMatter(Functions.GetLogonIdFromToken(oHostSecurityToken), matter);
     }
     else
     {
         returnValue = new MatterReturnValue();
         returnValue.Success = false;
         returnValue.Message = "Invalid Token";
     }
     return returnValue;
 }
        private void LoadMatterFeeEarner(Guid ProjectID)
        {
            MatterServiceClient matterService = new MatterServiceClient();
            try
            {
                MatterReturnValue matterReturnValue = new MatterReturnValue();
                matterReturnValue = matterService.GetMatter(_logonSettings.LogonId, ProjectID);

                if (matterReturnValue.Success)
                {
                    if (matterReturnValue != null)
                    {
                        if (matterReturnValue.Matter.FeeEarnerMemberId != null)
                        {
                            EarnerServiceClient partnerClient = new EarnerServiceClient();
                            try
                            {
                                PartnerSearchCriteria partnerCriteria = new PartnerSearchCriteria();
                                CollectionRequest collectionRequest = new CollectionRequest();
                                collectionRequest.StartRow = 0;

                                PartnerSearchReturnValue partnerReturnValue = partnerClient.PartnerSearch(_logonSettings.LogonId, collectionRequest, partnerCriteria);

                                if (partnerReturnValue.Success)
                                {
                                    if (partnerReturnValue.Partners != null)
                                    {
                                        for (int i = 0; i < partnerReturnValue.Partners.Rows.Length; i++)
                                        {
                                            if (partnerReturnValue.Partners.Rows[i].PartnerId.ToString() == matterReturnValue.Matter.FeeEarnerMemberId.ToString())
                                            {
                                                _txtAttendees.Text = CommonFunctions.MakeFullName(partnerReturnValue.Partners.Rows[i].PersonTitle, partnerReturnValue.Partners.Rows[i].Name, partnerReturnValue.Partners.Rows[i].Surname);
                                                _hdnAttendeesMemberId.Value = partnerReturnValue.Partners.Rows[i].PartnerId.ToString() + ";";
                                            }

                                        }
                                    }
                                }
                                else
                                {
                                    _lblError.Text = partnerReturnValue.Message;
                                }
                            }
                            catch (Exception ex)
                            {
                                throw ex;
                            }
                            finally
                            {
                                if (partnerClient.State != System.ServiceModel.CommunicationState.Faulted)
                                    partnerClient.Close();
                            }

                        }
                    }

                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (matterService.State != System.ServiceModel.CommunicationState.Faulted)
                    matterService.Close();
            }
        }
        private void LoadClientMatterDetails(Guid projectId)
        {
            try
            {
                MatterServiceClient matterService = new MatterServiceClient();
                try
                {
                    MatterReturnValue matterReturnValue = new MatterReturnValue();
                    matterReturnValue = matterService.GetMatter(((LogonReturnValue)Session[SessionName.LogonSettings]).LogonId, projectId);

                    if (matterReturnValue.Success)
                    {
                        if (matterReturnValue != null)
                        {
                            #region Load Client Details
                            // Store ClientID
                            if (matterReturnValue.ClientDetails.IsMember)
                            {
                                _cliMatDetails.MemberId = matterReturnValue.ClientDetails.MemberId;
                                _cliMatDetails.OrganisationId = DataConstants.DummyGuid;
                            }
                            else
                            {
                                _cliMatDetails.MemberId = DataConstants.DummyGuid;
                                _cliMatDetails.OrganisationId = matterReturnValue.ClientDetails.MemberId;
                            }

                            _cliMatDetails.IsClientMember = matterReturnValue.ClientDetails.IsMember;
                            _cliMatDetails.ClientRef = matterReturnValue.ClientDetails.Reference;
                            _cliMatDetails.ClientName = matterReturnValue.ClientDetails.FullName;

                            if (_cliMatDetails.Message != null)
                            {
                                if (_cliMatDetails.Message.Trim().Length > 0)
                                {
                                    throw new Exception("Loading failed for Client Matter Details.<br>Exception occured is: " + _cliMatDetails.Message);
                                }
                            }

                            #endregion
                        }
                        else
                        {
                            throw new Exception("Load failed.");
                        }
                    }
                    else
                    {
                        throw new Exception(matterReturnValue.Message);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    if (matterService.State != System.ServiceModel.CommunicationState.Faulted)
                        matterService.Close();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// Loads client matter details on load controls in edit mode
        /// </summary>
        /// <param name="projectId"></param>
        private void LoadClientMatterDetails(Guid projectId)
        {
            MatterServiceClient matterService = null;
            MatterReturnValue matterReturnValue = null;

            try
            {
                matterService = new MatterServiceClient();

                try
                {
                    matterReturnValue = new MatterReturnValue();
                    matterReturnValue = matterService.GetMatter(((LogonReturnValue)Session[SessionName.LogonSettings]).LogonId, projectId);

                    if (matterReturnValue.Success)
                    {
                        if (matterReturnValue != null)
                        {
                            #region Load Client Details
                            // Stores ClientID
                            if (matterReturnValue.ClientDetails.IsMember)
                            {
                                Session[SessionName.MemberId] = matterReturnValue.ClientDetails.MemberId;
                                Session[SessionName.OrganisationId] = DataConstants.DummyGuid;
                            }
                            else
                            {
                                Session[SessionName.MemberId] = DataConstants.DummyGuid;
                                // Shouldn't be looking for  MemberId for Organisation Client
                               // Session[SessionName.OrganisationId] = matterReturnValue.ClientDetails.MemberId;
                                Session[SessionName.OrganisationId] = matterReturnValue.ClientDetails.OrganisationId;

                            }

                            _cliMatDetails.IsClientMember = matterReturnValue.ClientDetails.IsMember;
                            Session[SessionName.ClientRef] = matterReturnValue.ClientDetails.Reference;
                            Session[SessionName.ClientName] = matterReturnValue.ClientDetails.FullName;

                            if (_cliMatDetails.Message != null)
                            {
                                if (_cliMatDetails.Message.Trim().Length > 0)
                                {
                                    throw new Exception("Loading failed for Client Matter Details.<br>Exception occured is: " + _cliMatDetails.Message);
                                }
                            }

                            #endregion
                        }
                        else
                        {
                            throw new Exception("Load failed.");
                        }
                    }
                    else
                    {
                        throw new Exception(matterReturnValue.Message);
                    }
                }
                catch (System.ServiceModel.EndpointNotFoundException)
                {
                    _lblMessage.Text = DataConstants.WSEndPointErrorMessage;
                    _lblMessage.CssClass = "errorMessage";
                }
                catch (Exception ex)
                {
                    _lblMessage.CssClass = "errorMessage";
                    _lblMessage.Text = ex.Message;
                }
                finally
                {
                    if (matterService.State != System.ServiceModel.CommunicationState.Faulted)
                        matterService.Close();
                }
            }
            catch (System.ServiceModel.EndpointNotFoundException)
            {
                _lblMessage.Text = DataConstants.WSEndPointErrorMessage;
                _lblMessage.CssClass = "errorMessage";
            }
            catch (Exception ex)
            {
                _lblMessage.CssClass = "errorMessage";
                _lblMessage.Text = ex.Message;
            }
        }
        /// <summary>
        /// Add a new matter
        /// </summary>
        /// <param name="logonId">Logon id obtained when logging on to the logon service</param>
        /// <param name="matter">Matter details</param>
        /// <returns></returns>
        public MatterReturnValue AddMatter(Guid logonId, Matter matter)
        {
            MatterReturnValue returnValue = new MatterReturnValue();

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

                    // Ensure we have permission
                    if (!UserSecuritySettings.GetUserSecuitySettings(182))
                        throw new Exception("You do not have sufficient permissions to carry out this request");

                    // Verify Annual Licence
                    if (!IRIS.Law.PmsBusiness.LicenseDetails.AnnualLicenseIsValid())
                    {
                        throw new Exception("Unable to add Matter. Your Annual Licence has expired or is invalid.");
                    }

                    SrvMatter srvMatter = new SrvMatter();

                    srvMatter.ClientId = matter.ClientId;
                    srvMatter.MatterDescription = matter.Description;
                    srvMatter.MatterPartnerMemberId = matter.PartnerMemberId;
                    srvMatter.FeeEarnerMemberId = matter.FeeEarnerMemberId;
                    srvMatter.WorkCategoryFranchised = matter.Franchised;
                    //Call SetDefaultsOnFeeEarnerMemberId in order to set the userId
                    srvMatter.SetDefaultsOnFeeEarnerMemberId();
                    srvMatter.UFNNumber = matter.UFN;
                    srvMatter.UFNDate = matter.UFNDate;
                    srvMatter.IsPublicFunding = matter.IsPublicFunding;
                    srvMatter.ClientBankId = matter.ClientBankId;
                    srvMatter.OfficeBankId = matter.OfficeBankId;
                    srvMatter.ChargeDescriptionId = matter.ChargeDescriptionId;
                    srvMatter.CurrentWorkTypeId = matter.WorkTypeId;
                    srvMatter.DepartmentId = matter.DepartmentId;
                    srvMatter.BranchId = matter.BranchReference;
                    srvMatter.CourtId = matter.CourtId;
                    srvMatter.MatterTypeId = matter.MatterTypeId;
                    srvMatter.ClientHOUCN = matter.HOUCN;
                    srvMatter.EarnerReference = matter.FeeEarnerReference;
                    srvMatter.ConOrgMemIdCollection = new NameValueCollection();
                    foreach (JointClientCandidateSearchItem client in matter.JointClientCandidates.Rows)
                    {
                        srvMatter.ConOrgMemIdCollection.Add(client.OrganisationId, client.MemberId);
                    }

                    string errorMessage;

                    returnValue.Success = srvMatter.Save(out errorMessage);
                    returnValue.Message = errorMessage;

                    matter.Id = srvMatter.ProjectId;
                    returnValue.Matter = matter;
                }
                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 one matter
        /// </summary>
        /// <param name="logonId">Logon id obtained when logging on to the logon service</param>
        /// <param name="projectId">Matter project id</param>
        /// <returns></returns>
        public MatterReturnValue GetMatter(Guid logonId, Guid projectId)
        {
            MatterReturnValue returnValue = new MatterReturnValue();

            try
            {
                // Get the logged on user from the current logons and add their
                // ApplicationSettings the list of concurrent sessions.
                // ApplicationSettings.Instance can now be used to get the
                // ApplicationSettings for this session.
                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(projectId))
                                throw new Exception("Access denied");
                            break;
                        default:
                            throw new Exception("Access denied");
                    }

                    SrvMatter srvMatter = new SrvMatter();
                    int campaignId = SrvMatterCommon.GetCampaignForProject(projectId);

                    srvMatter.Load(projectId);

                    Matter matter = new Matter();
                    matter.Id = srvMatter.ProjectId;

                    // Load Matter Details
                    matter.Description = srvMatter.MatterDescription;
                    matter.KeyDescription = srvMatter.MatterKeyDescription;
                    matter.FeeEarnerMemberId = srvMatter.FeeEarnerMemberId;
                    matter.PartnerMemberId = srvMatter.MatterPartnerMemberId;
                    matter.WorkTypeId = srvMatter.CurrentWorkTypeId;
                    matter.ClientBankId = srvMatter.ClientBankId;
                    matter.OfficeBankId = srvMatter.OfficeBankId;
                    matter.DepositBankId = srvMatter.MatterDepositBankId;
                    matter.BranchReference = srvMatter.BranchId;
                    matter.DepartmentId = srvMatter.DepartmentId;
                    matter.ChargeDescriptionId = srvMatter.ChargeDescriptionId;
                    matter.CourtId = srvMatter.CourtId;
                    matter.OpenDate = srvMatter.MatterOpenDate;
                    matter.NextReviewDate = srvMatter.MatterNextReviewDate;
                    matter.CostReviewDate = srvMatter.MatterCostReviewDate;
                    matter.LastSavedDate = srvMatter.MatterLastSaved;
                    matter.ClosedDate = srvMatter.MatterClosedDate;
                    matter.DestructDate = srvMatter.MatterDestructDate;
                    matter.FileNo = srvMatter.MatterFileNo;
                    matter.CompletedDate = srvMatter.MatterCompleted;
                    matter.SpanType1Ref = srvMatter.SpanType1;
                    matter.SpanType2Ref = srvMatter.SpanType2;

                    // Load Matter Additional Info
                    matter.Quote = srvMatter.MatterQuote;
                    matter.DisbsLimit = srvMatter.MatterDisbsLimit;
                    matter.TimeLimit = srvMatter.MatterTimeLimit;
                    matter.WIPLimit = srvMatter.MatterWIPLimit;
                    matter.OverallLimit = srvMatter.MatterOverallLimit;
                    matter.Status = srvMatter.MatterStatus;
                    matter.Indicators = srvMatter.MatterIndicators;
                    matter.BankReference = srvMatter.MatterBankReference;
                    matter.CashCollectionId = srvMatter.MatCashCollID;
                    matter.TotalLockup = srvMatter.MatTotalLockup;
                    matter.OurReference = srvMatter.OurReference;
                    matter.PreviousReference = srvMatter.PreviousReference;
                    matter.BusinessSourceId = srvMatter.SourceID;
                    matter.SourceCampaignId = campaignId;
                    matter.PersonDealingId = srvMatter.UserId;
                    matter.SalutationEnvelope = srvMatter.MatterSalutationEnvelope;
                    matter.SalutationLetter = srvMatter.MatterSalutationLetter;
                    matter.LetterHead = srvMatter.MatterLetterHead;

                    // Load Public Funding
                    matter.MatterLegalAided = srvMatter.MatterLegalAided;
                    matter.IsPublicFunding = srvMatter.IsPublicFunding;
                    matter.Franchised = srvMatter.MatterFranchised;
                    matter.isLondonRate = srvMatter.MatterLondonRate;
                    matter.UFNDate = srvMatter.UFNDate;
                    matter.UFN = srvMatter.UFNNumber;
                    matter.PFCertificateNo = srvMatter.MatterPFCertificateNo;
                    matter.PFCertificateNoLimits = srvMatter.MatterPFCertificateLimits;
                    matter.MatterTypeId = srvMatter.MatterTypeId;

                    // Load Client Details
                    Client client = new Client();
                    client.IsMember = srvMatter.IsMember;

                    //Set MemberID for Individual
                    if (client.IsMember)
                    {
                        client.MemberId = srvMatter.ClientId;
                        client.OrganisationId = DataConstants.DummyGuid;
                    }
                    //Set OrganisationId for Organisation
                    else
                    {
                        client.MemberId = DataConstants.DummyGuid;
                        client.OrganisationId = srvMatter.ClientId;
                    }

                    client.Reference = srvMatter.ClientReference;
                    client.FullName = srvMatter.ClientName;
                    client.IsArchived = srvMatter.IsClientArchived;

                    // Get Client Type ID
                    client.TypeId = this.GetClientType(srvMatter.ClientId, srvMatter.ProjectId, srvMatter.IsMember);

                    returnValue.Matter = matter;
                    returnValue.ClientDetails = client;
                }
                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 the client matter details.
        /// </summary>
        private void LoadClientMatterDetails()
        {
            if (_projectId != DataConstants.DummyGuid)
            {
                Guid memberId;
                Guid organisationId;

                try
                {
                    MatterServiceClient matterService = new MatterServiceClient();
                    try
                    {
                        MatterReturnValue matterReturnValue = new MatterReturnValue();
                        matterReturnValue = matterService.GetMatter(_logonId, _projectId);

                        if (matterReturnValue.Success)
                        {
                            #region Load Client Details

                            if (matterReturnValue.ClientDetails.IsMember)
                            {
                                memberId = matterReturnValue.ClientDetails.MemberId;
                                organisationId = DataConstants.DummyGuid;
                            }
                            else
                            {
                                memberId = DataConstants.DummyGuid;
                                organisationId = matterReturnValue.ClientDetails.MemberId;
                            }

                            ListItem item = new ListItem();
                            item.Text = matterReturnValue.ClientDetails.FullName;
                            item.Value = memberId.ToString() + "$" + organisationId.ToString();
                            _ddlClients.Items.Add(item);

                            //Get the matters for the client
                            GetClientMatters(memberId, organisationId);

                            //Select the matter
                            if (_ddlClientMatters.Items.Count > 0)
                            {
                                ListItem matter = _ddlClientMatters.Items.FindByValue(_projectId.ToString());
                                if (matter != null)
                                {
                                    _ddlClientMatters.SelectedValue = matter.Value;
                                    OnMatterChanged(EventArgs.Empty);
                                }
                            }
                            else
                            {
                                throw new Exception("Error loading matter");
                            }

                            #endregion
                        }
                        else
                        {
                            throw new Exception(matterReturnValue.Message);
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                    finally
                    {
                        if (matterService.State != System.ServiceModel.CommunicationState.Faulted)
                            matterService.Close();
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
        /// <summary>
        /// Gets the client bank Id, office bank Id and partner member Id based on the branch and dept id
        /// </summary>
        /// <param name="logonId">The logon id.</param>
        /// <param name="branchOrganisationId">The branch organisation id.</param>
        /// <param name="departmentId">The department id.</param>
        /// <returns></returns>
        public MatterReturnValue GetBranchDepartmentDefaults(Guid logonId, Guid branchOrganisationId,
                                                int departmentId)
        {
            MatterReturnValue returnValue = new MatterReturnValue();

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

                    returnValue.Matter = new Matter();
                    DsBranchDept dsBranchDept = SrvBranchLookup.GetBranchDepts(branchOrganisationId, departmentId);
                    if (dsBranchDept.BranchDept.Rows.Count != 0)
                    {
                        returnValue.Matter.ClientBankId = dsBranchDept.BranchDept[0].bankIdClient;
                        returnValue.Matter.OfficeBankId = dsBranchDept.BranchDept[0].bankIdOffice;
                        returnValue.Matter.PartnerMemberId = dsBranchDept.BranchDept[0].MemberId;
                    }
                    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>
 /// Gets the client bank Id, office bank Id and partner member Id based on the branch and dept id
 /// </summary>
 /// <param name="oHostSecurityToken">The Host Security Token from IWS</param>
 /// <param name="branchOrganisationId">The branch organisation id.</param>
 /// <param name="departmentId">The department id.</param>
 /// <returns></returns>
 public MatterReturnValue GetBranchDepartmentDefaults(HostSecurityToken oHostSecurityToken, Guid branchOrganisationId,
                                         int departmentId)
 {
     MatterReturnValue returnValue = new MatterReturnValue();
     if (Functions.ValidateIWSToken(oHostSecurityToken))
     {
         oBranchDeptService = new BranchDeptService();
         returnValue = oBranchDeptService.GetBranchDepartmentDefaults(Functions.GetLogonIdFromToken(oHostSecurityToken), branchOrganisationId, departmentId);
     }
     else
     {
         returnValue = new MatterReturnValue();
         returnValue.Success = false;
         returnValue.Message = "Invalid Token";
     }
     return returnValue;
 }