コード例 #1
0
        public override ImportContactsData GetContacts(string fileName, IEnumerable <FieldViewModel> customFields, int jobId, IEnumerable <DropdownValueViewModel> DropdownFields)
        {
            List <RawContact> persons = new List <RawContact>();
            var personCustomFieldData = new List <ImportCustomData>();
            var personPhoneData       = new List <ImportPhoneData>();
            ImportContactsData data   = new ImportContactsData();

            Func <RawContact, bool> ValidateEmail = (c) =>
            {
                /*
                 * If email is not empty or null then validate email
                 * If email is empty/or null then check for legth of first name and lastname
                 */
                if ((!string.IsNullOrEmpty(c.PrimaryEmail) && c.IsValidEmail(c.PrimaryEmail)) ||
                    (string.IsNullOrEmpty(c.PrimaryEmail) && !string.IsNullOrEmpty(c.FirstName) && !string.IsNullOrEmpty(c.LastName)))
                {
                    return(true);
                }
                return(false);
            };

            string soapResult = string.Empty;

            try
            {
                var ftpManager = new FtpService();
                var ftpcontent = ftpManager.GetService(leadAdapterAndAccountMap.RequestGuid);
                var cid        = default(int);
                int.TryParse(ftpcontent.UserName, out cid);
                DateTime lastProcessed = leadAdapterAndAccountMap.LastProcessed == null?DateTime.Now.ToUniversalTime().AddDays(-90) : leadAdapterAndAccountMap.LastProcessed.Value;

                HttpWebRequest request         = CreateWebRequest(ftpcontent.Host);
                XmlDocument    soapEnvelopeXml = new XmlDocument();
                List <string>  hashes          = new List <string>();
                soapEnvelopeXml.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8""?>
                <soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
                  <soap:Body><listLeads xmlns='http://tempuri.org/'><cid xsi:type="" xsd:int"">" + cid + @"</cid><password xsi:type="" xsd:string"">" + ftpcontent.Password + "</password>" +
                                        "</listLeads></soap:Body></soap:Envelope>");
                LeadAdapterRecordStatus status = LeadAdapterRecordStatus.Undefined;

                using (Stream stream = request.GetRequestStream())
                {
                    soapEnvelopeXml.Save(stream);
                }

                using (WebResponse response = request.GetResponse())
                {
                    using (StreamReader rd = new StreamReader(response.GetResponseStream()))
                    {
                        soapResult = rd.ReadToEnd();
                        //Console.WriteLine(soapResult);
                    }
                }

                int AccountID = leadAdapterAndAccountMap.AccountID;
                if (!string.IsNullOrWhiteSpace(soapResult))
                {
                    int    startIndex = soapResult.IndexOf("<return xsi:type=\"xsd:string\">") + "<return xsi:type=\"xsd:string\">".Length;
                    int    endIndex   = soapResult.IndexOf("</return>");
                    string newString  = soapResult.Substring(startIndex, endIndex - startIndex);

                    string[] leadsList = Regex.Split(newString, "\r\n|\r|\n");

                    /*The lead's ID 0 |
                     * The lead's name |
                     * The lead's primary email address |
                     * Agent Owner (by IDX assigned Agent ID) |
                     * The date the lead subscribed |
                     * The opt-in status of the lead (y = opted in) |
                     * The disabled status of the lead (y = disabled) |
                     * If the lead account is disabled |
                     * If the lead can login |
                     * If the lead unsubscribed from email updates |
                     * If the lead wants plain text of HTML emails |
                     * The area code of the lead |
                     * The first 3 digits of the lead phone number |
                     * The final 4 digits of the lead phone number |
                     * The lead street address |
                     * The lead city |
                     * The lead state |
                     * The lead zipcode |
                     * The last lead login date |
                     * The last lead update date |
                     * The lead category |
                     * If the lead has been flagged (starred)*/


                    leadsList = leadsList.Where(x => !string.IsNullOrEmpty(x)).ToArray();

                    customFields = customFields.Where(i => i.IsLeadAdapterField && i.StatusId == FieldStatus.Active && i.LeadAdapterType == (byte)LeadAdapterTypes.IDX);

                    foreach (var contact in leadsList)
                    {
                        var guid = Guid.NewGuid();

                        var contactDetails  = contact.Split('|');
                        var disabledstatus  = contactDetails[6];
                        var accountdisabled = contactDetails[7];

                        if (disabledstatus == "y" || accountdisabled == "y" ||
                            DateTime.Compare(lastProcessed, DateTime.Parse(contactDetails[5], CultureInfo.InvariantCulture)) > 0)
                        {
                            continue;
                        }

                        string fullName  = string.Empty;
                        string firstName = string.Empty;
                        string lastName  = string.Empty;
                        if (contactDetails.Length > 1)
                        {
                            fullName = contactDetails[1];
                        }

                        string[] name = fullName.Split(' ');
                        if (name.Length == 1)
                        {
                            firstName = name[0];
                        }
                        else if (name.Length > 1)
                        {
                            for (var i = 0; i < name.Length; i++)
                            {
                                if (i == 0)
                                {
                                    firstName = name[i];
                                }
                                else
                                {
                                    lastName = name[i] + " ";
                                }
                            }
                        }
                        IList <ImportCustomData> contactCustomData = new List <ImportCustomData>();
                        IList <ImportPhoneData>  contactPhoneData  = new List <ImportPhoneData>();
                        ///////////////////////////////////
                        var oldNewValues           = new Dictionary <string, dynamic> {
                        };
                        StringBuilder hash         = new StringBuilder();
                        string        primaryemail = contactDetails.Length > 2 ? contactDetails[2] : string.Empty;
                        IList <Email> emails       = new List <Email>();

                        if (!string.IsNullOrEmpty(primaryemail))
                        {
                            Email email = new Email()
                            {
                                EmailId   = primaryemail,
                                AccountID = AccountID,
                                IsPrimary = true
                            };
                            emails.Add(email);
                            hash.Append("-").Append(primaryemail);
                        }
                        else
                        {
                            hash.Append("-").Append("*****@*****.**");
                        }

                        Person person1 = new Person()
                        {
                            FirstName = firstName,
                            LastName  = lastName,
                            Emails    = emails,
                            AccountID = AccountID
                        };

                        if (string.IsNullOrEmpty(firstName))
                        {
                            hash.Append("-").Append(string.Empty);
                        }
                        else
                        {
                            hash.Append("-").Append(firstName);
                        }

                        if (string.IsNullOrEmpty(lastName))
                        {
                            hash.Append("-").Append(string.Empty);
                        }
                        else
                        {
                            hash.Append("-").Append(lastName);
                        }
                        hash.Append("-").Append(string.Empty);

                        bool IsNotValidContact   = false;
                        bool isDuplicateFromFile = false;

                        if (!IsNotValidContact)
                        {
                            bool duplicateemailcount = hashes.Where(h => h.Contains(primaryemail)).Any();
                            if (!string.IsNullOrEmpty(primaryemail) && duplicateemailcount)
                            {
                                isDuplicateFromFile = true;
                            }
                            else if (!string.IsNullOrEmpty(primaryemail) && !duplicateemailcount)
                            {
                                isDuplicateFromFile = false;
                            }
                            else if (string.IsNullOrEmpty(primaryemail) && hashes.Where(h => h.Contains(hash.ToString())).Any())
                            {
                                isDuplicateFromFile = true;
                            }
                            else
                            {
                                isDuplicateFromFile = false;
                            }
                        }

                        SearchResult <Contact> duplicateResult = new SearchResult <Contact>();
                        if (!IsNotValidContact && isDuplicateFromFile == false)
                        {
                            SearchParameters parameters = new SearchParameters()
                            {
                                AccountId = AccountID
                            };
                            IEnumerable <Contact> duplicateContacts = contactService.CheckIfDuplicate(new CheckContactDuplicateRequest()
                            {
                                Person = person1
                            }).Contacts;
                            duplicateResult = new SearchResult <Contact>()
                            {
                                Results = duplicateContacts, TotalHits = duplicateContacts != null?duplicateContacts.Count() : 0
                            };
                        }


                        if (IsNotValidContact)
                        {
                            status = LeadAdapterRecordStatus.ValidationFailed;
                        }
                        else if (isDuplicateFromFile)
                        {
                            status = LeadAdapterRecordStatus.DuplicateFromFile;
                        }
                        else if (duplicateResult.TotalHits > 0)
                        {
                            status = LeadAdapterRecordStatus.Updated;
                            guid   = duplicateResult.Results.FirstOrDefault().ReferenceId;
                        }
                        else
                        {
                            status = LeadAdapterRecordStatus.Added;
                        }



                        Contact duplicateperson = default(Person);
                        //contact.LeadAdapterRecordStatusId = (byte)status;
                        if (status == LeadAdapterRecordStatus.Updated)
                        {
                            duplicateperson = duplicateResult.Results.FirstOrDefault();
                        }
                        else
                        {
                            duplicateperson = new Person();
                        }


                        ///////////////////////////////////////////////////////////////

                        StringBuilder    CustomFields = new StringBuilder();
                        ImportCustomData customData   = new ImportCustomData();
                        customData.ReferenceID = guid;

                        string elementvalue = string.Empty;
                        string leadsid      = contactDetails[0];
                        if (!string.IsNullOrEmpty(leadsid))
                        {
                            var customfield = customFields.Where(i => i.Title.Replace(" ", string.Empty).ToLower() == "lead'sid(idx)").FirstOrDefault();
                            if (customfield != null)
                            {
                                var customfielddata = duplicateperson.CustomFields == null ? null : duplicateperson.CustomFields.Where(i => i.CustomFieldId == customfield.FieldId).FirstOrDefault();
                                if (customfielddata != null)
                                {
                                    elementvalue = customfielddata.Value;
                                }
                                if (CustomFields.Length == 0)
                                {
                                    CustomFields.Append(customfield.FieldId + "##$##" + (byte)customfield.FieldInputTypeId + "|" + leadsid);
                                }
                                else
                                {
                                    CustomFields.Append("~" + customfield.FieldId + "##$##" + (byte)customfield.FieldInputTypeId + "|" + leadsid);
                                }
                            }

                            customData.FieldID     = customfield.FieldId;
                            customData.FieldTypeID = (int?)customfield.FieldInputTypeId;
                            customData.FieldValue  = leadsid;
                            contactCustomData.Add(customData);

                            oldNewValues.Add("lead's ID", new { OldValue = string.IsNullOrEmpty(elementvalue) ? string.Empty : elementvalue, NewValue = leadsid });
                        }
                        //if (!string.IsNullOrEmpty(fullName))
                        //{
                        //    string oldname = string.Empty;
                        //    if (!string.IsNullOrEmpty(duplicateperson.))
                        //        oldname += duplicateperson.FirstName + " ";
                        //    if (!string.IsNullOrEmpty(duplicateperson.LastName))
                        //        oldname += duplicateperson.LastName;
                        //    oldNewValues.Add("The lead's name", new { OldValue = oldname, NewValue = fullName });
                        //}

                        //if (!string.IsNullOrEmpty(primaryemail))
                        //{
                        //    string oldemail = string.Empty;
                        //    if (duplicateperson.Emails != null && duplicateperson.Emails.Count(i => i.IsPrimary) > 0)
                        //        oldemail = duplicateperson.Emails.SingleOrDefault(i => i.IsPrimary).EmailId;
                        //    oldNewValues.Add("The lead's primary email address", new { OldValue = oldemail, NewValue = primaryemail });
                        //}
                        string agentowner = contactDetails[3];
                        if (!string.IsNullOrEmpty(agentowner))
                        {
                            var customfield = customFields.Where(i => i.Title.Replace(" ", string.Empty).ToLower() == "agentowner(idx)").FirstOrDefault();
                            if (customfield != null)
                            {
                                var customfielddata = duplicateperson.CustomFields == null ? null : duplicateperson.CustomFields.Where(i => i.CustomFieldId == customfield.FieldId).FirstOrDefault();
                                if (customfielddata != null)
                                {
                                    elementvalue = customfielddata.Value;
                                }
                                if (CustomFields.Length == 0)
                                {
                                    CustomFields.Append(customfield.FieldId + "##$##" + (byte)customfield.FieldInputTypeId + "|" + agentowner);
                                }
                                else
                                {
                                    CustomFields.Append("~" + customfield.FieldId + "##$##" + (byte)customfield.FieldInputTypeId + "|" + agentowner);
                                }
                            }
                            customData.FieldID     = customfield.FieldId;
                            customData.FieldTypeID = (int?)customfield.FieldInputTypeId;
                            customData.FieldValue  = agentowner;
                            contactCustomData.Add(customData);

                            oldNewValues.Add("Agent Owner", new { OldValue = string.IsNullOrEmpty(elementvalue) ? string.Empty : elementvalue, NewValue = agentowner });
                        }

                        string leadsubscribeddate = contactDetails[5];
                        if (!string.IsNullOrEmpty(leadsubscribeddate))
                        {
                            var customfield = customFields.Where(i => i.Title.Replace(" ", string.Empty).ToLower() == "thedatetheleadsubscribed(idx)").FirstOrDefault();
                            if (customfield != null)
                            {
                                var customfielddata = duplicateperson.CustomFields == null ? null : duplicateperson.CustomFields.Where(i => i.CustomFieldId == customfield.FieldId).FirstOrDefault();
                                if (customfielddata != null)
                                {
                                    elementvalue = customfielddata.Value;
                                }
                                if (CustomFields.Length == 0)
                                {
                                    CustomFields.Append(customfield.FieldId + "##$##" + (byte)customfield.FieldInputTypeId + "|" + leadsubscribeddate);
                                }
                                else
                                {
                                    CustomFields.Append("~" + customfield.FieldId + "##$##" + (byte)customfield.FieldInputTypeId + "|" + leadsubscribeddate);
                                }
                            }
                            customData.FieldID     = customfield.FieldId;
                            customData.FieldTypeID = (int?)customfield.FieldInputTypeId;
                            customData.FieldValue  = leadsubscribeddate;
                            contactCustomData.Add(customData);

                            oldNewValues.Add("The date the lead subscribed", new { OldValue = string.IsNullOrEmpty(elementvalue) ? string.Empty : elementvalue, NewValue = leadsubscribeddate });
                        }

                        string optinstatusoflead = contactDetails[6];
                        if (!string.IsNullOrEmpty(optinstatusoflead))
                        {
                            var customfield = customFields.Where(i => i.Title.Replace(" ", string.Empty).ToLower() == "theopt-instatusofthelead(idx)").FirstOrDefault();
                            if (customfield != null)
                            {
                                var customfielddata = duplicateperson.CustomFields == null ? null : duplicateperson.CustomFields.Where(i => i.CustomFieldId == customfield.FieldId).FirstOrDefault();
                                if (customfielddata != null)
                                {
                                    elementvalue = customfielddata.Value;
                                }
                                if (CustomFields.Length == 0)
                                {
                                    CustomFields.Append(customfield.FieldId + "##$##" + (byte)customfield.FieldInputTypeId + "|" + optinstatusoflead);
                                }
                                else
                                {
                                    CustomFields.Append("~" + customfield.FieldId + "##$##" + (byte)customfield.FieldInputTypeId + "|" + optinstatusoflead);
                                }
                            }
                            customData.FieldID     = customfield.FieldId;
                            customData.FieldTypeID = (int?)customfield.FieldInputTypeId;
                            customData.FieldValue  = optinstatusoflead;
                            contactCustomData.Add(customData);
                            oldNewValues.Add("The opt-in status of the lead", new { OldValue = string.IsNullOrEmpty(elementvalue) ? string.Empty : elementvalue, NewValue = optinstatusoflead });
                        }

                        string donotemail = contactDetails[9];
                        if (!string.IsNullOrEmpty(donotemail))
                        {
                            var customfield = customFields.Where(i => i.Title.Replace(" ", string.Empty).ToLower() == "iftheleadunsubscribedfromemailupdates(idx)").FirstOrDefault();
                            if (customfield != null)
                            {
                                var customfielddata = duplicateperson.CustomFields == null ? null : duplicateperson.CustomFields.Where(i => i.CustomFieldId == customfield.FieldId).FirstOrDefault();
                                if (customfielddata != null)
                                {
                                    elementvalue = customfielddata.Value;
                                }

                                if (CustomFields.Length == 0)
                                {
                                    CustomFields.Append(customfield.FieldId + "##$##" + (byte)customfield.FieldInputTypeId + "|" + donotemail);
                                }
                                else
                                {
                                    CustomFields.Append("~" + customfield.FieldId + "##$##" + (byte)customfield.FieldInputTypeId + "|" + donotemail);
                                }
                            }
                            customData.FieldID     = customfield.FieldId;
                            customData.FieldTypeID = (int?)customfield.FieldInputTypeId;
                            customData.FieldValue  = donotemail;
                            contactCustomData.Add(customData);
                            oldNewValues.Add("If the lead unsubscribed from email updates", new { OldValue = string.IsNullOrEmpty(elementvalue) ? string.Empty : elementvalue, NewValue = donotemail });
                        }

                        StringBuilder phonedata           = new StringBuilder();
                        string        areacode            = contactDetails.Length > 11 ? contactDetails[11] : string.Empty;
                        string        first3digitsofphone = contactDetails.Length > 12 ? contactDetails[12] : string.Empty;
                        string        last4digitsofphone  = contactDetails.Length > 13 ? contactDetails[13] : string.Empty;

                        string Phone = string.Concat(areacode, first3digitsofphone, last4digitsofphone);
                        if (!string.IsNullOrEmpty(Phone))
                        {
                            //string nonnumericphonenumber = GetNonNumericData(Phone);
                            DropdownValueViewModel drpvalue = DropdownFields.Where(i => i.DropdownValueTypeID == (short)DropdownValueTypes.MobilePhone).FirstOrDefault();
                            var             mobilephone     = default(Phone);
                            ImportPhoneData phoneData       = new ImportPhoneData();
                            phoneData.ReferenceID = guid;
                            if (drpvalue != null && !string.IsNullOrEmpty(Phone))
                            {
                                string nonnumericstring = GetNonNumericData(Phone);
                                if (IsValidPhoneNumberLength(nonnumericstring))
                                {
                                    phonedata.Append(drpvalue.DropdownValueID.ToString() + "|" + nonnumericstring);
                                    phoneData.PhoneType   = (int?)drpvalue.DropdownValueID;
                                    phoneData.PhoneNumber = nonnumericstring;
                                    contactPhoneData.Add(phoneData);
                                }
                            }

                            if (mobilephone != null)
                            {
                                elementvalue = mobilephone.Number;
                            }
                            oldNewValues.Add("Phone number", new { OldValue = string.IsNullOrEmpty(elementvalue) ? string.Empty : elementvalue, NewValue = Phone });
                        }

                        string leadsstreetadress = contactDetails[14];
                        oldNewValues.Add("The lead street address", new { OldValue = string.Empty, NewValue = leadsstreetadress });
                        string leadscity = contactDetails[15];
                        oldNewValues.Add("The lead city", new { OldValue = string.Empty, NewValue = leadscity });
                        string leadsstate = contactDetails[16];
                        oldNewValues.Add("The lead state", new { OldValue = string.Empty, NewValue = leadsstate });
                        string leadszipcode = contactDetails[17];
                        oldNewValues.Add("The lead zipcode", new { OldValue = string.Empty, NewValue = leadszipcode });

                        string leadlastlogindate = contactDetails[18];
                        if (!string.IsNullOrEmpty(leadlastlogindate))
                        {
                            var customfield = customFields.Where(i => i.Title.Replace(" ", string.Empty).ToLower() == "thelastleadlogindate(idx)").FirstOrDefault();
                            if (customfield != null)
                            {
                                var customfielddata = duplicateperson.CustomFields == null ? null : duplicateperson.CustomFields.Where(i => i.CustomFieldId == customfield.FieldId).FirstOrDefault();
                                if (customfielddata != null)
                                {
                                    elementvalue = customfielddata.Value;
                                }
                                if (CustomFields.Length == 0)
                                {
                                    CustomFields.Append(customfield.FieldId + "##$##" + (byte)customfield.FieldInputTypeId + "|" + leadlastlogindate);
                                }
                                else
                                {
                                    CustomFields.Append("~" + customfield.FieldId + "##$##" + (byte)customfield.FieldInputTypeId + "|" + leadlastlogindate);
                                }
                            }
                            customData.FieldID     = customfield.FieldId;
                            customData.FieldTypeID = (int?)customfield.FieldInputTypeId;
                            customData.FieldValue  = leadlastlogindate;
                            contactCustomData.Add(customData);

                            oldNewValues.Add("The last lead login date", new { OldValue = string.IsNullOrEmpty(elementvalue) ? string.Empty : elementvalue, NewValue = leadlastlogindate });
                        }

                        string leadlastupdatedate = contactDetails[19];
                        if (!string.IsNullOrEmpty(leadlastupdatedate))
                        {
                            var customfield = customFields.Where(i => i.Title.Replace(" ", string.Empty).ToLower() == "thelastleadupdatedate(idx)").FirstOrDefault();
                            if (customfield != null)
                            {
                                var customfielddata = duplicateperson.CustomFields == null ? null : duplicateperson.CustomFields.Where(i => i.CustomFieldId == customfield.FieldId).FirstOrDefault();
                                if (customfielddata != null)
                                {
                                    elementvalue = customfielddata.Value;
                                }
                                if (CustomFields.Length == 0)
                                {
                                    CustomFields.Append(customfield.FieldId + "##$##" + (byte)customfield.FieldInputTypeId + "|" + leadlastupdatedate);
                                }
                                else
                                {
                                    CustomFields.Append("~" + customfield.FieldId + "##$##" + (byte)customfield.FieldInputTypeId + "|" + leadlastupdatedate);
                                }
                            }
                            customData.FieldID     = customfield.FieldId;
                            customData.FieldTypeID = (int?)customfield.FieldInputTypeId;
                            customData.FieldValue  = leadlastupdatedate;
                            contactCustomData.Add(customData);

                            oldNewValues.Add("The last lead update date", new { OldValue = string.IsNullOrEmpty(elementvalue) ? string.Empty : elementvalue, NewValue = leadlastupdatedate });
                        }

                        string leadcategory = contactDetails[20];
                        if (!string.IsNullOrEmpty(leadcategory))
                        {
                            var customfield = customFields.Where(i => i.Title.Replace(" ", string.Empty).ToLower() == "theleadcategory(idx)").FirstOrDefault();
                            if (customfield != null)
                            {
                                var customfielddata = duplicateperson.CustomFields == null ? null : duplicateperson.CustomFields.Where(i => i.CustomFieldId == customfield.FieldId).FirstOrDefault();
                                if (customfielddata != null)
                                {
                                    elementvalue = customfielddata.Value;
                                }
                                if (CustomFields.Length == 0)
                                {
                                    CustomFields.Append(customfield.FieldId + "##$##" + (byte)customfield.FieldInputTypeId + "|" + leadcategory);
                                }
                                else
                                {
                                    CustomFields.Append("~" + customfield.FieldId + "##$##" + (byte)customfield.FieldInputTypeId + "|" + leadcategory);
                                }
                            }
                            customData.FieldID     = customfield.FieldId;
                            customData.FieldTypeID = (int?)customfield.FieldInputTypeId;
                            customData.FieldValue  = leadcategory;
                            contactCustomData.Add(customData);

                            oldNewValues.Add("The lead category", new { OldValue = string.IsNullOrEmpty(elementvalue) ? string.Empty : elementvalue, NewValue = leadcategory });
                        }

                        string isleadflagged = contactDetails[21];
                        if (!string.IsNullOrEmpty(isleadflagged))
                        {
                            var customfield = customFields.Where(i => i.Title.Replace(" ", string.Empty).ToLower() == "iftheleadhasbeenflagged(idx)").FirstOrDefault();
                            if (customfield != null)
                            {
                                var customfielddata = duplicateperson.CustomFields == null ? null : duplicateperson.CustomFields.Where(i => i.CustomFieldId == customfield.FieldId).FirstOrDefault();
                                if (customfielddata != null)
                                {
                                    elementvalue = customfielddata.Value;
                                }
                                if (CustomFields.Length == 0)
                                {
                                    CustomFields.Append(customfield.FieldId + "##$##" + (byte)customfield.FieldInputTypeId + "|" + isleadflagged);
                                }
                                else
                                {
                                    CustomFields.Append("~" + customfield.FieldId + "##$##" + (byte)customfield.FieldInputTypeId + "|" + isleadflagged);
                                }
                            }
                            customData.FieldID     = customfield.FieldId;
                            customData.FieldTypeID = (int?)customfield.FieldInputTypeId;
                            customData.FieldValue  = isleadflagged;
                            contactCustomData.Add(customData);
                            oldNewValues.Add("If the lead has been flagged", new { OldValue = string.IsNullOrEmpty(elementvalue) ? string.Empty : elementvalue, NewValue = isleadflagged });
                        }
                        contactCustomData.Add(customData);
                        var person = new RawContact
                        {
                            ReferenceId  = guid,
                            AccountID    = leadAdapterAndAccountMap.AccountID,
                            FirstName    = firstName,
                            LastName     = lastName,
                            PrimaryEmail = primaryemail,
                            AddressLine1 = leadsstreetadress,
                            City         = leadscity,
                            State        = leadsstate,
                            PhoneData    = phonedata.ToString(),

                            CustomFieldsData = CustomFields.ToString(),
                            ZipCode          = contactDetails.Length > 17 ? contactDetails[17] : string.Empty
                        };
                        person.ReferenceId = guid;
                        person.AccountID   = AccountID;
                        person.LeadAdapterRecordStatusId = (byte)status;
                        person.JobID           = jobId;
                        person.ContactStatusID = 1;
                        person.ContactTypeID   = 1;
                        JavaScriptSerializer js = new JavaScriptSerializer();
                        person.LeadAdapterSubmittedData = js.Serialize(oldNewValues);
                        person.LeadAdapterRowData       = contact;
                        personCustomFieldData.AddRange(contactCustomData);
                        personPhoneData.AddRange(contactPhoneData);

                        person.ValidEmail = ValidateEmail(person);

                        RawContact duplicate_data = null;
                        if (!String.IsNullOrEmpty(Convert.ToString(person.PrimaryEmail)))
                        {
                            duplicate_data = persons.Where(p => string.Compare(p.PrimaryEmail, Convert.ToString(person.PrimaryEmail), true) == 0).FirstOrDefault();
                        }
                        else
                        {
                            duplicate_data = persons.Where(p => string.Compare(p.FirstName, Convert.ToString(person.FirstName), true) == 0 && string.Compare(p.LastName, Convert.ToString(person.LastName), true) == 0).FirstOrDefault();
                        }

                        if (duplicate_data != null)
                        {
                            person.IsDuplicate = true;
                            //RawContact updatedperson = MergeDuplicateData(duplicate_data, person, guid);
                            //duplicate_data = updatedperson;
                        }

                        persons.Add(person);
                    }
                }
            }
            catch (WebException ex)
            {
                Logger.Current.Error("An error occurred in idx get data method(web exception): " + ex);
                Logger.Current.Error("The invalid xml file content: " + soapResult);
            }
            catch (XmlException ex)
            {
                Logger.Current.Error("An error occurred in idx get data method(web exception): " + ex);
                Logger.Current.Error("The invalid xml file content: " + soapResult);
            }
            catch (Exception ex)
            {
                Logger.Current.Error("An error occurred in idx get data method: " + ex);
            }
            data.ContactPhoneData  = personPhoneData;
            data.ContactCustomData = personCustomFieldData;
            data.ContactData       = persons;
            return(data);
        }
コード例 #2
0
        public override ImportContactsData GetContacts(string fileName, IEnumerable <FieldViewModel> customFields, int jobId, IEnumerable <DropdownValueViewModel> DropdownFields)
        {
            var persons = new List <RawContact>();
            var personCustomFieldData      = new List <ImportCustomData>();
            var personPhoneData            = new List <ImportPhoneData>();
            ImportContactsData data        = new ImportContactsData();
            string             leadsString = string.Empty;
            var oldNewValues = new Dictionary <string, dynamic> {
            };
            Func <RawContact, bool> ValidateEmail = (c) =>
            {
                /*
                 * If email is not empty or null then validate email
                 * If email is empty/or null then check for legth of first name and lastname
                 */
                if ((!string.IsNullOrEmpty(c.PrimaryEmail) && c.IsValidEmail(c.PrimaryEmail)) ||
                    (string.IsNullOrEmpty(c.PrimaryEmail) && !string.IsNullOrEmpty(c.FirstName) && !string.IsNullOrEmpty(c.LastName)))
                {
                    return(true);
                }
                return(false);
            };

            try
            {
                Logger.Current.Verbose("Getting the data for BDX Lead adapter provider");

                var      ftpManager    = new FtpService();
                var      ftpcontent    = ftpManager.GetService(leadAdapterAndAccountMap.RequestGuid);
                DateTime lastProcessed = leadAdapterAndAccountMap.LastProcessed == null?DateTime.Now.ToUniversalTime().AddDays(-90) : leadAdapterAndAccountMap.LastProcessed.Value;

                string url = string.Format(ftpcontent.Host + "?CommunityID={0}&Username={1}&Password={2}&StartDate={3}&EndDate={4}",
                                           leadAdapterAndAccountMap.BuilderNumber, ftpcontent.UserName, ftpcontent.Password,
                                           lastProcessed.ToString("MM-dd-yyyy hh:mm:ss", CultureInfo.InvariantCulture),
                                           DateTime.Now.ToUniversalTime().ToString("MM-dd-yyyy hh:mm:ss", CultureInfo.InvariantCulture));
                leadsString = this.ProcessWebRequest(url);

                string ext          = leadsString.Trim('\n', '\r');
                string formattedXml = XElement.Parse(ext).ToString();
                var    xDocument    = XDocument.Parse(formattedXml);
                var    leads        = xDocument.Descendants("Lead");
                customFields = customFields.Where(i => i.IsLeadAdapterField && i.LeadAdapterType == (byte)LeadAdapterTypes.PrivateCommunities && i.StatusId == FieldStatus.Active);
                IList <string>          hashes = new List <string>();
                LeadAdapterRecordStatus status = LeadAdapterRecordStatus.Undefined;

                int AccountID = leadAdapterAndAccountMap.AccountID;
                foreach (var lead in leads)
                {
                    var guid            = Guid.NewGuid();
                    var propertyIntrest = lead.Descendants("PropertyInterest").FirstOrDefault();
                    var leadcontact     = lead.Descendants("Contact").FirstOrDefault();

                    string BuilderNumber = propertyIntrest.Attribute("BuilderNumber") != null?propertyIntrest.Attribute("BuilderNumber").Value : "";

                    bool builderNumberPass = leadAdapterAndAccountMap.BuilderNumber.ToLower().Split(',').Contains(BuilderNumber.ToLower());

                    string CommunityNumber = propertyIntrest.Attribute("CommunityNumber") != null?propertyIntrest.Attribute("CommunityNumber").Value : "";

                    bool communityNumberPass = true;
                    //bool communityNumberPass = String.IsNullOrEmpty(leadAdapterAndAccountMap.CommunityNumber) ? true :
                    //    leadAdapterAndAccountMap.CommunityNumber.ToLower().Split(',').Contains(CommunityNumber.ToLower()) && !string.IsNullOrEmpty(CommunityNumber);
                    Logger.Current.Informational("Processing leads for account : " + leadAdapterAndAccountMap.AccountName + " IsCommunityPass : "******"FirstName") != null?leadcontact.Attribute("FirstName").Value : null;

                    string LastName = leadcontact.Attribute("LastName") != null?leadcontact.Attribute("LastName").Value : null;

                    string PrimaryEmail = leadcontact.Attribute("Email") != null?leadcontact.Attribute("Email").Value : null;

                    string CompanyName = string.Empty;

                    StringBuilder hash   = new StringBuilder();
                    IList <Email> emails = new List <Email>();

                    if (!string.IsNullOrEmpty(PrimaryEmail))
                    {
                        Email primaryemail = new Email()
                        {
                            EmailId   = PrimaryEmail,
                            AccountID = leadAdapterAndAccountMap.AccountID,
                            IsPrimary = true
                        };
                        emails.Add(primaryemail);
                        hash.Append("-").Append(PrimaryEmail);
                    }
                    else
                    {
                        hash.Append("-").Append("*****@*****.**");
                    }

                    Person person = new Person()
                    {
                        FirstName   = FirstName,
                        LastName    = LastName,
                        CompanyName = CompanyName,
                        Emails      = emails,
                        AccountID   = AccountID
                    };

                    if (string.IsNullOrEmpty(FirstName))
                    {
                        hash.Append("-").Append(string.Empty);
                    }
                    else
                    {
                        hash.Append("-").Append(FirstName);
                    }

                    if (string.IsNullOrEmpty(LastName))
                    {
                        hash.Append("-").Append(string.Empty);
                    }
                    else
                    {
                        hash.Append("-").Append(LastName);
                    }

                    if (string.IsNullOrEmpty(CompanyName))
                    {
                        hash.Append("-").Append(string.Empty);
                    }
                    else
                    {
                        hash.Append("-").Append(CompanyName);
                    }


                    bool IsNotValidContact = false;

                    bool isDuplicateFromFile = false;

                    if (!IsNotValidContact && builderNumberPass && communityNumberPass)
                    {
                        bool duplicateemailcount = hashes.Where(h => h.Contains(PrimaryEmail)).Any();
                        if (!string.IsNullOrEmpty(PrimaryEmail) && duplicateemailcount)
                        {
                            isDuplicateFromFile = true;
                        }
                        else if (!string.IsNullOrEmpty(PrimaryEmail) && !duplicateemailcount)
                        {
                            isDuplicateFromFile = false;
                        }
                        else if (string.IsNullOrEmpty(PrimaryEmail) && hashes.Where(h => h.Contains(hash.ToString())).Any())
                        {
                            isDuplicateFromFile = true;
                        }
                        else
                        {
                            isDuplicateFromFile = false;
                        }
                    }

                    SearchResult <Contact> duplicateResult = new SearchResult <Contact>();
                    if (!IsNotValidContact && builderNumberPass && isDuplicateFromFile == false && communityNumberPass)
                    {
                        SearchParameters parameters = new SearchParameters()
                        {
                            AccountId = AccountID
                        };
                        IEnumerable <Contact> duplicateContacts = contactService.CheckIfDuplicate(new CheckContactDuplicateRequest()
                        {
                            Person = person
                        }).Contacts;
                        duplicateResult = new SearchResult <Contact>()
                        {
                            Results = duplicateContacts, TotalHits = duplicateContacts != null?duplicateContacts.Count() : 0
                        };
                    }

                    if (!builderNumberPass)
                    {
                        status = LeadAdapterRecordStatus.BuilderNumberFailed;
                    }
                    else if (!communityNumberPass)
                    {
                        status = LeadAdapterRecordStatus.CommunityNumberFailed;
                    }
                    else if (IsNotValidContact)
                    {
                        status = LeadAdapterRecordStatus.ValidationFailed;
                    }
                    else if (isDuplicateFromFile)
                    {
                        status = LeadAdapterRecordStatus.DuplicateFromFile;
                    }
                    else if (duplicateResult.TotalHits > 0)
                    {
                        status = LeadAdapterRecordStatus.Updated;
                        guid   = duplicateResult.Results.FirstOrDefault().ReferenceId;
                    }
                    else
                    {
                        status = LeadAdapterRecordStatus.Added;
                    }



                    Contact duplicateperson = default(Person);
                    //contact.LeadAdapterRecordStatusId = (byte)status;
                    if (status == LeadAdapterRecordStatus.Updated)
                    {
                        duplicateperson = duplicateResult.Results.FirstOrDefault();
                    }
                    else
                    {
                        duplicateperson = new Person();
                    }

                    ///////////////////////////////////////////////////////////



                    RawContact contact = new RawContact();
                    IList <ImportCustomData> contactCustomData = new List <ImportCustomData>();
                    IList <ImportPhoneData>  contactPhoneData  = new List <ImportPhoneData>();

                    StringBuilder CustomFieldData = new StringBuilder();
                    try
                    {
                        XDocument            doc           = XDocument.Parse(lead.ToString());
                        List <XMLTypeHolder> allattributes = new List <XMLTypeHolder>();
                        foreach (XElement node in doc.Nodes())
                        {
                            allattributes.AddRange(node.Attributes().Select(x => new XMLTypeHolder {
                                NodeName = node.Name.LocalName, LocalName = x.Name.LocalName, Value = x.Value
                            }).ToList());
                            if (node.HasElements)
                            {
                                foreach (XElement ele in node.Elements())
                                {
                                    allattributes.AddRange(ele.Attributes().Select(x => new XMLTypeHolder {
                                        NodeName = ele.Name.LocalName, LocalName = x.Name.LocalName, Value = x.Value
                                    }).ToList());
                                }
                            }
                        }

                        foreach (var attribute in allattributes)
                        {
                            ImportCustomData customData = new ImportCustomData();
                            try
                            {
                                var elementvalue = string.Empty;
                                if (attribute.LocalName.ToLower() == "firstname" && attribute.NodeName == "Contact")
                                {
                                    elementvalue      = ((Person)duplicateperson).FirstName == null ? "" : ((Person)duplicateperson).FirstName;
                                    contact.FirstName = attribute.Value;
                                }
                                else if (attribute.LocalName.ToLower() == "lastname" && attribute.NodeName == "Contact")
                                {
                                    elementvalue     = ((Person)duplicateperson).LastName;
                                    contact.LastName = attribute.Value;
                                }
                                else if (attribute.LocalName.ToLower() == "email" && attribute.NodeName == "Contact")
                                {
                                    Email primaryemail = duplicateperson.Emails == null ? null : duplicateperson.Emails.Where(i => i.IsPrimary == true).FirstOrDefault();
                                    if (primaryemail != null)
                                    {
                                        elementvalue = primaryemail.EmailId;
                                    }
                                    contact.PrimaryEmail = attribute.Value;
                                }
                                else if (attribute.LocalName.ToLower() == "company" && attribute.NodeName == "Contact")
                                {
                                    elementvalue        = duplicateperson.CompanyName;
                                    contact.CompanyName = attribute.Value;
                                }
                                else if (attribute.LocalName.ToLower() == "phone" && attribute.NodeName == "Contact")
                                {
                                    DropdownValueViewModel drpvalue = DropdownFields.Where(i => i.DropdownValueTypeID == (short)DropdownValueTypes.MobilePhone).FirstOrDefault();
                                    var             mobilephone     = default(Phone);
                                    ImportPhoneData phoneData       = new ImportPhoneData();
                                    phoneData.ReferenceID = guid;
                                    if (drpvalue != null)
                                    {
                                        if (!string.IsNullOrEmpty(attribute.Value))
                                        {
                                            string nonnumericstring = GetNonNumericData(attribute.Value);
                                            if (IsValidPhoneNumberLength(nonnumericstring))
                                            {
                                                contact.PhoneData     = drpvalue.DropdownValueID.ToString() + "|" + nonnumericstring;
                                                phoneData.PhoneType   = (int?)drpvalue.DropdownValueID;
                                                phoneData.PhoneNumber = nonnumericstring;
                                                contactPhoneData.Add(phoneData);
                                            }
                                        }
                                        mobilephone = duplicateperson.Phones == null ? null : duplicateperson.Phones.Where(i => i.PhoneType == drpvalue.DropdownValueID).FirstOrDefault();
                                    }

                                    if (mobilephone != null)
                                    {
                                        elementvalue = mobilephone.Number;
                                    }
                                }
                                else if (attribute.LocalName.ToLower() == "country" && attribute.NodeName == "Contact")
                                {
                                    var countryvalue = attribute.Value.Replace(" ", string.Empty).ToLower();
                                    if (countryvalue == "usa" || countryvalue == "us" || countryvalue == "unitedstates" || countryvalue == "unitedstatesofamerica")
                                    {
                                        contact.Country = "US";
                                    }
                                    else if (countryvalue == "ca" || countryvalue == "canada")
                                    {
                                        contact.Country = "CA";
                                    }
                                    else
                                    {
                                        contact.Country = attribute.Value;
                                    }
                                }
                                else if (attribute.LocalName.ToLower() == "title" && attribute.NodeName == "Contact")
                                {
                                    contact.Title = attribute.Value;
                                }
                                else if (attribute.LocalName.ToLower() == "streetadress" && attribute.NodeName == "Contact")
                                {
                                    contact.AddressLine1 = attribute.Value;
                                }
                                else if (attribute.LocalName.ToLower() == "city" && attribute.NodeName == "Contact")
                                {
                                    contact.City = attribute.Value;
                                }
                                else if (attribute.LocalName.ToLower() == "state" && attribute.NodeName == "Contact")
                                {
                                    contact.State = attribute.Value;
                                }
                                else if (attribute.LocalName.ToLower() == "postalcode" && attribute.NodeName == "Contact")
                                {
                                    contact.ZipCode = attribute.Value;
                                }
                                else
                                {
                                    var customField = customFields.Where(i => i.Title.Replace(" ", string.Empty).ToLower() == (attribute.LocalName.ToLower() + "(" + LeadAdapterTypes.PrivateCommunities.ToString().ToLower() + ")")).FirstOrDefault();
                                    if (customField != null)
                                    {
                                        var customfielddata = duplicateperson.CustomFields == null ? null : duplicateperson.CustomFields.Where(i => i.CustomFieldId == customField.FieldId).FirstOrDefault();
                                        if (customfielddata != null)
                                        {
                                            elementvalue = customfielddata.Value;
                                        }

                                        customData.FieldID     = customField.FieldId;
                                        customData.FieldTypeID = (int?)customField.FieldInputTypeId;
                                        customData.ReferenceID = guid;

                                        if (customField.FieldInputTypeId == FieldType.date || customField.FieldInputTypeId == FieldType.datetime || customField.FieldInputTypeId == FieldType.time)
                                        {
                                            DateTime converteddate;
                                            if (DateTime.TryParse(attribute.Value, out converteddate))
                                            {
                                                CustomFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + converteddate.ToString("MM/dd/yyyy hh:mm tt"));
                                                customData.FieldValue = converteddate.ToString("MM/dd/yyyy hh:mm tt");
                                            }
                                        }
                                        else if (customField.FieldInputTypeId == FieldType.number)
                                        {
                                            double number;
                                            if (double.TryParse(attribute.Value, out number))
                                            {
                                                CustomFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + number.ToString());
                                                customData.FieldValue = number.ToString();
                                            }
                                        }
                                        else if (customField.FieldInputTypeId == FieldType.url)
                                        {
                                            if (IsValidURL(attribute.Value.Trim()))
                                            {
                                                CustomFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + attribute.Value.Trim());
                                                customData.FieldValue = attribute.Value.Trim();
                                            }
                                        }
                                        else
                                        {
                                            CustomFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + attribute.Value.Trim());
                                            customData.FieldValue = attribute.Value.Trim();
                                        }
                                        contactCustomData.Add(customData);
                                    }
                                }
                                if (!oldNewValues.ContainsKey(attribute.LocalName))
                                {
                                    oldNewValues.Add(attribute.LocalName, new { OldValue = string.IsNullOrEmpty(elementvalue) ? string.Empty : elementvalue, NewValue = attribute.Value });
                                }
                            }
                            catch (Exception ex)
                            {
                                Logger.Current.Error("An exception occured in Genereating old new values attribute in Private Communities : " + attribute.LocalName, ex);
                                continue;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Current.Error("An exception occured in Genereating old new values attribute in Private Communities : ", ex);
                    }
                    if (CustomFieldData.Length > 0)
                    {
                        CustomFieldData.Remove(0, 1);
                    }
                    contact.CustomFieldsData          = CustomFieldData.ToString();
                    contact.ReferenceId               = guid;
                    contact.AccountID                 = AccountID;
                    contact.LeadAdapterRecordStatusId = (byte)status;
                    contact.JobID = jobId;
                    contact.IsCommunityNumberPass = communityNumberPass;
                    contact.IsBuilderNumberPass   = builderNumberPass;
                    contact.ContactStatusID       = 1;
                    contact.ContactTypeID         = 1;
                    JavaScriptSerializer js = new JavaScriptSerializer();
                    contact.LeadAdapterSubmittedData = js.Serialize(oldNewValues);
                    contact.LeadAdapterRowData       = lead.ToString();
                    personCustomFieldData.AddRange(contactCustomData);
                    personPhoneData.AddRange(contactPhoneData);

                    contact.ValidEmail = ValidateEmail(contact);

                    RawContact duplicate_data = null;
                    if (!String.IsNullOrEmpty(Convert.ToString(contact.PrimaryEmail)))
                    {
                        duplicate_data = persons.Where(p => string.Compare(p.PrimaryEmail, Convert.ToString(contact.PrimaryEmail), true) == 0).FirstOrDefault();
                    }
                    else
                    {
                        duplicate_data = persons.Where(p => string.Compare(p.FirstName, Convert.ToString(contact.FirstName), true) == 0 && string.Compare(p.LastName, Convert.ToString(contact.LastName), true) == 0).FirstOrDefault();
                    }

                    if (duplicate_data != null)
                    {
                        contact.IsDuplicate = true;
                        //RawContact updatedperson = MergeDuplicateData(duplicate_data, contact, guid);
                        //duplicate_data = updatedperson;
                    }

                    persons.Add(contact);
                }
            }
            catch (Exception ex)
            {
                Logger.Current.Error("Exception occured while getting bdx files :" + ex);
            }
            data.ContactCustomData = personCustomFieldData;
            data.ContactPhoneData  = personPhoneData;
            data.ContactData       = persons;
            return(data);
        }
コード例 #3
0
        public override ImportContactsData GetContacts(string fileName, IEnumerable <FieldViewModel> customFields, int jobId, IEnumerable <DropdownValueViewModel> DropdownFields)
        {
            var persons = new List <RawContact>();
            var personCustomFieldData = new List <ImportCustomData>();
            var personPhoneData       = new List <ImportPhoneData>();
            ImportContactsData data   = new ImportContactsData();

            Func <RawContact, bool> ValidateEmail = (c) =>
            {
                /*
                 * If email is not empty or null then validate email
                 * If email is empty/or null then check for legth of first name and lastname
                 */
                if ((!string.IsNullOrEmpty(c.PrimaryEmail) && c.IsValidEmail(c.PrimaryEmail)) ||
                    (string.IsNullOrEmpty(c.PrimaryEmail) && !string.IsNullOrEmpty(c.FirstName) && !string.IsNullOrEmpty(c.LastName)))
                {
                    return(true);
                }
                return(false);
            };

            try
            {
                var xDocument = XDocument.Load(fileName);
                // getting all the leads in the file
                var            leads     = xDocument.Descendants("lead").Select(p => p).ToList();
                int            AccountID = leadAdapterAndAccountMap.AccountID;
                IList <string> hashes    = new List <string>();
                customFields = customFields.Where(i => i.IsLeadAdapterField && i.LeadAdapterType == (byte)LeadAdapterTypes.NewHomeFeed && i.StatusId == FieldStatus.Active);
                foreach (var lead in leads)
                {
                    // created the guid for reference in the contact
                    var    guid                = Guid.NewGuid();
                    string buildernumber       = lead.Elements("buildernumber").FirstOrDefault() == null ? string.Empty : lead.Elements("buildernumber").First().Value;
                    bool   builderNumberPass   = leadAdapterAndAccountMap.BuilderNumber.ToLower().Split(',').Contains(buildernumber.ToLower());
                    bool   communityNumberPass = true;
                    string CommunityNumber     = lead.Elements("communitynumber").FirstOrDefault() == null ? string.Empty : lead.Elements("communitynumber").First().Value;
                    //bool communityNumberPass = String.IsNullOrEmpty(leadAdapterAndAccountMap.CommunityNumber) ? true :
                    //    leadAdapterAndAccountMap.CommunityNumber.ToLower().Split(',').Contains(CommunityNumber.ToLower()) && !string.IsNullOrEmpty(CommunityNumber);
                    Logger.Current.Informational("Processing leads for account : " + leadAdapterAndAccountMap.AccountName + " IsCommunityPass : "******"firstname").FirstOrDefault() == null ? string.Empty : lead.Elements("firstname").First().Value;
                    string LastName     = lead.Elements("lastname").FirstOrDefault() == null ? string.Empty : lead.Elements("lastname").First().Value;
                    string PrimaryEmail = lead.Elements("email").FirstOrDefault() == null ? string.Empty : lead.Elements("email").First().Value;
                    string CompanyName  = lead.Elements("Company").FirstOrDefault() == null ? null : lead.Elements("Company").First().Value;


                    IList <Email> emails = new List <Email>();

                    if (!string.IsNullOrEmpty(PrimaryEmail))
                    {
                        Email primaryemail = new Email()
                        {
                            EmailId   = PrimaryEmail,
                            AccountID = AccountID,
                            IsPrimary = true
                        };
                        emails.Add(primaryemail);
                        hash.Append("-").Append(PrimaryEmail);
                    }
                    else
                    {
                        hash.Append("-").Append("*****@*****.**");
                    }

                    Person person = new Person()
                    {
                        FirstName   = FirstName,
                        LastName    = LastName,
                        CompanyName = CompanyName,
                        Emails      = emails,
                        AccountID   = AccountID
                    };

                    if (string.IsNullOrEmpty(FirstName))
                    {
                        hash.Append("-").Append(string.Empty);
                    }
                    else
                    {
                        hash.Append("-").Append(FirstName);
                    }

                    if (string.IsNullOrEmpty(LastName))
                    {
                        hash.Append("-").Append(string.Empty);
                    }
                    else
                    {
                        hash.Append("-").Append(LastName);
                    }

                    if (string.IsNullOrEmpty(CompanyName))
                    {
                        hash.Append("-").Append(string.Empty);
                    }
                    else
                    {
                        hash.Append("-").Append(CompanyName);
                    }



                    //var BrokenRules = person.GetBrokenRules();
                    bool IsNotValidContact = false;

                    bool isDuplicateFromFile = false;

                    if (!IsNotValidContact && builderNumberPass && communityNumberPass)
                    {
                        bool duplicateemailcount = hashes.Where(h => h.Contains(PrimaryEmail)).Any();
                        if (!string.IsNullOrEmpty(PrimaryEmail) && duplicateemailcount)
                        {
                            isDuplicateFromFile = true;
                        }
                        else if (!string.IsNullOrEmpty(PrimaryEmail) && !duplicateemailcount)
                        {
                            isDuplicateFromFile = false;
                        }
                        else if (string.IsNullOrEmpty(PrimaryEmail) && hashes.Where(h => h.Contains(hash.ToString())).Any())
                        {
                            isDuplicateFromFile = true;
                        }
                        else
                        {
                            isDuplicateFromFile = false;
                        }
                    }

                    SearchResult <Contact> duplicateResult = new SearchResult <Contact>();
                    if (!IsNotValidContact && builderNumberPass && isDuplicateFromFile == false && communityNumberPass)
                    {
                        SearchParameters parameters = new SearchParameters()
                        {
                            AccountId = AccountID
                        };
                        IEnumerable <Contact> duplicateContacts = contactService.CheckIfDuplicate(new CheckContactDuplicateRequest()
                        {
                            Person = person
                        }).Contacts;
                        duplicateResult = new SearchResult <Contact>()
                        {
                            Results = duplicateContacts, TotalHits = duplicateContacts != null?duplicateContacts.Count() : 0
                        };
                    }

                    if (!builderNumberPass)
                    {
                        status = LeadAdapterRecordStatus.BuilderNumberFailed;
                    }
                    else if (!communityNumberPass)
                    {
                        status = LeadAdapterRecordStatus.CommunityNumberFailed;
                    }
                    else if (IsNotValidContact)
                    {
                        status = LeadAdapterRecordStatus.ValidationFailed;
                    }
                    else if (isDuplicateFromFile)
                    {
                        status = LeadAdapterRecordStatus.DuplicateFromFile;
                    }
                    else if (duplicateResult.TotalHits > 0)
                    {
                        status = LeadAdapterRecordStatus.Updated;
                        guid   = duplicateResult.Results.FirstOrDefault().ReferenceId;
                    }
                    else
                    {
                        status = LeadAdapterRecordStatus.Added;
                    }



                    Contact duplicateperson = default(Person);
                    if (status == LeadAdapterRecordStatus.Updated)
                    {
                        duplicateperson = duplicateResult.Results.FirstOrDefault();
                    }
                    else
                    {
                        duplicateperson = new Person();
                    }

                    //////////////////////////////////////////////////////
                    try
                    {
                        XDocument        doc        = XDocument.Parse(lead.ToString());
                        ImportCustomData customData = new ImportCustomData();
                        var elements = doc.Root.DescendantNodes().OfType <XElement>();
                        foreach (XElement element in elements)
                        {
                            try
                            {
                                var elementvalue = string.Empty;
                                if (element.Name.LocalName.ToLower() == "firstname")
                                {
                                    elementvalue      = ((Person)duplicateperson).FirstName == null ? "" : ((Person)duplicateperson).FirstName;
                                    contact.FirstName = element.Value;
                                }
                                else if (element.Name.LocalName.ToLower() == "lastname")
                                {
                                    elementvalue     = ((Person)duplicateperson).LastName;
                                    contact.LastName = element.Value;
                                }
                                else if (element.Name.LocalName.ToLower() == "email")
                                {
                                    Email primaryemail = duplicateperson.Emails == null ? null : duplicateperson.Emails.Where(i => i.IsPrimary == true).FirstOrDefault();
                                    if (primaryemail != null)
                                    {
                                        elementvalue = primaryemail.EmailId;
                                    }
                                    contact.PrimaryEmail = element.Value;
                                }
                                else if (element.Name.LocalName.ToLower() == "company")
                                {
                                    elementvalue        = duplicateperson.CompanyName;
                                    contact.CompanyName = element.Value;
                                }
                                else if (element.Name.LocalName.ToLower() == "phone")
                                {
                                    DropdownValueViewModel drpvalue = DropdownFields.Where(i => i.DropdownValueTypeID == (short)DropdownValueTypes.MobilePhone).FirstOrDefault();
                                    var             mobilephone     = default(Phone);
                                    ImportPhoneData phoneData       = new ImportPhoneData();
                                    phoneData.ReferenceID = guid;
                                    if (drpvalue != null)
                                    {
                                        if (!string.IsNullOrEmpty(element.Value))
                                        {
                                            string nonnumericstring = GetNonNumericData(element.Value);
                                            if (IsValidPhoneNumberLength(nonnumericstring))
                                            {
                                                contact.PhoneData     = drpvalue.DropdownValueID.ToString() + "|" + nonnumericstring;
                                                phoneData.PhoneType   = (int?)drpvalue.DropdownValueID;
                                                phoneData.PhoneNumber = nonnumericstring;
                                                contactPhoneData.Add(phoneData);
                                            }
                                        }
                                        mobilephone = duplicateperson.Phones == null ? null : duplicateperson.Phones.Where(i => i.PhoneType == drpvalue.DropdownValueID).FirstOrDefault();
                                    }

                                    if (mobilephone != null)
                                    {
                                        elementvalue = mobilephone.Number;
                                    }
                                }
                                else
                                {
                                    var customField = customFields.Where(i => i.Title.Replace(" ", string.Empty).ToLower() == (element.Name.LocalName.ToLower() + "(" + LeadAdapterTypes.NewHomeFeed.ToString().ToLower() + ")")).FirstOrDefault();
                                    if (customField != null)
                                    {
                                        customData = new ImportCustomData();
                                        var customfielddata = duplicateperson.CustomFields == null ? null : duplicateperson.CustomFields.Where(i => i.CustomFieldId == customField.FieldId).FirstOrDefault();
                                        if (customfielddata != null)
                                        {
                                            elementvalue = customfielddata.Value;
                                        }

                                        customData.FieldID     = customField.FieldId;
                                        customData.FieldTypeID = (int?)customField.FieldInputTypeId;
                                        customData.ReferenceID = guid;

                                        if (customField.FieldInputTypeId == FieldType.date || customField.FieldInputTypeId == FieldType.datetime || customField.FieldInputTypeId == FieldType.time)
                                        {
                                            DateTime converteddate;
                                            if (DateTime.TryParse(element.Value.Trim(), out converteddate))
                                            {
                                                CustomFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + converteddate.ToString("MM/dd/yyyy hh:mm tt"));
                                                customData.FieldValue = converteddate.ToString("MM/dd/yyyy hh:mm tt");
                                            }
                                        }
                                        else if (customField.FieldInputTypeId == FieldType.number)
                                        {
                                            double number;
                                            if (double.TryParse(element.Value.Trim(), out number))
                                            {
                                                CustomFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + number.ToString());
                                                customData.FieldValue = number.ToString();
                                            }
                                        }
                                        else if (customField.FieldInputTypeId == FieldType.url)
                                        {
                                            if (IsValidURL(element.Value.Trim()))
                                            {
                                                CustomFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + element.Value.Trim());
                                                customData.FieldValue = element.Value.Trim();
                                            }
                                        }
                                        else
                                        {
                                            CustomFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + element.Value.Trim());
                                            customData.FieldValue = element.Value.Trim();
                                        }
                                        contactCustomData.Add(customData);
                                    }
                                }
                                if (!oldNewValues.ContainsKey(element.Name.LocalName))
                                {
                                    oldNewValues.Add(element.Name.LocalName, new { OldValue = string.IsNullOrEmpty(elementvalue) ? string.Empty : elementvalue, NewValue = element.Value.Trim() });
                                }
                            }
                            catch (Exception ex)
                            {
                                Logger.Current.Error("An exception occured in Genereating old new values element in NewHomeFeed : " + element.Name.LocalName, ex);
                                continue;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Current.Error("An exception occured in Genereating old new values element in NewHomeFeed : ", ex);
                    }
                    if (CustomFieldData.Length > 0)
                    {
                        CustomFieldData.Remove(0, 1);
                    }

                    contact.CustomFieldsData          = CustomFieldData.ToString();
                    contact.ReferenceId               = guid;
                    contact.AccountID                 = AccountID;
                    contact.IsBuilderNumberPass       = builderNumberPass;
                    contact.IsCommunityNumberPass     = communityNumberPass;
                    contact.LeadAdapterRecordStatusId = (byte)status;
                    contact.JobID           = jobId;
                    contact.ContactStatusID = 1;
                    contact.ContactTypeID   = 1;

                    JavaScriptSerializer js = new JavaScriptSerializer();
                    contact.LeadAdapterSubmittedData = js.Serialize(oldNewValues);
                    contact.LeadAdapterRowData       = lead.ToString();
                    personCustomFieldData.AddRange(contactCustomData);
                    personPhoneData.AddRange(contactPhoneData);

                    contact.ValidEmail = ValidateEmail(contact);

                    RawContact duplicate_data = null;
                    if (!String.IsNullOrEmpty(Convert.ToString(contact.PrimaryEmail)))
                    {
                        duplicate_data = persons.Where(p => string.Compare(p.PrimaryEmail, Convert.ToString(contact.PrimaryEmail), true) == 0).FirstOrDefault();
                    }
                    else
                    {
                        duplicate_data = persons.Where(p => string.Compare(p.FirstName, Convert.ToString(contact.FirstName), true) == 0 && string.Compare(p.LastName, Convert.ToString(contact.LastName), true) == 0).FirstOrDefault();
                    }

                    if (duplicate_data != null)
                    {
                        contact.IsDuplicate = true;
                    }

                    persons.Add(contact);
                }
            }
            catch (Exception ex)
            {
                Logger.Current.Error("An error occurred in zillow lead apapterprovider get data method", ex);
            }
            data.ContactCustomData = personCustomFieldData;
            data.ContactPhoneData  = personPhoneData;
            data.ContactData       = persons;
            return(data);
        }
コード例 #4
0
        //public override bool IsValidPhoneNumberLength(string phoneNumber)
        //{
        //    bool isValidPhone = false;
        //    string pattern = @"^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$";
        //    Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
        //    bool result = isValidPhone = regex.IsMatch(phoneNumber);
        //    return result;
        //}

        public override ImportContactsData GetContacts(string fileName, IEnumerable <FieldViewModel> customFields, int jobId, IEnumerable <DropdownValueViewModel> DropdownFields)
        {
            var persons             = new List <RawContact>();
            ImportContactsData data = new ImportContactsData();
            var                     personCustomFieldData = new List <ImportCustomData>();
            var                     personPhoneData       = new List <ImportPhoneData>();
            string                  leadsString           = string.Empty;
            IList <string>          hashes        = new List <string>();
            Func <RawContact, bool> ValidateEmail = (c) =>
            {
                /*
                 * If email is not empty or null then validate email
                 * If email is empty/or null then check for legth of first name and lastname
                 */
                if ((!string.IsNullOrEmpty(c.PrimaryEmail) && c.IsValidEmail(c.PrimaryEmail)) ||
                    (string.IsNullOrEmpty(c.PrimaryEmail) && !string.IsNullOrEmpty(c.FirstName) && !string.IsNullOrEmpty(c.LastName)))
                {
                    return(true);
                }
                return(false);
            };

            try
            {
                int      AccountID     = leadAdapterAndAccountMap.AccountID;
                var      ftpManager    = new FtpService();
                var      ftpcontent    = ftpManager.GetService(leadAdapterAndAccountMap.RequestGuid);
                DateTime lastProcessed = leadAdapterAndAccountMap.LastProcessed == null?DateTime.Now.ToUniversalTime().AddDays(-90) : leadAdapterAndAccountMap.LastProcessed.Value;

                string url = string.Format(ftpcontent.Host + "/{0}/{1}/{2}?date={3}&time={4}",
                                           ftpcontent.UserName, "xmlfeeds", ftpcontent.Password,
                                           lastProcessed.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture),
                                           lastProcessed.ToString("HH:mm"));
                leadsString = this.ProcessWebRequest(url);
                var xDocument           = XDocument.Parse(leadsString);
                var developmentElements = xDocument.Descendants("development");
                var builderagency       = xDocument.Descendants("developerbuilderagency");
                //string developerbuilderagency = builderagency != null ? builderagency.FirstOrDefault() == null ? "" : builderagency.FirstOrDefault().Value : "";
                LeadAdapterRecordStatus status = LeadAdapterRecordStatus.Undefined;
                customFields = customFields.Where(i => i.LeadAdapterType == (byte)LeadAdapterTypes.BuzzBuzzHomes && i.IsLeadAdapterField && i.StatusId == FieldStatus.Active);

                foreach (var developementElement in developmentElements)
                {
                    // developementElement attributes
                    //string developmentname = developementElement.Element("developmentname") != null ? developementElement.Element("developmentname").Value : "";
                    //string providerdevelopmentid = developementElement.Element("providerdevelopmentid") != null ? developementElement.Element("providerdevelopmentid").Value : "";
                    var leads = developementElement.Descendants("lead");



                    foreach (var lead in leads)
                    {
                        // created the guid for reference in the contact
                        var        guid    = Guid.NewGuid();
                        RawContact contact = new RawContact();
                        IList <ImportCustomData> contactCustomData = new List <ImportCustomData>();
                        IList <ImportPhoneData>  contactPhoneData  = new List <ImportPhoneData>();
                        var oldNewValues = new Dictionary <string, dynamic> {
                        };
                        StringBuilder CustomFieldData = new StringBuilder();

                        ////////////////////////////////////////////////
                        StringBuilder hash = new StringBuilder();

                        string firstName = string.Empty;
                        string lastName  = string.Empty;

                        string fullName = lead.Element("name").Value;

                        string[] name = fullName.Split(' ');
                        if (name.Length == 1)
                        {
                            firstName = name[0];
                        }
                        else if (name.Length > 1)
                        {
                            for (var i = 0; i < name.Length; i++)
                            {
                                if (i == 0)
                                {
                                    firstName = name[i];
                                }
                                else
                                {
                                    lastName = name[i] + " ";
                                }
                            }
                        }
                        string PrimaryEmail = lead.Elements("email").FirstOrDefault() == null ? string.Empty : lead.Elements("email").First().Value;
                        string CompanyName  = lead.Elements("Company").FirstOrDefault() == null ? null : lead.Elements("Company").First().Value;


                        IList <Email> emails = new List <Email>();

                        if (!string.IsNullOrEmpty(PrimaryEmail))
                        {
                            Email primaryemail = new Email()
                            {
                                EmailId   = PrimaryEmail,
                                AccountID = AccountID,
                                IsPrimary = true
                            };
                            emails.Add(primaryemail);
                            hash.Append("-").Append(PrimaryEmail);
                        }
                        else
                        {
                            hash.Append("-").Append("*****@*****.**");
                        }

                        Person person = new Person()
                        {
                            FirstName   = firstName,
                            LastName    = lastName,
                            CompanyName = CompanyName,
                            Emails      = emails,
                            AccountID   = AccountID
                        };

                        if (string.IsNullOrEmpty(firstName))
                        {
                            hash.Append("-").Append(string.Empty);
                        }
                        else
                        {
                            hash.Append("-").Append(firstName);
                        }

                        if (string.IsNullOrEmpty(lastName))
                        {
                            hash.Append("-").Append(string.Empty);
                        }
                        else
                        {
                            hash.Append("-").Append(lastName);
                        }

                        if (string.IsNullOrEmpty(CompanyName))
                        {
                            hash.Append("-").Append(string.Empty);
                        }
                        else
                        {
                            hash.Append("-").Append(CompanyName);
                        }



                        //var BrokenRules = person.GetBrokenRules();
                        bool IsNotValidContact = false;

                        bool isDuplicateFromFile = false;

                        if (!IsNotValidContact)
                        {
                            bool duplicateemailcount = hashes.Where(h => h.Contains(PrimaryEmail)).Any();
                            if (!string.IsNullOrEmpty(PrimaryEmail) && duplicateemailcount)
                            {
                                isDuplicateFromFile = true;
                            }
                            else if (!string.IsNullOrEmpty(PrimaryEmail) && !duplicateemailcount)
                            {
                                isDuplicateFromFile = false;
                            }
                            else if (string.IsNullOrEmpty(PrimaryEmail) && hashes.Where(h => h.Contains(hash.ToString())).Any())
                            {
                                isDuplicateFromFile = true;
                            }
                            else
                            {
                                isDuplicateFromFile = false;
                            }
                        }

                        SearchResult <Contact> duplicateResult = new SearchResult <Contact>();
                        if (!IsNotValidContact && isDuplicateFromFile == false)
                        {
                            SearchParameters parameters = new SearchParameters()
                            {
                                AccountId = AccountID
                            };
                            IEnumerable <Contact> duplicateContacts = contactService.CheckIfDuplicate(new CheckContactDuplicateRequest()
                            {
                                Person = person
                            }).Contacts;
                            duplicateResult = new SearchResult <Contact>()
                            {
                                Results = duplicateContacts, TotalHits = duplicateContacts != null?duplicateContacts.Count() : 0
                            };
                        }

                        if (IsNotValidContact)
                        {
                            status = LeadAdapterRecordStatus.ValidationFailed;
                        }
                        else if (isDuplicateFromFile)
                        {
                            status = LeadAdapterRecordStatus.DuplicateFromFile;
                        }
                        else if (duplicateResult.TotalHits > 0)
                        {
                            status = LeadAdapterRecordStatus.Updated;
                            guid   = duplicateResult.Results.FirstOrDefault().ReferenceId;
                        }
                        else
                        {
                            status = LeadAdapterRecordStatus.Added;
                        }

                        Contact duplicateperson = default(Person);
                        //contact.LeadAdapterRecordStatusId = (byte)status;
                        if (status == LeadAdapterRecordStatus.Updated)
                        {
                            duplicateperson = duplicateResult.Results.FirstOrDefault();
                        }
                        else
                        {
                            duplicateperson = new Person();
                        }
                        ///////////////////////////////////////////////////
                        try
                        {
                            XDocument doc      = XDocument.Parse(lead.ToString());
                            var       elements = doc.Root.DescendantNodes().OfType <XElement>();
                            foreach (XElement element in elements)
                            {
                                try
                                {
                                    var elementvalue = string.Empty;
                                    if (element.Name.LocalName.ToLower() == "name")
                                    {
                                        fullName = lead.Element("name").Value;

                                        string[] Name = fullName.Split(' ');

                                        if (Name.Length == 1)
                                        {
                                            firstName = Name[0];
                                        }
                                        else if (Name.Length > 1)
                                        {
                                            for (var i = 0; i < Name.Length; i++)
                                            {
                                                if (i == 0)
                                                {
                                                    firstName = Name[i];
                                                }
                                                else
                                                {
                                                    lastName = Name[i] + " ";
                                                }
                                            }
                                        }
                                        string previousfirstname = ((Person)duplicateperson).FirstName == null ? "" : ((Person)duplicateperson).FirstName;
                                        string previouslastname  = ((Person)duplicateperson).LastName == null ? "" : ((Person)duplicateperson).LastName;

                                        elementvalue      = previousfirstname + " " + previouslastname;
                                        contact.FirstName = firstName;
                                        contact.LastName  = lastName;
                                    }

                                    else if (element.Name.LocalName.ToLower() == "email")
                                    {
                                        Email primaryemail = duplicateperson.Emails == null ? null : duplicateperson.Emails.Where(i => i.IsPrimary == true).FirstOrDefault();
                                        if (primaryemail != null)
                                        {
                                            elementvalue = primaryemail.EmailId;
                                        }
                                        contact.PrimaryEmail = element.Value;
                                    }
                                    else if (element.Name.LocalName.ToLower() == "company")
                                    {
                                        elementvalue        = duplicateperson.CompanyName;
                                        contact.CompanyName = element.Value;
                                    }
                                    else if (element.Name.LocalName.ToLower() == "phone")
                                    {
                                        DropdownValueViewModel drpvalue = DropdownFields.Where(i => i.DropdownValueTypeID == (short)DropdownValueTypes.MobilePhone).FirstOrDefault();
                                        var             mobilephone     = default(Phone);
                                        ImportPhoneData phoneData       = new ImportPhoneData();
                                        phoneData.ReferenceID = guid;
                                        if (drpvalue != null && !string.IsNullOrEmpty(element.Value))
                                        {
                                            string nonnumericstring = GetNonNumericData(element.Value);
                                            if (IsValidPhoneNumberLength(nonnumericstring))
                                            {
                                                contact.PhoneData     = drpvalue.DropdownValueID.ToString() + "|" + nonnumericstring;
                                                phoneData.PhoneType   = (int?)drpvalue.DropdownValueID;
                                                phoneData.PhoneNumber = nonnumericstring;
                                                contactPhoneData.Add(phoneData);
                                            }
                                        }

                                        if (mobilephone != null)
                                        {
                                            elementvalue = mobilephone.Number;
                                        }
                                    }
                                    else
                                    {
                                        var customField             = customFields.Where(i => i.Title.Replace(" ", string.Empty).ToLower() == (element.Name.LocalName.ToLower() + "(" + LeadAdapterTypes.BuzzBuzzHomes.ToString().ToLower() + ")")).FirstOrDefault();
                                        ImportCustomData customData = new ImportCustomData();
                                        customData.FieldID     = customField.FieldId;
                                        customData.FieldTypeID = (int?)customField.FieldInputTypeId;
                                        customData.ReferenceID = guid;

                                        if (customField != null)
                                        {
                                            var customfielddata = duplicateperson.CustomFields == null ? null : duplicateperson.CustomFields.Where(i => i.CustomFieldId == customField.FieldId).FirstOrDefault();
                                            if (customfielddata != null)
                                            {
                                                elementvalue = customfielddata.Value;
                                            }

                                            if (customField.FieldInputTypeId == FieldType.date || customField.FieldInputTypeId == FieldType.datetime || customField.FieldInputTypeId == FieldType.time)
                                            {
                                                DateTime converteddate;
                                                if (DateTime.TryParse(element.Value.Trim(), out converteddate))
                                                {
                                                    CustomFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + converteddate.ToString("MM/dd/yyyy hh:mm tt"));
                                                    customData.FieldValue = converteddate.ToString("MM/dd/yyyy hh:mm tt");
                                                    contactCustomData.Add(customData);
                                                }
                                            }
                                            else if (customField.FieldInputTypeId == FieldType.number)
                                            {
                                                double number;
                                                if (double.TryParse(element.Value.Trim(), out number))
                                                {
                                                    CustomFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + number.ToString());
                                                    customData.FieldValue = number.ToString();
                                                    contactCustomData.Add(customData);
                                                }
                                            }
                                            else if (customField.FieldInputTypeId == FieldType.url)
                                            {
                                                if (IsValidURL(element.Value.Trim()))
                                                {
                                                    CustomFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + element.Value.Trim());
                                                    customData.FieldValue = element.Value.Trim();
                                                }
                                            }
                                            else
                                            {
                                                CustomFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + element.Value.Trim());
                                                customData.FieldValue = element.Value.Trim();
                                            }
                                            contactCustomData.Add(customData);
                                        }
                                    }
                                    if (!oldNewValues.ContainsKey(element.Name.LocalName))
                                    {
                                        oldNewValues.Add(element.Name.LocalName, new { OldValue = string.IsNullOrEmpty(elementvalue) ? string.Empty : elementvalue, NewValue = element.Value });
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Logger.Current.Error("An exception occured in Genereating old new values element in BuzzBuzz Homes : " + element.Name.LocalName, ex);
                                    continue;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.Current.Error("An exception occured in Genereating old new values element in Buzzbuzz homes : ", ex);
                        }
                        if (CustomFieldData.Length > 0)
                        {
                            CustomFieldData.Remove(0, 1);
                        }

                        contact.CustomFieldsData          = CustomFieldData.ToString();
                        contact.CustomFieldsData          = CustomFieldData.ToString();
                        contact.ReferenceId               = guid;
                        contact.AccountID                 = AccountID;
                        contact.LeadAdapterRecordStatusId = (byte)status;
                        contact.JobID = jobId;
                        JavaScriptSerializer js = new JavaScriptSerializer();
                        contact.LeadAdapterSubmittedData = js.Serialize(oldNewValues);
                        contact.LeadAdapterRowData       = lead.ToString();
                        contact.ContactStatusID          = 1;
                        contact.ContactTypeID            = 1;
                        personCustomFieldData.AddRange(contactCustomData);
                        personPhoneData.AddRange(contactPhoneData);

                        contact.ValidEmail = ValidateEmail(contact);

                        RawContact duplicate_data = null;
                        if (!String.IsNullOrEmpty(Convert.ToString(contact.PrimaryEmail)))
                        {
                            duplicate_data = persons.Where(p => string.Compare(p.PrimaryEmail, Convert.ToString(contact.PrimaryEmail), true) == 0).FirstOrDefault();
                        }
                        else
                        {
                            duplicate_data = persons.Where(p => string.Compare(p.FirstName, Convert.ToString(contact.FirstName), true) == 0 && string.Compare(p.LastName, Convert.ToString(contact.LastName), true) == 0).FirstOrDefault();
                        }

                        if (duplicate_data != null)
                        {
                            contact.IsDuplicate = true;
                            //RawContact updatedperson = MergeDuplicateData(duplicate_data, contact, guid);
                            //duplicate_data = updatedperson;
                        }
                        persons.Add(contact);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Current.Error("An error occurred in zillow lead apapterprovider get data method", ex);
            }
            data.ContactCustomData = personCustomFieldData;
            data.ContactPhoneData  = personPhoneData;
            data.ContactData       = persons;
            return(data);
        }
コード例 #5
0
        public override ImportContactsData GetContacts(string fileName,
                                                       IEnumerable <ApplicationServices.ViewModels.FieldViewModel> Fields, int jobId, IEnumerable <ApplicationServices.ViewModels.DropdownValueViewModel> DropdownFields)
        {
            ImportContactsData data            = new ImportContactsData();
            var                     ftpManager = new FtpService();
            Developments            result;
            Func <RawContact, bool> ValidateEmail = (c) =>
            {
                /*
                 * If email is not empty or null then validate email
                 * If email is empty/or null then check for legth of first name and lastname
                 */
                if ((!string.IsNullOrEmpty(c.PrimaryEmail) && c.IsValidEmail(c.PrimaryEmail)) ||
                    (string.IsNullOrEmpty(c.PrimaryEmail) && !string.IsNullOrEmpty(c.FirstName) && !string.IsNullOrEmpty(c.LastName)))
                {
                    return(true);
                }
                return(false);
            };

            try
            {
                var    ftpcontent = ftpManager.GetService(leadAdapterAndAccountMap.RequestGuid);
                string url        = ftpcontent.Host;
                var    xml        = this.ProcessWebRequest(url);
                var    serializer = new XmlSerializer(typeof(Developments));

                //Read Lead XML File into C# Class
                using (TextReader reader = new StringReader(xml))
                {
                    result = (Developments)serializer.Deserialize(reader);
                }

                LeadAdapterRecordStatus status = LeadAdapterRecordStatus.Undefined;
                int accountID   = leadAdapterAndAccountMap.AccountID;
                var communities = result.AllLeads;

                Func <string, string> GetValue = (s) =>
                {
                    return((string.IsNullOrEmpty(s)) ? string.Empty : s);
                };

                /*
                 * TODO: Process Leads
                 * */
                string[]       laCommunities         = null;//string.IsNullOrEmpty(leadAdapterAndAccountMap.CommunityNumber) ? default(string[]) : leadAdapterAndAccountMap.CommunityNumber.Split(',');
                var            builderNumber         = string.IsNullOrEmpty(leadAdapterAndAccountMap.BuilderNumber) ? string.Empty : leadAdapterAndAccountMap.BuilderNumber.ToLower();
                var            builderNumberPass     = true;
                IList <string> hashes                = new List <string>();
                var            personCustomFieldData = new List <ImportCustomData>();
                var            persons               = new List <RawContact>();

                #region Process Community Wise
                foreach (var community in communities)
                {
                    var communityName       = string.IsNullOrEmpty(community.CommunityName) ? string.Empty : community.CommunityName;
                    var communityNumberPass = false;

                    if ((laCommunities != null && laCommunities.Any(c => c.ToLower().Contains(communityName.ToLower()))) || laCommunities == null)
                    {
                        communityNumberPass = true;
                    }
                    foreach (var lead in community.leads)
                    {
                        #region Process Lead
                        var oldNewValues = new Dictionary <string, dynamic>()
                        {
                        };
                        var           guid                = Guid.NewGuid();
                        var           firstName           = GetValue(lead.Name);
                        var           lastName            = string.Empty;
                        var           primaryEmail        = GetValue(lead.Email);
                        var           company             = string.Empty;
                        StringBuilder hash                = new StringBuilder();
                        bool          isNotValidContact   = false;
                        bool          isDuplicateFromFile = false;

                        Action <string> Append = (a) =>
                        {
                            hash.Append("-").Append(a);
                        };

                        IList <Email> emails = new List <Email>();
                        if (!string.IsNullOrEmpty(primaryEmail))
                        {
                            Email primaryEmailObject = new Email()
                            {
                                EmailId   = primaryEmail,
                                AccountID = leadAdapterAndAccountMap.AccountID,
                                IsPrimary = true
                            };
                            emails.Add(primaryEmailObject);
                            hash.Append("-").Append(primaryEmail);
                        }
                        else
                        {
                            hash.Append("-").Append("*****@*****.**");
                        }

                        Person person = new Person()
                        {
                            FirstName   = firstName,
                            LastName    = lastName,
                            CompanyName = company,
                            Emails      = emails,
                            AccountID   = accountID
                        };
                        Append(firstName);
                        Append(lastName);
                        Append(company);

                        SearchResult <Contact> duplicateResult = new SearchResult <Contact>();
                        if (!isNotValidContact && builderNumberPass && communityNumberPass)
                        {
                            bool duplicatEemailCount = hashes.Where(h => h.Contains(primaryEmail)).Any();
                            if (!string.IsNullOrEmpty(primaryEmail) && duplicatEemailCount)
                            {
                                isDuplicateFromFile = true;
                            }
                            else if (!string.IsNullOrEmpty(primaryEmail) && !duplicatEemailCount)
                            {
                                isDuplicateFromFile = false;
                            }
                            else if (string.IsNullOrEmpty(primaryEmail) && hashes.Where(h => h.Contains(hash.ToString())).Any())
                            {
                                isDuplicateFromFile = true;
                            }
                            else
                            {
                                isDuplicateFromFile = false;
                            }
                        }

                        if (!isNotValidContact && builderNumberPass && isDuplicateFromFile == false && communityNumberPass)
                        {
                            SearchParameters parameters = new SearchParameters()
                            {
                                AccountId = accountID
                            };
                            IEnumerable <Contact> duplicateContacts = contactService.CheckIfDuplicate(new CheckContactDuplicateRequest()
                            {
                                Person = person
                            }).Contacts;
                            duplicateResult = new SearchResult <Contact>()
                            {
                                Results = duplicateContacts, TotalHits = duplicateContacts != null?duplicateContacts.Count() : 0
                            };
                        }

                        if (!builderNumberPass)
                        {
                            status = LeadAdapterRecordStatus.BuilderNumberFailed;
                        }
                        else if (!communityNumberPass)
                        {
                            status = LeadAdapterRecordStatus.CommunityNumberFailed;
                        }
                        else if (isNotValidContact)
                        {
                            status = LeadAdapterRecordStatus.ValidationFailed;
                        }
                        else if (isDuplicateFromFile)
                        {
                            status = LeadAdapterRecordStatus.DuplicateFromFile;
                        }
                        else if (duplicateResult.TotalHits > 0)
                        {
                            status = LeadAdapterRecordStatus.Updated;
                            //guid = duplicateResult.Results.FirstOrDefault().ReferenceId;
                        }
                        else
                        {
                            status = LeadAdapterRecordStatus.Added;
                        }

                        Contact duplicateperson = new Person()
                        {
                            Emails = new List <Email>()
                            {
                                new Email()
                            }
                        };
                        if (status == LeadAdapterRecordStatus.Updated)
                        {
                            duplicateperson = duplicateResult.Results.FirstOrDefault();
                        }


                        RawContact contact = new RawContact();
                        IList <ImportCustomData> contactCustomData = new List <ImportCustomData>();
                        IList <ImportPhoneData>  contactPhoneData  = new List <ImportPhoneData>();

                        StringBuilder CustomFieldData = new StringBuilder();

                        Action <string, string, string> AddOldNewValues = (field, oldvalue, newvalue) =>
                        {
                            if (!oldNewValues.ContainsKey(field))
                            {
                                oldNewValues.Add(field, new { OldValue = string.IsNullOrEmpty(oldvalue) ? string.Empty : oldvalue, NewValue = newvalue });
                            }
                        };
                        try
                        {
                            ImportCustomData customData = new ImportCustomData();

                            contact.FirstName = firstName;
                            AddOldNewValues("Name", ((Person)duplicateperson).FirstName, firstName);

                            contact.PrimaryEmail = primaryEmail;
                            AddOldNewValues("Email", ((Person)duplicateperson).Emails.FirstOrDefault().EmailId, primaryEmail);

                            foreach (var propertyInfo in typeof(Lead).GetProperties())
                            {
                                #region Process Customfields
                                var    oldValue     = string.Empty;
                                string newValue     = string.Empty;
                                string propertyName = propertyInfo.Name.Trim();
                                var    customField  = Fields.FirstOrDefault(f => f.Title.Replace(" ", "").ToLower().Contains(propertyInfo.Name));
                                if (customField != null)
                                {
                                    newValue = ((string)propertyInfo.GetValue(lead, null));
                                    var customfielddata = duplicateperson.CustomFields == null ? null : duplicateperson.CustomFields.Where(i => i.CustomFieldId == customField.FieldId).FirstOrDefault();
                                    if (customfielddata != null)
                                    {
                                        oldValue = customfielddata.Value;
                                    }

                                    customData.FieldID     = customField.FieldId;
                                    customData.FieldTypeID = (int?)customField.FieldInputTypeId;
                                    customData.ReferenceID = guid;

                                    if (customField.FieldInputTypeId == FieldType.date || customField.FieldInputTypeId == FieldType.datetime || customField.FieldInputTypeId == FieldType.time)
                                    {
                                        DateTime converteddate;
                                        if (DateTime.TryParse(newValue, out converteddate))
                                        {
                                            CustomFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + converteddate.ToString("MM/dd/yyyy hh:mm tt"));
                                            customData.FieldValue = converteddate.ToString("MM/dd/yyyy hh:mm tt");
                                        }
                                    }
                                    else if (customField.FieldInputTypeId == FieldType.number)
                                    {
                                        double number;
                                        if (double.TryParse(newValue, out number))
                                        {
                                            CustomFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + number.ToString());
                                            customData.FieldValue = number.ToString();
                                        }
                                    }
                                    else if (customField.FieldInputTypeId == FieldType.url)
                                    {
                                        if (IsValidURL(newValue))
                                        {
                                            CustomFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + newValue);
                                            customData.FieldValue = newValue;
                                        }
                                    }
                                    else
                                    {
                                        CustomFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + newValue);
                                        customData.FieldValue = newValue;
                                    }
                                    contactCustomData.Add(customData);

                                    AddOldNewValues(propertyInfo.Name, oldValue, newValue);
                                }
                                #endregion
                            }
                            var brokenrules = contact.GetBrokenRules();
                            if ((brokenrules != null && brokenrules.Any()) && builderNumberPass && communityNumberPass)
                            {
                                status = LeadAdapterRecordStatus.ValidationFailed;
                            }
                            contact.ReferenceId               = guid;
                            contact.AccountID                 = accountID;
                            contact.IsBuilderNumberPass       = builderNumberPass;
                            contact.IsCommunityNumberPass     = communityNumberPass;
                            contact.LeadAdapterRecordStatusId = (byte)status;
                            contact.JobID              = jobId;
                            contact.ContactStatusID    = 1;
                            contact.ContactTypeID      = 1;
                            contact.LeadAdapterRowData = lead.ToString();
                            JavaScriptSerializer js = new JavaScriptSerializer();
                            contact.LeadAdapterSubmittedData = js.Serialize(oldNewValues);
                        }
                        catch (Exception ex)
                        {
                            Logger.Current.Error("Error while preparing contact - Homefinder", ex);
                            ex.Data.Add("Account", accountID);
                        }
                        personCustomFieldData.AddRange(contactCustomData);

                        if (CustomFieldData.Length > 0)
                        {
                            CustomFieldData.Remove(0, 1);
                        }
                        contact.CustomFieldsData = CustomFieldData.ToString();

                        contact.ValidEmail = ValidateEmail(contact);

                        RawContact duplicate_data = null;
                        if (!String.IsNullOrEmpty(Convert.ToString(contact.PrimaryEmail)))
                        {
                            duplicate_data = persons.Where(p => string.Compare(p.PrimaryEmail, Convert.ToString(contact.PrimaryEmail), true) == 0).FirstOrDefault();
                        }
                        else
                        {
                            duplicate_data = persons.Where(p => string.Compare(p.FirstName, Convert.ToString(contact.FirstName), true) == 0 && string.Compare(p.LastName, Convert.ToString(contact.LastName), true) == 0).FirstOrDefault();
                        }

                        if (duplicate_data != null)
                        {
                            contact.IsDuplicate = true;
                        }
                        persons.Add(contact);
                        #endregion
                    }
                }
                data.ContactData       = persons;
                data.ContactCustomData = personCustomFieldData;
                #endregion
            }
            catch (Exception ex)
            {
                Logger.Current.Error("Error while processing GetContacts", ex);
            }
            return(data);
        }
コード例 #6
0
        private ImportContactsData ProcessContacts(IEnumerable <FacebookLead> fbLeads)
        {
            ImportContactsData data = new ImportContactsData();

            if (fbLeads != null && fbLeads.Any() && fbLeads.Where(w => w.FieldData != null && w.FieldData.Any()).Any())
            {
                int jobLogId = this.InsertLeadAdapterJobLog();
                Logger.Current.Informational("Request received for processing fbleads to importcontactdata");
                var persons = new List <RawContact>();
                var personCustomFieldData = new List <ImportCustomData>();
                var personPhoneData       = new List <ImportPhoneData>();

                Func <RawContact, bool> ValidateEmail = (c) =>
                {
                    /*
                     * If email is not empty or null then validate email
                     * If email is empty/or null then check for legth of first name and lastname
                     */
                    if ((!string.IsNullOrEmpty(c.PrimaryEmail) && c.IsValidEmail(c.PrimaryEmail)) ||
                        (string.IsNullOrEmpty(c.PrimaryEmail) && !string.IsNullOrEmpty(c.FirstName) && !string.IsNullOrEmpty(c.LastName)))
                    {
                        return(true);
                    }
                    return(false);
                };

                foreach (var lead in fbLeads)
                {
                    RawContact contact = new RawContact();
                    IList <ImportPhoneData>  contactPhoneData  = new List <ImportPhoneData>();
                    IList <ImportCustomData> contactCustomData = new List <ImportCustomData>();
                    List <FacebookAttribute> attributes        = new List <FacebookAttribute>();

                    if (lead != null && lead.FieldData != null)
                    {
                        var guid = Guid.NewGuid();
                        LeadAdapterRecordStatus status = LeadAdapterRecordStatus.Undefined;
                        string firstName      = string.Empty;
                        string lastName       = string.Empty;
                        string company        = string.Empty;
                        string primaryEmail   = string.Empty;
                        string zipCode        = string.Empty;
                        string phone          = string.Empty;
                        string militaryStatus = string.Empty;
                        string addressline1   = string.Empty;
                        string state          = string.Empty;
                        string city           = string.Empty;

                        foreach (var field in lead.FieldData)
                        {
                            if (field.Name == "first_name" && field.Values != null)
                            {
                                attributes.Add(new FacebookAttribute()
                                {
                                    LocalName = field.Name, Value = field.Values[0]
                                });
                                firstName = field.Values[0];
                            }
                            else if (field.Name == "last_name" && field.Values != null)
                            {
                                attributes.Add(new FacebookAttribute()
                                {
                                    LocalName = field.Name, Value = field.Values[0]
                                });
                                lastName = field.Values[0];
                            }
                            else if (field.Name == "full_name" && field.Values != null)
                            {
                                string[] names = field.Values[0].Split();
                                if (names != null && names.Any())
                                {
                                    firstName = names[0];
                                    lastName  = names[1];
                                }
                                attributes.Add(new FacebookAttribute()
                                {
                                    LocalName = "first_name", Value = firstName
                                });
                                attributes.Add(new FacebookAttribute()
                                {
                                    LocalName = "last_name", Value = lastName
                                });
                            }
                            else if (field.Name == "company_name" && field.Values != null)
                            {
                                attributes.Add(new FacebookAttribute()
                                {
                                    LocalName = field.Name, Value = field.Values[0]
                                });
                                company = field.Values[0];
                            }
                            else if (field.Name == "email" && field.Values != null)
                            {
                                attributes.Add(new FacebookAttribute()
                                {
                                    LocalName = field.Name, Value = field.Values[0]
                                });
                                primaryEmail = field.Values[0];
                            }
                            else if ((field.Name == "post_code" || field.Name == "zip_code") && field.Values != null)
                            {
                                attributes.Add(new FacebookAttribute()
                                {
                                    LocalName = "post_code", Value = field.Values[0]
                                });
                                zipCode = field.Values[0];
                            }
                            else if ((field.Name == "phone_number" || field.Name == "work_phone_number") && field.Values != null)
                            {
                                attributes.Add(new FacebookAttribute()
                                {
                                    LocalName = "phone", Value = field.Values[0]
                                });
                                phone = field.Values[0];
                            }
                            else if (field.Name == "military_status" && field.Values != null)
                            {
                                string value = new string(field.Values[0].Take(11).ToArray());
                                attributes.Add(new FacebookAttribute()
                                {
                                    LocalName = "militarystatus", Value = value
                                });
                                militaryStatus = value;
                            }
                            else if (field.Name == "street_address" && field.Values != null)
                            {
                                attributes.Add(new FacebookAttribute()
                                {
                                    LocalName = field.Name, Value = field.Values[0]
                                });
                                addressline1 = field.Values[0];
                            }
                            else if (field.Name == "city" && field.Values != null)
                            {
                                attributes.Add(new FacebookAttribute()
                                {
                                    LocalName = field.Name, Value = field.Values[0]
                                });
                                city = field.Values[0];
                            }
                            else if (field.Name == "state" && field.Values != null)
                            {
                                attributes.Add(new FacebookAttribute()
                                {
                                    LocalName = field.Name, Value = field.Values[0]
                                });
                                state = field.Values[0];
                            }
                        }

                        StringBuilder  hash   = new StringBuilder();
                        IList <Email>  emails = new List <Email>();
                        IList <string> hashes = new List <string>();
                        if (!string.IsNullOrEmpty(primaryEmail))
                        {
                            Email primaryemail = new Email()
                            {
                                EmailId   = primaryEmail,
                                AccountID = leadAdapterAndAccountMap.AccountID,
                                IsPrimary = true
                            };
                            emails.Add(primaryemail);
                            hash.Append("-").Append(primaryEmail);
                        }
                        else
                        {
                            hash.Append("-").Append("*****@*****.**");
                        }

                        Person person = new Person()
                        {
                            FirstName   = firstName,
                            LastName    = lastName,
                            CompanyName = company,
                            Emails      = emails,
                            AccountID   = AccountID
                        };
                        if (string.IsNullOrEmpty(firstName))
                        {
                            hash.Append("-").Append(string.Empty);
                        }
                        else
                        {
                            hash.Append("-").Append(firstName);
                        }

                        if (string.IsNullOrEmpty(lastName))
                        {
                            hash.Append("-").Append(string.Empty);
                        }
                        else
                        {
                            hash.Append("-").Append(lastName);
                        }

                        if (string.IsNullOrEmpty(company))
                        {
                            hash.Append("-").Append(string.Empty);
                        }
                        else
                        {
                            hash.Append("-").Append(company);
                        }

                        SearchResult <Contact> duplicateResult = new SearchResult <Contact>();
                        SearchParameters       parameters      = new SearchParameters()
                        {
                            AccountId = AccountID
                        };
                        IEnumerable <Contact> duplicateContacts = contactService.CheckIfDuplicate(new CheckContactDuplicateRequest()
                        {
                            Person = person
                        }).Contacts;
                        duplicateResult = new SearchResult <Contact>()
                        {
                            Results = duplicateContacts, TotalHits = duplicateContacts != null?duplicateContacts.Count() : 0
                        };

                        if (duplicateResult.TotalHits > 0)
                        {
                            status = LeadAdapterRecordStatus.Updated;
                        }
                        else
                        {
                            status = LeadAdapterRecordStatus.Added;
                        }

                        Contact duplicateperson = default(Person);
                        if (status == LeadAdapterRecordStatus.Updated)
                        {
                            duplicateperson = duplicateResult.Results.FirstOrDefault();
                        }
                        else
                        {
                            duplicateperson = new Person();
                        }

                        StringBuilder CustomFieldData = new StringBuilder();
                        var           oldNewValues    = new Dictionary <string, dynamic> {
                        };
                        foreach (var attribute in attributes)
                        {
                            ImportCustomData customData = new ImportCustomData();
                            try
                            {
                                var elementvalue = string.Empty;
                                if (attribute.LocalName == "first_name")
                                {
                                    elementvalue      = ((Person)duplicateperson).FirstName == null ? "" : ((Person)duplicateperson).FirstName;
                                    contact.FirstName = attribute.Value;
                                }
                                else if (attribute.LocalName == "last_name")
                                {
                                    elementvalue     = ((Person)duplicateperson).LastName;
                                    contact.LastName = attribute.Value;
                                }
                                else if (attribute.LocalName.ToLower() == "email")
                                {
                                    Email primaryemail = duplicateperson.Emails == null ? null : duplicateperson.Emails.Where(i => i.IsPrimary == true).FirstOrDefault();
                                    if (primaryemail != null)
                                    {
                                        elementvalue = primaryemail.EmailId;
                                    }
                                    contact.PrimaryEmail = attribute.Value;
                                }
                                else if (attribute.LocalName.ToLower() == "company")
                                {
                                    elementvalue        = duplicateperson.CompanyName;
                                    contact.CompanyName = attribute.Value;
                                }
                                else if (attribute.LocalName.ToLower() == "post_code")
                                {
                                    contact.ZipCode = attribute.Value;
                                }
                                else if (attribute.LocalName.ToLower() == "street_address")
                                {
                                    contact.AddressLine1 = attribute.Value;
                                }
                                else if (attribute.LocalName.ToLower() == "city")
                                {
                                    contact.City = attribute.Value;
                                }
                                else if (attribute.LocalName.ToLower() == "state")
                                {
                                    contact.State = attribute.Value;
                                }
                                else if (attribute.LocalName.ToLower() == "phone")
                                {
                                    DropdownValueViewModel drpvalue = phoneDropdownFields.Where(i => i.DropdownValueTypeID == (short)DropdownValueTypes.MobilePhone).FirstOrDefault();
                                    if (duplicateperson.Phones != null)
                                    {
                                        var mobilePhone = duplicateperson.Phones.Where(w => w.DropdownValueTypeID == (short)DropdownValueTypes.MobilePhone).FirstOrDefault();
                                        if (mobilePhone != null)
                                        {
                                            elementvalue = mobilePhone.Number;
                                        }
                                    }
                                    ImportPhoneData phoneData = new ImportPhoneData();
                                    phoneData.ReferenceID = guid;

                                    string nonnumericstring = GetNonNumericData(attribute.Value);
                                    if (IsValidPhoneNumberLength(nonnumericstring))
                                    {
                                        contact.PhoneData     = drpvalue.DropdownValueID.ToString() + "|" + nonnumericstring;
                                        phoneData.PhoneType   = (int?)drpvalue.DropdownValueID;
                                        phoneData.PhoneNumber = nonnumericstring;
                                        contactPhoneData.Add(phoneData);
                                    }
                                }
                                else if (attribute.LocalName.ToLower() == "militarystatus")
                                {
                                    var customField = customFields.Where(i => i.Title.Replace(" ", string.Empty).ToLower() == (attribute.LocalName.ToLower() + "(" + LeadAdapterTypes.Facebook.ToString().ToLower() + ")")).FirstOrDefault();
                                    if (customField != null)
                                    {
                                        var customfielddata = duplicateperson.CustomFields == null ? null : duplicateperson.CustomFields.Where(i => i.CustomFieldId == customField.FieldId).FirstOrDefault();
                                        if (customfielddata != null)
                                        {
                                            elementvalue = customfielddata.Value;
                                        }

                                        customData.FieldID     = customField.FieldId;
                                        customData.FieldTypeID = (int?)customField.FieldInputTypeId;
                                        customData.ReferenceID = guid;
                                        CustomFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + attribute.Value.Trim());
                                        customData.FieldValue = attribute.Value.Trim();

                                        contactCustomData.Add(customData);
                                    }
                                }
                                if (!oldNewValues.ContainsKey(attribute.LocalName))
                                {
                                    oldNewValues.Add(attribute.LocalName, new { OldValue = string.IsNullOrEmpty(elementvalue) ? string.Empty : elementvalue, NewValue = attribute.Value.Trim() });
                                }

                                var brokenrules = contact.GetBrokenRules();
                                if (brokenrules != null && brokenrules.Any())
                                {
                                    status = LeadAdapterRecordStatus.ValidationFailed;
                                }
                                contact.ReferenceId               = guid;
                                contact.AccountID                 = AccountID;
                                contact.IsBuilderNumberPass       = true;
                                contact.IsCommunityNumberPass     = true;
                                contact.LeadAdapterRecordStatusId = (byte)status;
                                contact.JobID           = jobLogId;
                                contact.ContactStatusID = 1;
                                contact.ContactTypeID   = 1;
                                JavaScriptSerializer js = new JavaScriptSerializer();
                                string submittedData    = js.Serialize(oldNewValues);
                                contact.LeadAdapterRowData       = submittedData;
                                contact.LeadAdapterSubmittedData = submittedData;
                            }
                            catch (Exception Ex)
                            {
                                Logger.Current.Error("An error occured while processing contact fields, facebook lead adapter", Ex);
                            }
                        }
                    }
                    contact.ValidEmail = ValidateEmail(contact);
                    persons.Add(contact);
                    personPhoneData.AddRange(contactPhoneData);
                    personCustomFieldData.AddRange(contactCustomData);
                }
                data.ContactData       = persons;
                data.ContactPhoneData  = personPhoneData;
                data.ContactCustomData = personCustomFieldData;
            }
            return(data);
        }
コード例 #7
0
        private void processContacts(Node node, NodeAttributes attributes,
                                     IEnumerable <FieldViewModel> customFields, int jobId,
                                     IEnumerable <DropdownValueViewModel> dropdownFields, string fileName)
        {
            #region Declarations
            StringBuilder                hash                = new StringBuilder();
            IList <Email>                emails              = new List <Email>();
            var                          guid                = Guid.NewGuid();
            RawContact                   contact             = new RawContact();
            IList <ImportCustomData>     contactCustomData   = new List <ImportCustomData>();
            IList <ImportPhoneData>      contactPhoneData    = new List <ImportPhoneData>();
            StringBuilder                customFieldData     = new StringBuilder();
            bool                         isDuplicateFromFile = false;
            LeadAdapterRecordStatus      status              = LeadAdapterRecordStatus.Undefined;
            SearchResult <Contact>       duplicateResult     = new SearchResult <Contact>();
            Dictionary <string, dynamic> oldNewValues        = new Dictionary <string, dynamic> {
            };
            #endregion

            #region BuilderNumber Validation
            string builderNumber     = attributes[_fieldMappings.GetOrDefault("BuilderNumber")].Value;
            bool   builderNumberPass = leadAdapterAndAccountMap.BuilderNumber.ToLower().Split(',').Contains(builderNumber.ToLower());
            #endregion

            #region Community Number Validation
            string communityNumber     = attributes[_fieldMappings.GetOrDefault("CommunityNumber")].Value;
            bool   communityNumberPass = true;
            #endregion

            #region ContactsProcessing
            string firstName    = attributes[_fieldMappings.GetOrDefault("FirstName")].Value;
            string lastName     = attributes[_fieldMappings.GetOrDefault("LastName")].Value;
            string primaryEmail = attributes[_fieldMappings.GetOrDefault("Email")].Value;
            string companyName  = string.Empty;

            #region HashPreparation
            Action <string> HashAppend = (n) =>
            {
                if (string.IsNullOrEmpty(n))
                {
                    hash.Append("-").Append(string.Empty);
                }
                else
                {
                    hash.Append("-").Append(n);
                }
            };

            if (!string.IsNullOrEmpty(primaryEmail))
            {
                Email _primaryemail = new Email()
                {
                    EmailId   = primaryEmail,
                    AccountID = leadAdapterAndAccountMap.AccountID,
                    IsPrimary = true
                };
                emails.Add(_primaryemail);
                hash.Append("-").Append(primaryEmail);
            }
            else
            {
                hash.Append("-").Append("*****@*****.**");
            }

            HashAppend(firstName);
            HashAppend(lastName);
            HashAppend(companyName);
            #endregion

            Person person = new Person()
            {
                FirstName   = firstName,
                LastName    = lastName,
                CompanyName = companyName,
                Emails      = emails,
                AccountID   = AccountID
            };


            if (builderNumberPass && communityNumberPass)
            {
                bool duplicatEemailCount = hashes.Any(h => !string.IsNullOrEmpty(primaryEmail) && h.Contains(primaryEmail));
                if (duplicatEemailCount ||
                    (string.IsNullOrEmpty(primaryEmail) && hashes.Where(h => h.Contains(hash.ToString())).Any()))
                {
                    isDuplicateFromFile = true;
                }
                else if (!duplicatEemailCount)
                {
                    isDuplicateFromFile = false;
                }
            }

            hashes.Add(hash.ToString());


            if (builderNumberPass && communityNumberPass)
            {
                SearchParameters parameters = new SearchParameters()
                {
                    AccountId = AccountID
                };
                IEnumerable <Contact> duplicateContacts = contactService.CheckIfDuplicate(new CheckContactDuplicateRequest()
                {
                    Person = person
                }).Contacts;
                duplicateResult = new SearchResult <Contact>()
                {
                    Results = duplicateContacts, TotalHits = duplicateContacts != null?duplicateContacts.Count() : 0
                };
            }

            if (!builderNumberPass)
            {
                status = LeadAdapterRecordStatus.BuilderNumberFailed;
            }
            else if (!communityNumberPass)
            {
                status = LeadAdapterRecordStatus.CommunityNumberFailed;
            }
            else if (isDuplicateFromFile)
            {
                status = LeadAdapterRecordStatus.DuplicateFromFile;
            }
            else if (duplicateResult.TotalHits > 0)
            {
                status = LeadAdapterRecordStatus.Updated;
                guid   = duplicateResult.Results.FirstOrDefault().ReferenceId;
            }
            else
            {
                status = LeadAdapterRecordStatus.Added;
            }


            Contact duplicatePerson = default(Person);

            if (status == LeadAdapterRecordStatus.Updated)
            {
                duplicatePerson = duplicateResult.Results.FirstOrDefault();
            }
            else
            {
                duplicatePerson = new Person();
            }

            Func <NodeAttribute, string, bool> checkIfStandardField = (name, field) =>
            {
                return(name.Name.ToLower() == _fieldMappings.GetOrDefault(field).NullSafeToLower());
            };

            try
            {
                foreach (var attribute in attributes)
                {
                    var name  = attribute.Name.ToLower();
                    var value = attribute.Value;

                    ImportCustomData customData = new ImportCustomData();
                    try
                    {
                        var elementValue = string.Empty;
                        if (checkIfStandardField(attribute, "FirstName"))
                        {
                            elementValue      = ((Person)duplicatePerson).FirstName == null ? string.Empty : ((Person)duplicatePerson).FirstName;
                            contact.FirstName = value;
                        }
                        else if (checkIfStandardField(attribute, "LastName"))
                        {
                            elementValue     = ((Person)duplicatePerson).LastName;
                            contact.LastName = value;
                        }
                        else if (checkIfStandardField(attribute, "Email"))
                        {
                            Email primaryemail = duplicatePerson.Emails.IsAny() ? duplicatePerson.Emails.Where(i => i.IsPrimary == true).FirstOrDefault() : null;
                            if (primaryemail != null)
                            {
                                elementValue = primaryemail.EmailId;
                            }
                            contact.PrimaryEmail = value;
                        }
                        else if (checkIfStandardField(attribute, "Company"))
                        {
                            // get company dynamic
                            elementValue        = duplicatePerson.CompanyName;
                            contact.CompanyName = value;
                        }
                        else if (checkIfStandardField(attribute, "PhoneNumber") || checkIfStandardField(attribute, "Phone"))
                        {
                            DropdownValueViewModel dropdownValue = dropdownFields.Where(i => i.DropdownValueTypeID == (short)DropdownValueTypes.MobilePhone).FirstOrDefault();
                            var             mobilephone          = default(Phone);
                            ImportPhoneData phoneData            = new ImportPhoneData();
                            phoneData.ReferenceID = guid;
                            if (dropdownValue != null)
                            {
                                if (!string.IsNullOrEmpty(value))
                                {
                                    string phoneNumber = GetNonNumericData(value);
                                    if (IsValidPhoneNumberLength(phoneNumber))
                                    {
                                        contact.PhoneData     = dropdownValue.DropdownValueID.ToString() + "|" + phoneNumber;
                                        phoneData.PhoneType   = (int?)dropdownValue.DropdownValueID;
                                        phoneData.PhoneNumber = phoneNumber;
                                        contactPhoneData.Add(phoneData);
                                    }
                                }
                                mobilephone = duplicatePerson.Phones.IsAny() ? duplicatePerson.Phones.Where(i => i.PhoneType == dropdownValue.DropdownValueID).FirstOrDefault() : null;
                            }

                            if (mobilephone != null)
                            {
                                elementValue = mobilephone.Number;
                            }
                        }
                        else if (checkIfStandardField(attribute, "Country"))
                        {
                            var countryvalue = value.Replace(" ", string.Empty).ToLower();
                            if (countryvalue == "usa" || countryvalue == "us" || countryvalue == "unitedstates" || countryvalue == "unitedstatesofamerica")
                            {
                                contact.Country = "US";
                            }
                            else if (countryvalue == "ca" || countryvalue == "canada")
                            {
                                contact.Country = "CA";
                            }
                            else
                            {
                                contact.Country = value;
                            }
                        }
                        else if (checkIfStandardField(attribute, "StreetAddress"))
                        {
                            contact.AddressLine1 = value;
                        }
                        else if (checkIfStandardField(attribute, "City"))
                        {
                            contact.City = value;
                        }
                        else if (checkIfStandardField(attribute, "State"))
                        {
                            contact.State = value;
                        }
                        else if (checkIfStandardField(attribute, "PostalCode"))
                        {
                            contact.ZipCode = value;
                        }
                        else
                        {
                            var customField = customFields.Where(i => i.Title.Replace(" ", string.Empty).ToLower() == (name + "(" + leadAdapterType.ToString().ToLower() + ")")).FirstOrDefault();
                            if (customField != null)
                            {
                                var customfielddata = duplicatePerson.CustomFields == null ? null : duplicatePerson.CustomFields.Where(i => i.CustomFieldId == customField.FieldId).FirstOrDefault();
                                if (customfielddata != null)
                                {
                                    elementValue = customfielddata.Value;
                                }
                                customData.FieldID     = customField.FieldId;
                                customData.FieldTypeID = (int?)customField.FieldInputTypeId;
                                customData.ReferenceID = guid;

                                if (customField.FieldInputTypeId == FieldType.date || customField.FieldInputTypeId == FieldType.datetime || customField.FieldInputTypeId == FieldType.time)
                                {
                                    DateTime converteddate;
                                    if (DateTime.TryParse(value, out converteddate))
                                    {
                                        customFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + converteddate.ToString("MM/dd/yyyy hh:mm tt"));
                                        customData.FieldValue = converteddate.ToString("MM/dd/yyyy hh:mm tt");
                                    }
                                }
                                else if (customField.FieldInputTypeId == FieldType.number)
                                {
                                    double number;
                                    if (double.TryParse(value, out number))
                                    {
                                        customFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + number.ToString());
                                        customData.FieldValue = number.ToString();
                                    }
                                }
                                else if (customField.FieldInputTypeId == FieldType.url)
                                {
                                    if (IsValidURL(value.Trim()))
                                    {
                                        customFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + value.Trim());
                                        customData.FieldValue = value.Trim();
                                    }
                                }
                                else
                                {
                                    customFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + value.Trim());
                                    customData.FieldValue = value.Trim();
                                }
                                contactCustomData.Add(customData);
                            }
                        }
                        if (!oldNewValues.ContainsKey(attribute.Name))
                        {
                            oldNewValues.Add(attribute.Name, new { OldValue = string.IsNullOrEmpty(elementValue) ? string.Empty : elementValue, NewValue = value });
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Current.Error("An exception occured in Genereating old new values element in Trulia : " + attribute.Name, ex);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Current.Error("An exception occured in Genereating old new values element in Trulia : ", ex);
            }
            #endregion

            if (customFieldData.Length > 0)
            {
                customFieldData.Remove(0, 1);
            }
            contact.CustomFieldsData = customFieldData.ToString();

            contact.ReferenceId               = guid;
            contact.AccountID                 = AccountID;
            contact.IsBuilderNumberPass       = builderNumberPass;
            contact.IsCommunityNumberPass     = communityNumberPass;
            contact.LeadAdapterRecordStatusId = (byte)status;
            contact.JobID           = jobId;
            contact.ContactStatusID = 1;
            contact.ContactTypeID   = 1;
            JavaScriptSerializer js = new JavaScriptSerializer();
            contact.LeadAdapterSubmittedData = js.Serialize(oldNewValues);
            contact.LeadAdapterRowData       = node.Current != null?node.Current.ToString() : string.Empty;

            personCustomFieldData.AddRange(contactCustomData);
            personPhoneData.AddRange(contactPhoneData);

            contact.ValidEmail = ValidateEmail(contact);

            RawContact duplicate_data = null;
            if (!string.IsNullOrEmpty(contact.PrimaryEmail))
            {
                duplicate_data = persons.Where(p => string.Compare(p.PrimaryEmail, contact.PrimaryEmail, true) == 0).FirstOrDefault();
            }
            else
            {
                duplicate_data = persons.Where(p => string.Compare(p.FirstName, contact.FirstName, true) == 0 &&
                                               string.Compare(p.LastName, contact.LastName, true) == 0).FirstOrDefault();
            }

            if (duplicate_data != null)
            {
                contact.IsDuplicate = true;
                //RawContact updatedperson = MergeDuplicateData(duplicate_data, contact, guid);
                //duplicate_data = updatedperson;
            }

            persons.Add(contact);
        }