/// <summary>
        /// Set the values for additional details
        /// </summary>
        /// <returns></returns>
        public AdditionalAddressElement[] GetAdditionalDetails()
        {
            AdditionalAddressElement[] addressDetails = new AdditionalAddressElement[10];

            #region Set Second Person's Additional Address Information
            for (int i = 0; i <= 9; i++)
            {
                addressDetails[i] = new AdditionalAddressElement();
                switch (i)
                {
                    case 0:
                        addressDetails[0].ElementText = _txtHomeTelephone.Text;
                        break;
                    case 1:
                        addressDetails[1].ElementText = _txtWorkTel1.Text;
                        break;
                    case 2:
                        addressDetails[2].ElementText = _txtWorkTel2.Text;
                        break;
                    case 3:
                        addressDetails[3].ElementText = _txtDDI.Text;
                        break;
                    case 4:
                        addressDetails[4].ElementText = _txtMob1.Text;
                        break;
                    case 5:
                        addressDetails[5].ElementText = _txtMob2.Text;
                        break;
                    case 6:
                        addressDetails[6].ElementText = _txtFax.Text;
                        break;
                    case 7:
                        addressDetails[7].ElementText = _txtHomeEmail.Text;
                        break;
                    case 8:
                        addressDetails[8].ElementText = _txtWorkEmail.Text;
                        break;
                    case 9:
                        addressDetails[9].ElementText = _txtURL.Text;
                        break;
                }
            }
            #endregion
            
            return addressDetails;
        }
        /// <summary>
        /// Get the address for the specified contact  
        /// </summary>
        /// <param name="logonId"></param>
        /// <param name="collectionRequest"></param>
        /// <param name="criteria"></param>
        /// <returns></returns>
        public AddressSearchReturnValue GetContactAddresses(Guid logonId, CollectionRequest collectionRequest,
                                        AddressSearchCriteria criteria)
        {
            AddressSearchReturnValue returnValue = new AddressSearchReturnValue();
            SrvAddress srvAddress;

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

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

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

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

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

                    int intCtr;
                    foreach (Address address in returnValue.Addresses.Rows)
                    {
                        srvAddress = new SrvAddress();
                        srvAddress.MemberId = criteria.MemberId;
                        srvAddress.OrganisationId = criteria.OrganisationId;
                        srvAddress.Load(address.Id);
                        address.AdditionalAddressElements = new List<AdditionalAddressElement>();
                        for (intCtr = 0; intCtr < srvAddress.AdditionalInfoElements.Count; intCtr++)
                        {
                            AdditionalAddressElement additionalAddressElement = new AdditionalAddressElement();
                            additionalAddressElement.ElementComment = srvAddress.AdditionalInfoElements[intCtr].AddressElComment;
                            additionalAddressElement.ElementText = srvAddress.AdditionalInfoElements[intCtr].AddressElementText;
                            additionalAddressElement.TypeId = srvAddress.AdditionalInfoElements[intCtr].AddressElTypeId;
                            address.AdditionalAddressElements.Add(additionalAddressElement);
                        }
                    }
                }
                finally
                {
                    // Remove the logged on user's ApplicationSettings from the
                    // list of concurrent sessions
                    Host.UnloadLoggedOnUser();
                }
            }
            catch (System.Data.SqlClient.SqlException)
            {
                returnValue.Success = false;
                returnValue.Message = Functions.SQLErrorMessage;
            }
            catch (Exception Ex)
            {
                returnValue.Success = false;
                returnValue.Message = Ex.Message;
            }

            return returnValue;
        }
        /// <summary>
        /// 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>
        /// 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>
        /// 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>
        /// Saves the additional address element.
        /// </summary>
        /// <param name="logonId">Logon id obtained when logging on to the logon service.</param>
        /// <param name="additionalElement">The additional element.</param>
        /// <returns></returns>
        public ReturnValue SaveAdditionalAddressElement(Guid logonId,
                                        AdditionalAddressElement additionalElement)
        {
            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.MemberId, additionalElement.OrganisationId))
                                throw new Exception("Access denied");
                            break;
                        default:
                            throw new Exception("Access denied");
                    }

                    SrvAddressAdditionalInfoElement srvAddressAdditionalInfoElement = new SrvAddressAdditionalInfoElement();

                    srvAddressAdditionalInfoElement.Load(additionalElement.MemberId, additionalElement.OrganisationId, additionalElement.TypeId);

                    srvAddressAdditionalInfoElement.AddressId = additionalElement.AddressId;
                    srvAddressAdditionalInfoElement.AddressElementText = additionalElement.ElementText;
                    srvAddressAdditionalInfoElement.AddressElComment = additionalElement.ElementComment;

                    string errorMessage;

                    returnValue.Success = srvAddressAdditionalInfoElement.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 associations for the matter.
        /// </summary>
        /// <param name="logonId">Logon id obtained when logging on to the logon service.</param>
        /// <param name="collectionRequest">The collection request.</param>
        /// <param name="criteria">The criteria.</param>
        /// <returns></returns>
        public MatterAssociationReturnValue MatterAssociationSearch(Guid logonId, CollectionRequest collectionRequest,
                                                                    MatterAssociationSearchCriteria criteria)
        {
            MatterAssociationReturnValue returnValue = new MatterAssociationReturnValue();

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

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

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

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

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

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

                    DataSet dsMatterAssociations;

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

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

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

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

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

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

                            }
                        }
                    });

                    returnValue.Associations = matterAssociations;
                }
                finally
                {
                    Host.UnloadLoggedOnUser();
                }
            }
            catch (System.Data.SqlClient.SqlException)
            {
                returnValue.Success = false;
                returnValue.Message = Functions.SQLErrorMessage;
            }
            catch (Exception ex)
            {
                returnValue.Success = false;
                returnValue.Message = ex.Message;
            }
            return returnValue;
        }
 /// <summary>
 /// 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>
 /// 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;
 }
 /// <summary>
 /// Saves the additional address element.
 /// </summary>
 /// <param name="oHostSecurityToken">HostSecurityToken obtained when security provider of IWS is called</param>
 /// <param name="additionalElement">The additional element.</param>
 /// <returns></returns>
 public ReturnValue SaveAdditionalAddressElement(HostSecurityToken oHostSecurityToken,
                                 AdditionalAddressElement additionalElement)
 {
     ReturnValue returnValue = null;
     if (Functions.ValidateIWSToken(oHostSecurityToken))
     {
         oContactService = new ContactService();
         returnValue = oContactService.SaveAdditionalAddressElement(Functions.GetLogonIdFromToken(oHostSecurityToken), additionalElement);
     }
     else
     {
         returnValue = new ReturnValue();
         returnValue.Success = false;
         returnValue.Message = "Invalid Token";
     }
     return returnValue;
 }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="logonId"></param>
        /// <param name="collectionRequest"></param>
        /// <param name="criteria"></param>
        /// <returns></returns>
        public PartnerSearchReturnValue PartnerSearch(Guid logonId, CollectionRequest collectionRequest,
            PartnerSearchCriteria criteria)
        {
            PartnerSearchReturnValue returnValue = new PartnerSearchReturnValue();

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

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

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

                    // Declare an inline event (annonymous delegate) to read the
                    // dataset if it is required
                    dataListCreator.ReadDataSet += delegate(object Sender, ReadDataSetEventArgs e)
                    {
                        // TODO: Does not use criteria: Name
                        e.DataSet = SrvEarnerLookup.GetPartnerLookup(criteria.IncludeArchived);

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

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

                    DataSet dsPartnerList;

                    partnerList.Rows.ForEach(delegate(PartnerSearchItem item)
                    {
                        dsPartnerList = SrvAddressLookup.GetMemberAddresses(item.PartnerId);
                        SrvAddress srvAddress;
                        int intCtr;

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

                            srvAddress = new SrvAddress();
                            srvAddress.MemberId = item.PartnerId;
                            srvAddress.Load(int.Parse(dr["addressId"].ToString()));

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

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

                            }
                        }
                    });

                    returnValue.Partners = partnerList;
                }
                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;
        }
        protected void _grdContactDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            ContactServiceClient contactService = null;

            try
            {
                TextBox txtElementText = (TextBox)_grdContactDetails.Rows[e.RowIndex].FindControl("_txtElementText");
                contactService = new ContactServiceClient();
                AdditionalAddressElement element = new AdditionalAddressElement();

                Guid _memberId = DataConstants.DummyGuid;
                Guid _organisationId = DataConstants.DummyGuid;

                if (Session[SessionName.MemberId] != null && Session[SessionName.OrganisationId] != null)
                {
                    _memberId = (Guid)Session[SessionName.MemberId];
                    _organisationId = (Guid)Session[SessionName.OrganisationId];
                }

                if (_logonSettings.UserType == (int)DataConstants.UserType.ThirdParty && Request.QueryString["mydetails"] == "true")
                {
                    _memberId = _logonSettings.MemberId;
                    _organisationId = _logonSettings.OrganisationId;
                }

                element.MemberId = _memberId;
                element.OrganisationId = _organisationId;
                element.TypeId = (int)_grdContactDetails.DataKeys[e.RowIndex].Values["TypeId"];
                element.ElementText = txtElementText.Text.Trim();
                element.ElementComment = ((TextBox)_grdContactDetails.Rows[e.RowIndex].FindControl("_txtElementComment")).Text.Trim();
                element.AddressId = (int)_grdContactDetails.DataKeys[e.RowIndex].Values["AddressId"];

                ReturnValue returnValue = contactService.SaveAdditionalAddressElement(((LogonReturnValue)Session[SessionName.LogonSettings]).LogonId, element);
                if (returnValue.Success)
                {
                    //update the modified additional info in the session
                    AdditionalAddressElement[] additionalAddressElements = (AdditionalAddressElement[])Session[SessionName.ContactDetails];
                    for (int i = 0; i < additionalAddressElements.Length; i++)
                    {
                        if (additionalAddressElements[i].TypeId == element.TypeId)
                        {
                            additionalAddressElements[i].ElementText = element.ElementText;
                            additionalAddressElements[i].ElementComment = element.ElementComment;
                            break;
                        }
                    }

                    _messageCssClass = "successMessage";
                    _message = "Edit successful";
                }
                else
                {
                    _messageCssClass = "errorMessage";
                    _message = returnValue.Message;
                }

                _grdContactDetails.EditIndex = -1;
                DisplayContactDetails();
            }
            catch (Exception ex)
            {
                _messageCssClass = "errorMessage";
                _message = ex.Message;
            }
            finally
            {
                if (contactService != null)
                {
                    if (contactService.State != System.ServiceModel.CommunicationState.Faulted)
                        contactService.Close();
                }

                if (ErrorOccured != null)
                {
                    OnErrorOccured(System.EventArgs.Empty);
                }
            }
        }
        /// <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>
        /// 
        /// </summary>
        /// <param name="isSecondClient"></param>
        /// <returns></returns>
        public ConflictCheckStandardReturnValue PerformConflictCheck()
        {
            ConflictCheckStandardReturnValue dsConflictCheckFields;
            ClientServiceClient clientService = new ClientServiceClient();

            IRIS.Law.WebServiceInterfaces.Contact.AdditionalAddressElement[] addressElementsFirst;
            addressElementsFirst = null;

            if (_additionalAddressDetails != null && _additionalAddressDetails.Length == 10)
            {
                //if (!_isSecondClient || _isSecondClient)
                //{
                addressElementsFirst = new AdditionalAddressElement[10];
                #region Set First Person's and Second Person's Additional Address Information
                for (int i = 0; i <= 9; i++)
                {
                    addressElementsFirst[i] = new AdditionalAddressElement();
                    switch (i)
                    {
                        case 0:
                            addressElementsFirst[0].ElementText = _additionalAddressDetails[0].ElementText;
                            break;
                        case 1:
                            addressElementsFirst[1].ElementText = _additionalAddressDetails[1].ElementText;
                            break;
                        case 2:
                            addressElementsFirst[2].ElementText = _additionalAddressDetails[2].ElementText;
                            break;
                        case 3:
                            addressElementsFirst[3].ElementText = _additionalAddressDetails[3].ElementText;
                            break;
                        case 4:
                            addressElementsFirst[4].ElementText = _additionalAddressDetails[4].ElementText;
                            break;
                        case 5:
                            addressElementsFirst[5].ElementText = _additionalAddressDetails[5].ElementText;
                            break;
                        case 6:
                            addressElementsFirst[6].ElementText = _additionalAddressDetails[6].ElementText;
                            break;
                        case 7:
                            addressElementsFirst[7].ElementText = _additionalAddressDetails[7].ElementText;
                            break;
                        case 8:
                            addressElementsFirst[8].ElementText = _additionalAddressDetails[8].ElementText;
                            break;
                        case 9:
                            addressElementsFirst[9].ElementText = _additionalAddressDetails[9].ElementText;
                            break;
                    }
                    //}
                #endregion
                }
            }

            CollectionRequest collectionRequest = new CollectionRequest();
            collectionRequest.StartRow = 0;
            dsConflictCheckFields = clientService.ConflictCheck(_logonSettings.LogonId,
                                                                    collectionRequest,
                                                                    _clientType,
                                                                    _person,
                                                                    _organisation,
                                                                    _address,
                                                                    addressElementsFirst,
                                                                    _logonSettings.ConflictCheckRoles
                                                                    );

            return dsConflictCheckFields;
        }