/// <summary>
        /// Create Service contract
        /// </summary>
        private void CreateServiceContact(string conflictNoteSummary, string conflictNoteContent)
        {
            ContactServiceClient contactService = null;
            try
            {
                ServiceContact serviceContactInfo = new ServiceContact();

                serviceContactInfo.ServiceId = new Guid(Convert.ToString(ViewState["ServiceId"]));
                serviceContactInfo.ServiceName = Convert.ToString(ViewState["ServiceName"]);
                serviceContactInfo.SurName = _cdContactDetails.SurName;
                serviceContactInfo.ForeName = _cdContactDetails.ForeName;
                serviceContactInfo.Title = _cdContactDetails.Title;
                if (_cdContactDetails.Sex!=string.Empty)
                    serviceContactInfo.Sex = int.Parse(_cdContactDetails.Sex);
                serviceContactInfo.Position = _cdContactDetails.Position;

                //Get the address details
                Address address = new Address();
                address = _addressDetails.Address;

                contactService = new ContactServiceClient();

                ReturnValue returnValue = contactService.SaveServiceContact(_logonSettings.LogonId, address, _aadContactInfo.AdditionalDetails, serviceContactInfo, conflictNoteSummary, conflictNoteContent);

                if (returnValue.Success)
                {
                    _wizardContact.Visible = true;
                    Session["SuccessMesage"] = "Service Contact saved successfully";

                    ResetControls();
                }
                else
                {
                    _lblError.CssClass = "errorMessage";
                    _lblError.Text = returnValue.Message;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (contactService != null)
                {
                    if (contactService.State != System.ServiceModel.CommunicationState.Faulted)
                        contactService.Close();
                }
            }
        }
        /// <summary>
        /// Saves the address for the contact.
        /// </summary>
        /// <param name="logonId">Logon id obtained when logging on to the logon service.</param>
        /// <param name="address">The address.</param>
        /// <returns></returns>
        public AddressReturnValue SaveAddress(Guid logonId, Address address)
        {
            AddressReturnValue returnValue = new AddressReturnValue();

            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(address.MemberId, address.OrganisationId))
                                throw new Exception("Access denied");
                            break;
                        default:
                            throw new Exception("Access denied");
                    }

                    SrvAddress srvAddress = new SrvAddress();
                    if (address.Id > 0)
                    {
                        srvAddress.Load(address.Id);
                    }

                    srvAddress.MemberId = address.MemberId;
                    srvAddress.OrganisationId = address.OrganisationId;
                    srvAddress.AddressTypeId = address.TypeId;
                    srvAddress.AddressId = address.Id;
                    srvAddress.AddressStreetNumber = address.StreetNumber;
                    srvAddress.AddressPostCode = address.PostCode;
                    srvAddress.AddressHouseName = address.HouseName;
                    srvAddress.AddressLine1 = address.Line1;
                    srvAddress.AddressLine2 = address.Line2;
                    srvAddress.AddressLine3 = address.Line3;
                    srvAddress.AddressTown = address.Town;
                    srvAddress.AddressCounty = address.County;
                    srvAddress.AddressCountry = address.Country;
                    srvAddress.AddressDXTown = address.DXTown;
                    srvAddress.AddressDXNumber = address.DXNumber;
                    srvAddress.IsMailingAddress = address.IsMailingAddress;
                    srvAddress.IsBillingAddress = address.IsBillingAddress;
                    srvAddress.AddressOrgName = address.OrganisationName;
                    srvAddress.AddressComment = address.Comment;
                    srvAddress.AddressDepartment = address.Department;
                    srvAddress.AddressPostBox = address.PostBox;
                    srvAddress.AddressSubBuilding = address.SubBuilding;
                    srvAddress.AddressDependantLocality = address.DependantLocality;
                    srvAddress.AddressLastVerified = address.LastVerified;

                    string errorMessage;

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

                    address.Id = srvAddress.AddressId;
                    returnValue.Address = address;
                }
                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>
        /// Displays the address details for the selected address type.
        /// </summary>
        private void DisplayContactAddressDetails()
        {
            try
            {
                AddressSearchReturnValue addressSearchReturnValue = new AddressSearchReturnValue();
                CollectionRequest collectionRequest = new CollectionRequest();
                AddressSearchCriteria searchCriteria = new AddressSearchCriteria();
                searchCriteria.MemberId = _memberId;
                searchCriteria.OrganisationId = _organisationId;

                ContactServiceClient serviceClient = new ContactServiceClient();
                addressSearchReturnValue = serviceClient.GetContactAddresses(_logonSettings.LogonId, collectionRequest, searchCriteria);

                List<Address> contactAddresses = null;
                Address currentAddress = null;
                if (!IsPostBack)
                {
                    GetContactAddressTypes();
                    //Store the addresses in a list so that we can add items if necessary
                    contactAddresses = new List<Address>();
                    foreach (Address address in addressSearchReturnValue.Addresses.Rows)
                    {
                        contactAddresses.Add(address);
                    }
                    Session[SessionName.ClientAddresses] = contactAddresses;
                }
                else
                {
                    contactAddresses = (List<Address>)Session[SessionName.ClientAddresses];
                }

                //Get the current selected address type and display the address
                foreach (Address address in contactAddresses)
                {
                    if (address.TypeId == 1)
                    {
                        Session[SessionName.ContactDetails] = address.AdditionalAddressElements;
                    }

                    if (address.TypeId == Convert.ToInt32(_ddlAddressType.SelectedValue))
                    {
                        currentAddress = address;
                        break;
                    }
                }
                //If an address exists then display it..
                if (currentAddress != null)
                {
                    List<string> updatedAddresses = (List<string>)ViewState[UpdatedAddresses];
                    _ucAddress.Address = currentAddress;
                    _ucAddress.IsDataChanged = updatedAddresses.Contains(currentAddress.TypeId.ToString());
                    _ucAddress.DataBind();
                }
                else
                {
                    //No address exists for the current type, so create a new one
                    currentAddress = new Address();
                    currentAddress.LastVerified = DataConstants.BlankDate;
                    currentAddress.TypeId = Convert.ToInt32(_ddlAddressType.SelectedValue);
                    contactAddresses.Add(currentAddress);
                    _ucAddress.Address = currentAddress;
                    _ucAddress.IsDataChanged = false;
                    _ucAddress.DataBind();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// Create General contact for Individual and Organisation Contact Type 
        /// </summary>
        private void CreateGeneralContact(string conflictNoteSummary, string conflictNoteContent)
        {
            ContactServiceClient contactService = null;
            try
            {
                Person person = null;
                Organisation organisation = null;
                ContactType contactType = ContactType.Individual;

                if (_ddlContactType.Text == "Individual")
                {
                    person = new Person();
                    person.ForeName = _txtForename.Text;
                    person.Surname = _txtSurname.Text;
                    person.Title = _ddlTitle.Text;
                    contactType = ContactType.Individual;
                }

                if (_ddlContactType.Text == "Organisation")
                {
                    organisation = new Organisation();
                    organisation.Name = _txtOrgName.Text;
                    contactType = ContactType.Organisation;
                }

                // Gets the address details
                Address address = new Address();
                address = _addressDetails.Address;
                address.TypeId = 1;

                contactService = new ContactServiceClient();
                ReturnValue returnValue = contactService.SaveGeneralContact(_logonSettings.LogonId, address,
                                                            person, _aadContactInfo.AdditionalDetails,
                                                            contactType, organisation, conflictNoteSummary,
                                                            conflictNoteContent);

                if (returnValue.Success)
                {
                    _wizardContact.Visible = true;
                    Session["SuccessMesage"] = "General Contact saved successfully";

                    ResetControls();
                }
                else
                {
                    _lblError.CssClass = "errorMessage";
                    _lblError.Text = returnValue.Message;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (contactService != null)
                {
                    if (contactService.State != System.ServiceModel.CommunicationState.Faulted)
                        contactService.Close();
                }
            }
        }
        /// <summary>
        /// Conflicts the check.
        /// </summary>
        /// <returns></returns>
        private bool ConflictCheck()
        {
            bool canSave = false;
            try
            {
                if (_ddlRole.SelectedItem.Text.Trim() == "Otherside")
                {
                    Guid memId = new Guid(_hdnMemberId.Value);
                    Guid orgId = new Guid(_hdnOrganisationId.Value);

                    string conflictName = string.Empty;
                    Organisation organisation = null;
                    Person person = new Person();

                    if (memId != DataConstants.DummyGuid)
                    {
                        conflictName = GetPersonName(memId);
                    }
                    else
                    {
                        conflictName = GetOrganisationName(orgId);

                    }

                    person.ForeName = "";
                    person.Title = "";

                    _conflictCheck.Person = person;

                    organisation = new Organisation();
                    organisation.Name = conflictName;
                    _conflictCheck.ClientType = IRIS.Law.Services.Pms.Client.ClientType.Organisation;

                    Address address = new Address();
                    address.Line1 = GetAddress(memId, orgId);
                    address.Line3 = "";
                    address.PostCode = "";
                    _conflictCheck.Organisation = organisation;
                    _conflictCheck.Address = address;
                    ConflictCheckStandardReturnValue returnValue = _conflictCheck.PerformConflictCheck();
                    if (returnValue.Success)
                    {
                        //Display conflict check screen if conflict is found
                        if (returnValue.IsConflict)
                        {
                            _wizardAddAssociationsForMatter.Visible = false;
                            _tblConflictCheck.Visible = true;
                            _conflictCheck.ReturnConflictCheck = returnValue;
                            _conflictCheck.BindConflictCheckGridView();
                        }
                        canSave = !returnValue.IsConflict;
                    }
                    else
                    {
                        throw new Exception(returnValue.Message);
                    }
                }
                else
                {
                    canSave = true;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return canSave;
        }
        public ConflictCheckStandardReturnValue ConflictCheck(Guid logonId,
            CollectionRequest collectionRequest,
            IRISLegal.IlbCommon.ContactType clientType,
            Person person,
            Organisation organisation,
            Address addresses,
            List<AdditionalAddressElement> addressInformation, 
            bool checkOnAllRoles)
        {
            ConflictCheckStandardReturnValue returnValue = new ConflictCheckStandardReturnValue();
            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<ConflictCheckStandardItem> dataListCreator = new DataListCreator<ConflictCheckStandardItem>();
                    DsConflictCheckStandard dsConflictCheckStandard = new DsConflictCheckStandard();

                    //Assign all control values to ConflictCheckFields
                    SrvConflictCheckFields conflictFields = new SrvConflictCheckFields();
                    SrvConflictCheck conflictCheck = new SrvConflictCheck();
                    conflictFields.ConflictCheckClientType = clientType;

                    if (person != null)
                    {
                        conflictFields.PersonSurname = person.Surname;
                        conflictFields.PersonName = person.ForeName;
                        conflictFields.PersonTitle = person.Title;
                    }
                    if (organisation != null)
                    {
                        conflictFields.OrgName = organisation.Name;
                    }
                    if (addresses != null)
                    {
                        conflictFields.AddressLine1 = addresses.Line1;
                        conflictFields.AddressLine2 = addresses.Line2;
                        conflictFields.AddressLine3 = addresses.Line3;
                        conflictFields.AddressCountry = addresses.Country;
                        conflictFields.AddressCounty = addresses.County;
                        conflictFields.AddressDepLocality = addresses.DependantLocality;
                        conflictFields.AddressDept = addresses.Department;
                        conflictFields.AddressDXNumber = addresses.DXNumber;
                        conflictFields.AddressDXTown = addresses.DXTown;
                        conflictFields.AddressHouseName = addresses.HouseName;
                        conflictFields.AddressOrgName = addresses.OrganisationName;
                        conflictFields.AddressPoBox = addresses.PostBox;
                        conflictFields.AddressPostCode = addresses.PostCode;
                        conflictFields.AddressStreetNo = addresses.StreetNumber;
                        conflictFields.AddressSubBldg = addresses.SubBuilding;
                        conflictFields.AddressTown = addresses.Town;
                    }

                    if (addressInformation != null)
                    {
                        for (int i = 0; i <= addressInformation.Count - 1; i++)
                        {
                            switch (i)
                            {
                                case 0:
                                    conflictFields.ConflictCheck1 = addressInformation[i].ElementText;
                                    break;
                                case 1:
                                    conflictFields.ConflictCheck2 = addressInformation[i].ElementText;
                                    break;
                                case 2:
                                    conflictFields.ConflictCheck3 = addressInformation[i].ElementText;
                                    break;
                                case 3:
                                    conflictFields.ConflictCheck4 = addressInformation[i].ElementText;
                                    break;
                                case 4:
                                    conflictFields.ConflictCheck5 = addressInformation[i].ElementText;
                                    break;
                                case 5:
                                    conflictFields.ConflictCheck6 = addressInformation[i].ElementText;
                                    break;
                                case 6:
                                    conflictFields.ConflictCheck7 = addressInformation[i].ElementText;
                                    break;
                                case 7:
                                    conflictFields.ConflictCheck8 = addressInformation[i].ElementText;
                                    break;
                                case 8:
                                    conflictFields.ConflictCheck9 = addressInformation[i].ElementText;
                                    break;
                                case 9:
                                    conflictFields.ConflictCheck10 = addressInformation[i].ElementText;
                                    break;
                            }
                        }
                    }

                    //dsConflictCheckStandard = conflictCheck.DoConflictCheck(conflictFields, ApplicationSettings.Instance.DbUid);
                    IRIS.Law.PmsCommonData.DsConflictCheckStandard dsConflictCheckStandard1 = null;
                    IRIS.Law.PmsCommonData.DsConflictCheckAddress dsConflictCheckAddress1 = null;
                    IRIS.Law.PmsCommonData.DsConflictCheckAdditionalAddress dsConflictCheckAdditionalAddress1 = null;
                    IRIS.Law.PmsCommonData.DsConflictCheckExtendedInfo dsConflictCheckExtendedInfo1 = null;
                    var sbSummary = conflictCheck.DoConflictCheck(conflictFields, out dsConflictCheckStandard1, out dsConflictCheckAddress1, out dsConflictCheckAdditionalAddress1, out dsConflictCheckExtendedInfo1, DataConstants.DummyGuid, checkOnAllRoles);

                    if (dsConflictCheckStandard1.uvw_ConflictCheckStandard.Rows.Count > 0 || dsConflictCheckAddress1.uvw_ConflictCheckAddress.Rows.Count > 0 || dsConflictCheckAdditionalAddress1.uvw_ConflictCheckAdditionalAddress.Rows.Count > 0 || dsConflictCheckExtendedInfo1.uvw_ConflictCheckExtendedInfo.Rows.Count > 0)
                    {
                        returnValue.IsConflict = true;
                    }
                    else
                    {
                        returnValue.IsConflict = false;
                    }

                    returnValue.Summary = new StringBuilder(sbSummary);

                    collectionRequest.ForceRefresh = true;

                    //returnValue.IsConflict = conflictCheck.IsConflict;

                    dataListCreator.ReadDataSet += delegate(object Sender, ReadDataSetEventArgs e)
                    {
                        // Perform Sorting on SelectType
                        DataView dvConflictCheck = new DataView(dsConflictCheckStandard1.Tables[0]);
                        dvConflictCheck.Sort = "SelectType asc";

                        DataSet dsSorted = new DataSet();
                        dsSorted.Tables.Add(dvConflictCheck.ToTable());
                        e.DataSet = dsSorted;
                        //e.DataSet = dsConflictCheckStandard1;
                    };

                    returnValue.ConflictCheckStandard = dataListCreator.Create(logonId,
                        // Give the query a name so it can be cached
                        "ConflictCheckStandard",
                        // Tell it the query criteria used so if the cache is accessed
                        // again it knows if it is the same query
                        "",
                        collectionRequest,
                        // Import mappings to map the dataset row fields to the data
                        // list entity properties
                        new ImportMapping[] {
                            new ImportMapping("ClientRef", "cliRef"),
                            new ImportMapping("SelectType", "SelectType"),
                            new ImportMapping("PersonTitle", "PersonTitle"),
                            new ImportMapping("PersonName", "PersonName"),
                            new ImportMapping("PersonSurName", "PersonSurName"),
                            new ImportMapping("AddressStreetNo", "AddressStreetNo"),
                            new ImportMapping("AddressHouseName", "AddressHouseName"),
                            new ImportMapping("AddressLine1", "AddressLine1"),
                            new ImportMapping("OrgName", "OrgName"),
                            new ImportMapping("IsMember", "IsMember")
                            }
                        );
                }
                finally
                {
                    // Remove the logged on user's ApplicationSettings from the
                    // list of concurrent sessions
                    Host.UnloadLoggedOnUser();
                }
            }
            catch (Exception Ex)
            {
                returnValue.Success = false;
                returnValue.Message = "Could not load conflict check fields for the current user." + Ex.Message;
            }

            return returnValue;
        }
 /// <summary>
 /// Saves the service contact.
 /// </summary>
 /// <param name="oHostSecurityToken">HostSecurityToken obtained when security provider of IWS is called</param>
 /// <param name="contactAddress">The contact address.</param>
 /// <param name="additionalElement">The additional element.</param>
 /// <param name="serviceContact">The service contact.</param>
 /// <param name="conflictNoteSummary">The conflict note summary.</param>
 /// <param name="conflictNoteContent">Content of the conflict note.</param>
 /// <returns></returns>
 public ReturnValue SaveServiceContact(HostSecurityToken oHostSecurityToken, Address contactAddress,
                                AdditionalAddressElement[] additionalElement,
                                ServiceContact serviceContact,
                                string conflictNoteSummary,
                                string conflictNoteContent)
 {
     ReturnValue returnValue = null;
     if (Functions.ValidateIWSToken(oHostSecurityToken))
     {
         oContactService = new ContactService();
         returnValue = oContactService.SaveServiceContact(Functions.GetLogonIdFromToken(oHostSecurityToken), contactAddress,
             additionalElement, serviceContact, conflictNoteSummary, conflictNoteContent);
     }
     else
     {
         returnValue = new ReturnValue();
         returnValue.Success = false;
         returnValue.Message = "Invalid Token";
     }
     return returnValue;
 }
        /// <summary>
        /// Saves the service contact.
        /// </summary>
        /// <param name="logonId">Logon id obtained when logging on to the logon service.</param>
        /// <param name="contactAddress">The contact address.</param>
        /// <param name="additionalElement">The additional element.</param>
        /// <param name="serviceContact">The service contact.</param>
        /// <param name="conflictNoteSummary">The conflict note summary.</param>
        /// <param name="conflictNoteContent">Content of the conflict note.</param>
        /// <returns></returns>
        public ReturnValue SaveServiceContact(Guid logonId, Address contactAddress,
                                       AdditionalAddressElement[] additionalElement,
                                       ServiceContact serviceContact,
                                       string conflictNoteSummary,
                                       string conflictNoteContent)
        {
            ReturnValue returnValue = new ReturnValue();

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

                try
                {
                    Functions.RestrictRekoopIntegrationUser(UserInformation.Instance.DbUid);
                    switch (UserInformation.Instance.UserType)
                    {
                        case DataConstants.UserType.Staff:
                            // Can do everything
                            break;
                        case DataConstants.UserType.Client:
                        case DataConstants.UserType.ThirdParty:
                            if (!ApplicationSettings.Instance.IsUser(additionalElement[0].MemberId, additionalElement[0].OrganisationId))
                                throw new Exception("Access denied");
                            break;
                        default:
                            throw new Exception("Access denied");
                    }

                    SrvServiceContact serviceContactSrv = new SrvServiceContact();
                    SrvAddress srvAddress = new SrvAddress();

                    this.SetAddressValue(srvAddress, contactAddress);

                    // Save Additional Address Info to Address Object
                    if (additionalElement != null)
                    {
                        for (int i = 0; i <= 9; i++)
                        {
                            srvAddress.AdditionalInfoElements[i].AddressElementText = additionalElement[i].ElementText;
                        }
                    }
                    serviceContactSrv.Addresses.Add(srvAddress);

                    serviceContactSrv.ServiceId = serviceContact.ServiceId;
                    serviceContactSrv.Person.ForeName = serviceContact.ForeName;
                    serviceContactSrv.Person.Surname = serviceContact.SurName;
                    serviceContactSrv.Person.Title = serviceContact.Title;
                    serviceContactSrv.Position = serviceContact.Position;
                    serviceContactSrv.Person.Sex = serviceContact.Sex;

                    //These two notes fields are mandatory and have defined
                    //default values
                    serviceContactSrv.ConflictNoteSummary = conflictNoteSummary;
                    serviceContactSrv.ConflictNoteContent = conflictNoteContent;

                    string errorMessage;

                    returnValue.Success = serviceContactSrv.Save(out errorMessage);
                    returnValue.Message = errorMessage;
                }
                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>
 /// Saves the address for the contact.
 /// </summary>
 /// <param name="oHostSecurityToken">HostSecurityToken obtained when security provider of IWS is called</param>
 /// <param name="address">The address.</param>
 /// <returns></returns>
 public AddressReturnValue SaveAddress(HostSecurityToken oHostSecurityToken, Address address)
 {
     AddressReturnValue returnValue = null;
     if (Functions.ValidateIWSToken(oHostSecurityToken))
     {
         oContactService = new ContactService();
         returnValue = oContactService.SaveAddress(Functions.GetLogonIdFromToken(oHostSecurityToken), address);
     }
     else
     {
         returnValue = new AddressReturnValue();
         returnValue.Success = false;
         returnValue.Message = "Invalid Token";
     }
     return returnValue;
 }
 /// <summary>
 /// This method adds the Person, Address and Additional Address information
 /// using contact service to create a general contact.
 /// </summary>
 /// <param name="logonId">User logon ID</param>
 /// <param name="contactAddress">Address information for contact</param>
 /// <param name="person">Person information</param>
 /// <param name="additionalElement">Additional Element</param>
 /// <param name="contactType">Individual / Organisation</param>
 /// <param name="organisation">Organisation Information</param>
 /// <param name="conflictNoteSummary">The conflict note summary.</param>
 /// <param name="conflictNoteContent">Content of the conflict note.</param>
 /// <returns>Return Value</returns>
 public ReturnValue SaveGeneralContact(HostSecurityToken oHostSecurityToken,
                                       Address contactAddress,
                                       Person person,
                                       AdditionalAddressElement[] additionalElement,
                                       IRISLegal.IlbCommon.ContactType contactType,
                                       Organisation organisation,
                                       string conflictNoteSummary,
                                       string conflictNoteContent)
 {
     ReturnValue returnValue = null;
     if (Functions.ValidateIWSToken(oHostSecurityToken))
     {
         oContactService = new ContactService();
         returnValue = oContactService.SaveGeneralContact(Functions.GetLogonIdFromToken(oHostSecurityToken), contactAddress, person, additionalElement, contactType, organisation,
             conflictNoteSummary, conflictNoteContent);
     }
     else
     {
         returnValue = new ReturnValue();
         returnValue.Success = false;
         returnValue.Message = "Invalid Token";
     }
     return returnValue;
 }
 public ConflictCheckStandardReturnValue ConflictCheck(HostSecurityToken oHostSecurityToken,
     CollectionRequest collectionRequest,
     IRISLegal.IlbCommon.ContactType clientType,
     Person person,
     Organisation organisation,
     Address addresses,
     List<AdditionalAddressElement> addressInformation,
     bool checkOnAllRoles)
 {
     ConflictCheckStandardReturnValue returnValue = null;
     if (Functions.ValidateIWSToken(oHostSecurityToken))
     {
         oClientService = new ClientService();
         returnValue = oClientService.ConflictCheck(Functions.GetLogonIdFromToken(oHostSecurityToken), collectionRequest,
            clientType, person, organisation, addresses, addressInformation, checkOnAllRoles);
     }
     else
     {
         returnValue = new ConflictCheckStandardReturnValue();
         returnValue.Success = false;
         returnValue.Message = "Invalid Token";
     }
     return returnValue;
 }
 /// <summary>
 /// Update an existing client's address or add a new one
 /// </summary>
 /// <param name="oHostSecurityToken">HostSecurityToken obtained when security provider of IWS is called</param>
 /// <param name="memberId">Member id of the client</param>
 /// <param name="organisationId">Orgainisation id of the client</param>
 /// <param name="address">Address to update or new address to add.
 /// If the Address.Id = 0 then a new address is being added.</param>
 /// <returns></returns>
 public ReturnValue UpdateClientAddress(HostSecurityToken oHostSecurityToken, Guid memberId,
     Guid organisationId, Address address)
 {
     ReturnValue returnValue = null;
     if (Functions.ValidateIWSToken(oHostSecurityToken))
     {
         oClientService = new ClientService();
         returnValue = oClientService.UpdateClientAddress(Functions.GetLogonIdFromToken(oHostSecurityToken), memberId, organisationId, address);
     }
     else
     {
         returnValue = new ReturnValue();
         returnValue.Success = false;
         returnValue.Message = "Invalid Token";
     }
     return returnValue;
 }
        /// <summary>
        /// Get one client
        /// </summary>
        /// <param name="logonId">Logon id obtained when logging on to the Client service</param>
        /// <param name="memberId">Member id</param>
        /// <param name="organisationId">Organisation id</param>
        /// <returns></returns>
        public ClientReturnValue GetClient(Guid logonId, Guid memberId, Guid organisationId)
        {
            ClientReturnValue returnValue = new ClientReturnValue();

            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.ThirdParty:
                            if (!SrvClientCommon.WebAllowedToAccessClient(memberId, organisationId))
                                throw new Exception("Access denied");
                            break;
                        case DataConstants.UserType.Client:
                            if (!ApplicationSettings.Instance.IsUser(memberId, organisationId))
                                throw new Exception("Access denied");
                            break;
                        default:
                            throw new Exception("Access denied");
                    }

                    SrvClient srvClient = new SrvClient();

                    srvClient.Load(memberId, organisationId);

                    Client client = new Client();
                    client.MemberId = srvClient.MemberId;
                    client.OrganisationId = srvClient.OrganisationId;
                    client.PartnerId = srvClient.ClientPartnerId;
                    client.Branch = srvClient.ClientBranch.Trim();
                    client.OpenDate = srvClient.ClientOpenDate;
                    client.PreviousReference = srvClient.PreviousReference.Trim();
                    client.BusinessSourceId = srvClient.SourceId;
                    client.RatingId = srvClient.RatingId;
                    client.IsWebCaseTracking = srvClient.IsClientDoUpload;
                    client.NetPassword = srvClient.ClientNetPassword;
                    client.Group = srvClient.ClientGroup.Trim();
                    client.HOUCN = srvClient.ClientHOUCN.Trim();
                    client.UCN = srvClient.ClientUCN.Trim();
                    client.IsArchived = srvClient.IsClientArchived;
                    client.Type = srvClient.ClientType;
                    client.IsReceivingMarketing = srvClient.IsReceivingMarketing;
                    client.CashCollectionId = srvClient.CliCashCollID;
                    client.TotalLockup = srvClient.CliTotalLockup;
                    client.Reference = srvClient.ClientText.Trim();
                    client.CampaignId = srvClient.CampaignId;

                    returnValue.Client = client;

                    if (srvClient.IsMember)
                    {
                        Person person = new Person();

                        person.MemberId = srvClient.Person.PersonId;
                        person.Title = srvClient.Person.Title;
                        person.ForeName = srvClient.Person.ForeName;
                        person.Surname = srvClient.Person.Surname;
                        client.FullName = IRIS.Law.PmsCommonData.CommonServices.CommonFunctions.MakeFullName(person.Title, person.ForeName, person.Surname);
                        person.MaritalStatusId = srvClient.Person.MaritalId;
                        person.PreviousName = srvClient.Person.PersonPreviousName;
                        person.Occupation = srvClient.Person.PersonOccupation;
                        person.Sex = srvClient.Person.Sex;
                        person.DOB = srvClient.Person.PersonDOB;
                        person.DOD = srvClient.Person.PersonDOD;
                        person.PlaceOfBirth = srvClient.Person.PersonPlaceOfBirth;
                        person.BirthName = srvClient.Person.PersonBirthName;
                        person.SalutationLettterFormal = srvClient.Person.PersonSalletForm;
                        person.SalutationLettterInformal = srvClient.Person.PersonSalutationlettterInformal;
                        person.SalutationLettterFriendly = srvClient.Person.PersonSalLet;
                        person.SalutationEnvelope = srvClient.Person.PersonSalEnv;
                        person.EthnicityId = srvClient.Person.PersonEthnicityId;
                        person.DisabilityId = srvClient.Person.PersonDisability;
                        person.IsInArmedForces = srvClient.Person.PersonInArmedForces;
                        person.ArmedForcesNo = srvClient.Person.PersonArmedForcesNo;
                        person.NINo = srvClient.Person.PersonNINo;

                        returnValue.Person = person;
                    }

                    if (srvClient.IsOrganisation)
                    {
                        Organisation organisation = new Organisation();

                        organisation.OrganisationId = srvClient.Organisation.OrganisationId;
                        organisation.Name = srvClient.Organisation.Name;
                        client.FullName = organisation.Name;
                        organisation.RegisteredName = srvClient.Organisation.RegisteredName;
                        organisation.RegisteredNo = srvClient.Organisation.RegisteredNumber;
                        organisation.VATNo = srvClient.Organisation.VATNumber;
                        organisation.IndustryId = srvClient.Organisation.IndustryId;
                        organisation.SubTypeId = srvClient.Organisation.SubTypesId;

                        returnValue.Organisation = organisation;
                    }

                    returnValue.Addresses = new List<Address>();
                    returnValue.AdditionalAddressElements = new List<AdditionalAddressElement>();
                    foreach (SrvAddress address in srvClient.Addresses)
                    {
                        Address clientAddress = new Address();

                        clientAddress.Id = address.AddressId;
                        clientAddress.TypeId = address.AddressTypeId;
                        clientAddress.Line1 = address.AddressLine1;
                        clientAddress.Line2 = address.AddressLine2;
                        clientAddress.Line3 = address.AddressLine3;
                        clientAddress.Town = address.AddressTown;
                        clientAddress.County = address.AddressCounty;
                        clientAddress.PostCode = address.AddressPostCode;
                        clientAddress.DXTown = address.AddressDXTown;
                        clientAddress.DXNumber = address.AddressDXNumber;
                        clientAddress.Country = address.AddressCountry;
                        clientAddress.IsMailingAddress = address.IsMailingAddress;
                        clientAddress.IsBillingAddress = address.IsBillingAddress;
                        clientAddress.Comment = address.AddressComment;
                        clientAddress.OrganisationName = address.AddressOrgName;
                        clientAddress.Department = address.AddressDepartment;
                        clientAddress.PostBox = address.AddressPostBox;
                        clientAddress.SubBuilding = address.AddressSubBuilding;
                        clientAddress.StreetNumber = address.AddressStreetNumber;
                        clientAddress.HouseName = address.AddressHouseName;
                        clientAddress.DependantLocality = address.AddressDependantLocality;
                        clientAddress.LastVerified = address.AddressLastVerified;

                        returnValue.Addresses.Add(clientAddress);

                        //Get the contact details from the main address
                        if (address.AddressTypeId == 1)
                        {
                            DsAdditionalAddElTypes dsAdditionalAddElTypes = SrvAddressLookup.GetAdditionalAddressElTypes();
                            // integer array which specifies the order of the addAddressElements to display
                            // eg { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 } would display the items as listed in the
                            // table but in the reverse order
                            int[] additionalTypeOrder = new int[11] { 1, 2, 3, 10, 4, 5, 6, 7, 8, 9, 11 };
                            bool addItem = true;

                            for (int x = 0; x < dsAdditionalAddElTypes.AdditionalAddElTypes.Rows.Count; x++)
                            {
                                // Loop through element type table and get the next id type you want
                                for (int i = 0; i < dsAdditionalAddElTypes.AdditionalAddElTypes.Rows.Count; i++)
                                {
                                    int typeId = (int)dsAdditionalAddElTypes.AdditionalAddElTypes[i].AddElTypeID;
                                    if (typeId == additionalTypeOrder[x])
                                    {
                                        string typeText = (string)dsAdditionalAddElTypes.AdditionalAddElTypes[i].AddElTypeText;
                                        string elementText = string.Empty;
                                        string elementComment = string.Empty;

                                        // Loop through member or organisation addEl tables to see if there are any matches.
                                        if (srvClient.IsMember)
                                        {
                                            addItem = true;
                                        }
                                        else
                                        {
                                            if (typeId == 1 || typeId == 7 || typeId == 10)
                                            {
                                                addItem = false;
                                            }
                                            else
                                            {
                                                addItem = true;
                                            }
                                        }

                                        if (addItem)
                                        {
                                            for (int j = 0; j < address.AdditionalInfoElements.Count; j++)
                                            {
                                                if (address.AdditionalInfoElements[j].AddressElTypeId == typeId)
                                                {
                                                    elementText = address.AdditionalInfoElements[j].AddressElementText;
                                                    elementComment = address.AdditionalInfoElements[j].AddressElComment;
                                                    break;
                                                }
                                            }

                                            AdditionalAddressElement additionalAddressElement = new AdditionalAddressElement();
                                            additionalAddressElement.TypeId = typeId;
                                            additionalAddressElement.TypeText = typeText;
                                            additionalAddressElement.ElementText = elementText;
                                            additionalAddressElement.ElementComment = elementComment;
                                            additionalAddressElement.AddressId = address.AddressId;
                                            returnValue.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>
        /// This method adds the Person, Address and Additional Address information
        /// using contact service to create a general contact.
        /// </summary>
        /// <param name="logonId">User logon ID</param>
        /// <param name="contactAddress">Address information for contact</param>
        /// <param name="person">Person information</param>
        /// <param name="additionalElement">Additional Element</param>
        /// <param name="contactType">Individual / Organisation</param>
        /// <param name="organisation">Organisation Information</param>
        /// <param name="conflictNoteSummary">The conflict note summary.</param>
        /// <param name="conflictNoteContent">Content of the conflict note.</param>
        /// <returns>Return Value</returns>
        public ReturnValue SaveGeneralContact(Guid logonId,
                                              Address contactAddress,
                                              Person person,
                                              AdditionalAddressElement[] additionalElement,
                                              IRISLegal.IlbCommon.ContactType contactType,
                                              Organisation organisation,
                                              string conflictNoteSummary,
                                              string conflictNoteContent)
        {
            ReturnValue returnValue = new ReturnValue();

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

                try
                {
                    Functions.RestrictRekoopIntegrationUser(UserInformation.Instance.DbUid);
                    switch (UserInformation.Instance.UserType)
                    {
                        case DataConstants.UserType.Staff:
                            // Can do everything
                            break;
                        case DataConstants.UserType.Client:
                        case DataConstants.UserType.ThirdParty:
                            if (!ApplicationSettings.Instance.IsUser(additionalElement[0].MemberId, additionalElement[0].OrganisationId))
                                throw new Exception("Access denied");
                            break;
                        default:
                            throw new Exception("Access denied");
                    }

                    SrvContact contactService = new SrvContact();
                    SrvAddress srvAddress = new SrvAddress();

                    srvAddress.AddressTypeId = Convert.ToInt32(DataConstants.SystemAddressTypes.Main);
                    srvAddress.AddressStreetNumber = contactAddress.StreetNumber;
                    srvAddress.AddressPostCode = contactAddress.PostCode;
                    srvAddress.AddressHouseName = contactAddress.HouseName;
                    srvAddress.AddressLine1 = contactAddress.Line1;
                    srvAddress.AddressLine2 = contactAddress.Line2;
                    srvAddress.AddressLine3 = contactAddress.Line3;
                    srvAddress.AddressTown = contactAddress.Town;
                    srvAddress.AddressCounty = contactAddress.County;
                    srvAddress.AddressCountry = contactAddress.Country;
                    srvAddress.AddressDXTown = contactAddress.DXTown;
                    srvAddress.AddressDXNumber = contactAddress.DXNumber;
                    srvAddress.IsMailingAddress = contactAddress.IsMailingAddress;
                    srvAddress.IsBillingAddress = contactAddress.IsBillingAddress;

                    srvAddress.AddressOrgName = contactAddress.OrganisationName;
                    srvAddress.AddressComment = contactAddress.Comment;
                    srvAddress.AddressDepartment = contactAddress.Department;
                    srvAddress.AddressPostBox = contactAddress.PostBox;
                    srvAddress.AddressSubBuilding = contactAddress.SubBuilding;
                    srvAddress.AddressStreetNumber = contactAddress.StreetNumber;
                    srvAddress.AddressDependantLocality = contactAddress.DependantLocality;
                    srvAddress.AddressLastVerified = contactAddress.LastVerified;

                    // Save Additional Address Info to Address Object
                    if (additionalElement != null)
                    {
                        for (int i = 0; i <= 9; i++)
                        {
                            srvAddress.AdditionalInfoElements[i].AddressElementText = additionalElement[i].ElementText;
                        }
                    }

                    contactService.Addresses.Add(srvAddress);
                    contactService.ContactType = contactType;

                    if (contactService.ContactType == IRISLegal.IlbCommon.ContactType.Individual)
                    {
                        //Person Information for Individual contact
                        contactService.Person.Surname = person.Surname;
                        contactService.Person.ForeName = person.ForeName;
                        contactService.Person.Title = person.Title;
                    }
                    else
                    {
                        contactService.Organisation.Name = organisation.Name;
                    }

                    contactService.ConflictNoteSummary = conflictNoteSummary;
                    contactService.ConflictNoteContent = conflictNoteContent;

                    string errorMessage;

                    returnValue.Success = contactService.Save(out errorMessage);
                    returnValue.Message = errorMessage;
                }
                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 address.
        /// </summary>
        /// <returns></returns>
        private Address GetAddress()
        {
            Address address = new Address();
            if (_hfAddressId.Value != string.Empty)
            {
                address.Id = Convert.ToInt32(_hfAddressId.Value);
            }
            if (_hfAddressTypeId.Value != string.Empty)
            {
                address.TypeId = Convert.ToInt32(_hfAddressTypeId.Value);
            }
            address.StreetNumber = _txtHouseNumber.Text.Trim();
            address.PostCode = _txtPostcode.Text.Trim();
            address.HouseName = _txtHouseName.Text.Trim();
            address.Line1 = _txtAddress1.Text.Trim();
            address.Line2 = _txtAddress2.Text.Trim();
            address.Line3 = _txtAddress3.Text.Trim();
            address.Town = _txtTown.Text.Trim();
            address.County = _txtCounty.Text.Trim();
            address.Country = _txtCountry.Text.Trim();
            address.DXNumber = _txtDXAddress1.Text.Trim();
            address.DXTown = _txtDXAddress2.Text.Trim();
            address.IsMailingAddress = _chkMailAddress.Checked;
            address.IsBillingAddress = _chkBillAddress.Checked;
            address.OrganisationName = _txtOrganisation.Text.Trim();
            address.Department = _txtDepartment.Text.Trim();
            address.PostBox = _txtPOBox.Text.Trim();
            address.SubBuilding = _txtSubBuildingName.Text.Trim();
            address.DependantLocality = _txtDeptLoc.Text.Trim();
            address.Comment = _txtComment.Text.Trim();
            if (_ccLastVerifiedDate.DateText != "")
            {
                address.LastVerified = Convert.ToDateTime(_ccLastVerifiedDate.DateText.Trim());
            }
            else
            {
                address.LastVerified = DataConstants.BlankDate;
            }

            return address;
        }
        /// <summary>
        /// Adds a new service.
        /// </summary>
        /// <param name="logonId">Logon id obtained when logging on to the logon service.</param>
        /// <param name="serviceAddress">The service address.</param>
        /// <param name="serviceAdditionalElement">The service additional element.</param>
        /// <param name="serviceInfo">The service info.</param>
        /// <param name="serviceContactInfo">The service contact info.</param>
        /// <param name="serviceContactAddress">The service contact address.</param>
        /// <param name="ServiceContactAdditionalElement">The service contact additional element.</param>
        /// <param name="conflictNoteSummary">The conflict note summary.</param>
        /// <param name="conflictNoteContent">Content of the conflict note.</param>
        /// <returns></returns>
        public ReturnValue SaveService(Guid logonId, Address serviceAddress,
                                       AdditionalAddressElement[] serviceAdditionalElement,
                                       ServiceInfo serviceInfo,
                                       ServiceContact serviceContactInfo,
                                       Address serviceContactAddress,
                                       AdditionalAddressElement[] ServiceContactAdditionalElement,
                                       string conflictNoteSummary,
                                       string conflictNoteContent)
        {
            ReturnValue returnValue = new ReturnValue();

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

                try
                {
                    Functions.RestrictRekoopIntegrationUser(UserInformation.Instance.DbUid);
                    switch (UserInformation.Instance.UserType)
                    {
                        case DataConstants.UserType.Staff:
                            // Can do everything
                            break;
                        case DataConstants.UserType.Client:
                        case DataConstants.UserType.ThirdParty:
                            if (!ApplicationSettings.Instance.IsUser(serviceAdditionalElement[0].MemberId, serviceAdditionalElement[0].OrganisationId))
                                throw new Exception("Access denied");
                            break;
                        default:
                            throw new Exception("Access denied");
                    }

                    SrvService service = new SrvService();
                    SrvAddress srvAddress = new SrvAddress();

                    this.SetAddressValue(srvAddress, serviceAddress);

                    // Save Additional Address Info to Address Object
                    if (serviceAdditionalElement != null)
                    {
                        for (int i = 0; i <= 9; i++)
                        {
                            srvAddress.AdditionalInfoElements[i].AddressElementText = serviceAdditionalElement[i].ElementText;
                        }
                    }
                    service.Addresses.Add(srvAddress);
                    service.Name = serviceInfo.ServiceName;
                    service.NetId = SrvServiceCommon.GenerateNumericPassword(6);
                    service.NetPassword = SrvServiceCommon.GenerateStringPassword(10);
                    service.Organisation.IndustryId = serviceInfo.IndustryId;

                    service.Addresses[0].AddressTypeId = Convert.ToInt32(DataConstants.SystemAddressTypes.Main);
                    service.Addresses[0].MemberId = DataConstants.DummyGuid;
                    service.Addresses[0].OrganisationId = DataConstants.DummyGuid;

                    service.ServiceContact[0].Description = serviceContactInfo.Description;
                    service.ServiceContact[0].Position = serviceContactInfo.Position;
                    service.ServiceContact[0].Person.ForeName = serviceContactInfo.ForeName;
                    service.ServiceContact[0].Person.Surname = serviceContactInfo.SurName;
                    service.ServiceContact[0].Person.Title = serviceContactInfo.Title;
                    service.ServiceContact[0].Person.Sex = serviceContactInfo.Sex;
                    service.ServiceContact[0].ConflictNoteContent = conflictNoteContent;
                    service.ServiceContact[0].ConflictNoteSummary = conflictNoteSummary;

                    SrvAddress contactAddress = new SrvAddress();
                    this.SetAddressValue(contactAddress, serviceContactAddress);

                    // Save Additional Address Info to Address Object
                    if (ServiceContactAdditionalElement != null)
                    {
                        for (int i = 0; i <= 9; i++)
                        {
                            contactAddress.AdditionalInfoElements[i].AddressElementText = ServiceContactAdditionalElement[i].ElementText;
                        }
                    }

                    service.ServiceContact[0].Addresses.Add(contactAddress);
                    service.ServiceContact[0].Addresses[0].MemberId = DataConstants.DummyGuid;
                    service.ServiceContact[0].Addresses[0].OrganisationId = DataConstants.DummyGuid;

                    string errorMessage;

                    returnValue.Success = service.Save(out errorMessage);
                    returnValue.Message = errorMessage;
                }
                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>
        /// Checks if the address has been modified and updates the address in the session.
        /// </summary>
        private void CheckForModifiedAddress()
        {
            if (_ucAddress.IsDataChanged)
            {
                //Store the current address in the session before loading the new address
                List<Address> clientAddresses = (List<Address>)Session[SessionName.ClientAddresses];
                Address currentAddress = _ucAddress.Address;

                Address oldBillingAddress = new Address();
                Address oldMailingAddress = new Address();

                int oldBillingAddressId = (int)Session[SessionName.ClientBillingAddressId];
                int oldMailingAddressId = (int)Session[SessionName.ClientMailingAddressId];

                for (int i = 0; i < clientAddresses.Count; i++)
                {
                    if (clientAddresses[i].Id == oldBillingAddressId)
                    {
                        oldBillingAddress = clientAddresses[i];
                    }

                    if (clientAddresses[i].Id == oldMailingAddressId)
                    {
                        oldMailingAddress = clientAddresses[i];
                    }

                    if (clientAddresses[i].TypeId == currentAddress.TypeId)
                    {
                        int addressId = clientAddresses[i].Id;
                        clientAddresses[i] = currentAddress;
                        clientAddresses[i].Id = addressId;

                        if (clientAddresses[i].IsBillingAddress == true)
                        {
                            Session[SessionName.ClientBillingAddressId] = addressId;
                        }

                        if (clientAddresses[i].IsMailingAddress == true)
                        {
                            Session[SessionName.ClientMailingAddressId] = addressId;
                        }

                        //Add the address type id to the list of addresses that have been modified
                        //Only those addresses will be updated at the time of save
                        List<string> updatedAddresses = (List<string>)ViewState[UpdatedAddresses];
                        if (!updatedAddresses.Contains(currentAddress.TypeId.ToString()))
                        {
                            updatedAddresses.Add(currentAddress.TypeId.ToString());
                        }

                        // Check if we need to update the old Billing or Mailing Address too
                        if (oldBillingAddressId != (int)Session[SessionName.ClientBillingAddressId] && oldBillingAddressId != 0)
                        {
                            updatedAddresses.Add(oldBillingAddress.TypeId.ToString());
                        }

                        if (oldMailingAddressId != (int)Session[SessionName.ClientMailingAddressId] && oldMailingAddressId != 0)
                        {
                            updatedAddresses.Add(oldMailingAddress.TypeId.ToString());
                        }

                        break;
                    }
                }
                _ucAddress.IsDataChanged = false;
            }
        }
        /// <summary>
        /// Sets the address value.
        /// </summary>
        /// <param name="serviceAddress">The service address.</param>
        /// <param name="controlAddress">The control address.</param>
        private void SetAddressValue(SrvAddress serviceAddress, Address controlAddress)
        {
            if (controlAddress != null)
            {
                serviceAddress.AddressTypeId = (int)(DataConstants.SystemAddressTypes.Main);
                serviceAddress.AddressStreetNumber = controlAddress.StreetNumber;
                serviceAddress.AddressPostCode = controlAddress.PostCode;
                serviceAddress.AddressHouseName = controlAddress.HouseName;
                serviceAddress.AddressLine1 = controlAddress.Line1;
                serviceAddress.AddressLine2 = controlAddress.Line2;
                serviceAddress.AddressLine3 = controlAddress.Line3;
                serviceAddress.AddressTown = controlAddress.Town;
                serviceAddress.AddressCounty = controlAddress.County;
                serviceAddress.AddressCountry = controlAddress.Country;
                serviceAddress.AddressDXTown = controlAddress.DXTown;
                serviceAddress.AddressDXNumber = controlAddress.DXNumber;
                serviceAddress.IsMailingAddress = controlAddress.IsMailingAddress;
                serviceAddress.IsBillingAddress = controlAddress.IsBillingAddress;

                serviceAddress.AddressOrgName = controlAddress.OrganisationName;
                serviceAddress.AddressComment = controlAddress.Comment;
                serviceAddress.AddressDepartment = controlAddress.Department;
                serviceAddress.AddressPostBox = controlAddress.PostBox;
                serviceAddress.AddressSubBuilding = controlAddress.SubBuilding;
                serviceAddress.AddressStreetNumber = controlAddress.StreetNumber;
                serviceAddress.AddressDependantLocality = controlAddress.DependantLocality;
                serviceAddress.AddressLastVerified = controlAddress.LastVerified;
            }
        }
        /// <summary>
        /// Displays the address details for the selected address type.
        /// </summary>
        private void DisplayAddressDetails()
        {
            try
            {
                List<Address> clientAddresses = null;
                int clientMailingAddressId = 0;
                int clientBillingAddressId = 0;

                Address currentAddress = null;
                if (!IsPostBack)
                {
                    GetAddressTypes();
                    //Store the addresses in a list so that we can add items if necessary
                    clientAddresses = new List<Address>();
                    foreach (Address address in _clientReturnValue.Addresses)
                    {
                        clientAddresses.Add(address);
                        if (address.IsBillingAddress)
                        {
                            clientBillingAddressId = address.Id;
                        }
                        if (address.IsMailingAddress)
                        {
                            clientMailingAddressId = address.Id;
                        }
                    }
                    Session[SessionName.ClientAddresses] = clientAddresses;
                    Session[SessionName.ClientBillingAddressId] = clientBillingAddressId;
                    Session[SessionName.ClientMailingAddressId] = clientMailingAddressId;

                }
                else
                {
                    clientAddresses = (List<Address>)Session[SessionName.ClientAddresses];
                }

                //Get the current selected address type and display the address
                foreach (Address address in clientAddresses)
                {
                    if (address.TypeId == Convert.ToInt32(_ddlAddressType.SelectedValue))
                    {
                        currentAddress = address;
                        break;
                    }
                }
                //If an address exists then display it..
                if (currentAddress != null)
                {
                    List<string> updatedAddresses = (List<string>)ViewState[UpdatedAddresses];
                    _ucAddress.Address = currentAddress;
                    _ucAddress.IsDataChanged = updatedAddresses.Contains(currentAddress.TypeId.ToString());
                    _ucAddress.DataBind();
                }
                else
                {
                    //No address exists for the current type, so create a new one
                    currentAddress = new Address();
                    currentAddress.LastVerified = DataConstants.BlankDate;
                    currentAddress.TypeId = Convert.ToInt32(_ddlAddressType.SelectedValue);
                    clientAddresses.Add(currentAddress);
                    _ucAddress.Address = currentAddress;
                    _ucAddress.IsDataChanged = false;
                    _ucAddress.DataBind();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// Displays the address details for the selected address type.
        /// </summary>
        private void DisplayAddressDetails()
        {
            try
            {
                List<Address> clientAddresses = null;
                Address currentAddress = null;
                if (_addressSearchReturnValue != null)
                {
                    //Store the addresses in a list so that we can add items if necessary
                    clientAddresses = new List<Address>();
                    foreach (Address address in _addressSearchReturnValue.Addresses.Rows)
                    {
                        clientAddresses.Add(address);
                    }
                    Session[SessionName.ClientAddresses] = clientAddresses;
                }
                else
                {
                    clientAddresses = (List<Address>)Session[SessionName.ClientAddresses];
                }

                //Get the current selected address type and display the address
                foreach (Address address in clientAddresses)
                {
                    if (address.TypeId == Convert.ToInt32(_ddlAddressType.SelectedValue))
                    {
                        currentAddress = address;
                        break;
                    }
                }
                //If an address exists then display it..
                if (currentAddress != null)
                {
                    _ucAddress.Address = currentAddress;
                    _ucAddress.DataBind();
                    if (currentAddress.AdditionalAddressElements != null)
                    {
                        _aadContactInfo.AdditionalDetails = currentAddress.AdditionalAddressElements;
                        _aadContactInfo.ClearFields();
                        _aadContactInfo.DataBind();
                        _aadContactInfo.DisableFields();
                    }
                }
                else
                {
                    //No address exists for the current type, so create a new one
                    currentAddress = new Address();
                    currentAddress.LastVerified = DataConstants.BlankDate;
                    currentAddress.TypeId = Convert.ToInt32(_ddlAddressType.SelectedValue);
                    clientAddresses.Add(currentAddress);
                    _ucAddress.Address = currentAddress;
                    _ucAddress.IsDataChanged = false;
                    _ucAddress.DataBind();
                    if (currentAddress.AdditionalAddressElements != null)
                    {
                        _aadContactInfo.AdditionalDetails = currentAddress.AdditionalAddressElements;
                        _aadContactInfo.ClearFields();
                        _aadContactInfo.DataBind();
                        _aadContactInfo.DisableFields();
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// Update an existing client's address or add a new one
        /// </summary>
        /// <param name="logonId">Logon id obtained when logging on to the logon service</param>
        /// <param name="memberId">Member id of the client</param>
        /// <param name="organisationId">Orgainisation id of the client</param>
        /// <param name="address">Address to update or new address to add.
        /// If the Address.Id = 0 then a new address is being added.</param>
        /// <returns></returns>
        public ReturnValue UpdateClientAddress(Guid logonId, Guid memberId,
            Guid organisationId, Address address)
        {
            ReturnValue returnValue = new ReturnValue();

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

                try
                {
                    Functions.RestrictRekoopIntegrationUser(UserInformation.Instance.DbUid);
                    switch (UserInformation.Instance.UserType)
                    {
                        case DataConstants.UserType.Staff:
                            // Can do everything
                            break;
                        case DataConstants.UserType.Client:
                            if (!ApplicationSettings.Instance.IsUser(memberId, organisationId))
                                throw new Exception("Access denied");
                            break;
                        case DataConstants.UserType.ThirdParty:
                            throw new Exception("Access denied");
                        default:
                            throw new Exception("Access denied");
                    }

                    SrvClient srvClient = new SrvClient();

                    srvClient.Load(memberId, organisationId);

                    SrvAddress srvAddress = null;

                    if (address.Id != 0)
                    {
                        // Updating an existing address so check it exists on this client
                        foreach (SrvAddress addr in srvClient.Addresses)
                        {
                            if (addr.AddressId == address.Id)
                            {
                                // Found it
                                srvAddress = addr;
                                break;
                            }
                        }

                        if (srvAddress == null)
                            throw new Exception("Address does not exist for client");
                    }
                    else
                    {
                        // A new address is being added
                        srvAddress = new SrvAddress();

                        srvAddress.MemberId = memberId;
                        srvAddress.OrganisationId = organisationId;
                    }

                    srvAddress.AddressTypeId = address.TypeId;
                    srvAddress.AddressLine1 = address.Line1;
                    // TODO more address fields

                    string errorMessage;

                    returnValue.Success = srvAddress.Save(out errorMessage);
                    returnValue.Message = errorMessage;
                }
                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;
        }