private void SyncContactInformation(ContactsViewItem contact)
        {
            Logs.WriteEvent(string.Format("Processing contact {0}({1}) of organization {2}({3})", contact.Name, contact.UserID, contact.Organization, contact.OrganizationID));

            if (!string.IsNullOrEmpty(contact.Email))
            {
                string responseText     = string.Empty;
                string requestParameter = string.Format("{0}={1}", ContactObjects.Lookup.email.ToString(), contact.Email);
                string requestUrl       = string.Format("{0}person.json?{1}", _baseURI, requestParameter);
                responseText = CustomerInsightsUtilities.MakeHttpWebRequest(requestUrl, _securityToken, Logs, Settings, _currentContactApiCallsKey, ref _currentContactApiCalls);

                try
                {
                    if (!string.IsNullOrEmpty(responseText))
                    {
                        JObject jObject = JObject.Parse(responseText);
                        ContactObjects.RootObject contactInfo = JsonConvert.DeserializeObject <ContactObjects.RootObject>(jObject.ToString());
                        User currentContact = Users.GetUser(LoginUser, contact.UserID);
                        UpdateContactInformation(contactInfo, currentContact, (int)contact.OrganizationParentID);
                    }
                    else
                    {
                        Logs.WriteEvent("CustomerInsights did not return information.");
                    }
                }
                catch (Exception ex)
                {
                    Logs.WriteException(ex);
                }
            }
            else
            {
                Logs.WriteEvent("This contact does not have a email entered, can't get its CustomerInsights information.");
            }

            UpdateFullContactContactModified(contact.UserID);
        }
        private void SyncOrganizationInformation(Organization company)
        {
            Logs.WriteEvent(string.Format("Processing company {0}({1})", company.Name, company.OrganizationID));

            if (!string.IsNullOrEmpty(company.Website))
            {
                string responseText     = string.Empty;
                string requestParameter = string.Format("{0}={1}", CompanyObjects.Lookup.domain.ToString(), company.Website);
                string requestUrl       = string.Format("{0}company/lookup.json?{1}", _baseURI, requestParameter);
                responseText = CustomerInsightsUtilities.MakeHttpWebRequest(requestUrl, _securityToken, Logs, Settings, _currentCompanyApiCallsKey, ref _currentCompanyApiCalls);

                try
                {
                    if (!string.IsNullOrEmpty(responseText))
                    {
                        JObject jObject = JObject.Parse(responseText);
                        CompanyObjects.RootObject companyInfo = JsonConvert.DeserializeObject <CompanyObjects.RootObject>(jObject.ToString());
                        UpdateCompanyInformation(companyInfo, company);
                    }
                    else
                    {
                        Logs.WriteEvent("CustomerInsights did not return information.");
                    }
                }
                catch (Exception ex)
                {
                    Logs.WriteException(ex);
                }
            }
            else
            {
                Logs.WriteEvent("This company does not have a website entered, can't get its CustomerInsights information.");
            }

            UpdateFullContactCompanyModified(company.OrganizationID);
        }
        private bool UpdateContactInformation(ContactObjects.RootObject customerInsightsContactInfo, User currentContactInfo, int organizationParentId)
        {
            bool   isTitleUpdated    = false;
            bool   isLinkedInUpdated = false;
            string useSocialProfile  = CustomerInsightsUtilities.SocialProfiles.LinkedIn.ToString();

            if (customerInsightsContactInfo.socialProfiles != null && customerInsightsContactInfo.socialProfiles.Count > 0)
            {
                if (!customerInsightsContactInfo.socialProfiles.Exists(p => p.typeName.ToLower() == CustomerInsightsUtilities.SocialProfiles.LinkedIn.ToString().ToLower()))
                {
                    Logs.WriteEvent("LinkedIn not found");
                }
                else
                {
                    ContactObjects.SocialProfile contactInfo = customerInsightsContactInfo.socialProfiles.Where(p => p.typeName.ToLower() == useSocialProfile.ToLower()).FirstOrDefault();
                    if (contactInfo != null && CanUpdateContactLinkedIn(currentContactInfo, contactInfo.url))
                    {
                        currentContactInfo.LinkedIn = contactInfo.url;
                        isLinkedInUpdated           = true;
                    }
                }
            }
            else
            {
                Logs.WriteEvent("No social profile found");
            }

            if (customerInsightsContactInfo.organizations != null && customerInsightsContactInfo.organizations.Count > 0)
            {
                ContactObjects.Organization organization = customerInsightsContactInfo.organizations.Where(p => p.isPrimary).FirstOrDefault();
                if (organization != null && CanUpdateContactTitle(currentContactInfo, organization.title))
                {
                    currentContactInfo.Title = organization.title;
                    isTitleUpdated           = true;
                }
            }
            else
            {
                Logs.WriteEvent("No organizations found");
            }

            if (isLinkedInUpdated || isTitleUpdated)
            {
                currentContactInfo.Collection.Save();
                string description = string.Empty;

                if (isLinkedInUpdated)
                {
                    Logs.WriteEventFormat("LinkedIn updated to {0}", currentContactInfo.LinkedIn);
                    description = string.Format("TeamSupport System changed LinkedIn to {0} ", currentContactInfo.LinkedIn);
                    ActionLogs.AddActionLog(LoginUser, ActionLogType.Update, ReferenceType.Users, currentContactInfo.UserID, description);
                }

                if (isTitleUpdated)
                {
                    Logs.WriteEventFormat("Title updated to {0}", currentContactInfo.Title);
                    description = string.Format("TeamSupport System set contact title to {0} ", currentContactInfo.Title);
                    ActionLogs.AddActionLog(LoginUser, ActionLogType.Update, ReferenceType.Users, currentContactInfo.UserID, description);
                }
            }

            string usePhotoFrom = CustomerInsightsUtilities.SocialProfiles.LinkedIn.ToString();
            string photoUrl     = string.Empty;

            if (customerInsightsContactInfo.photos != null && customerInsightsContactInfo.photos.Any())
            {
                if (customerInsightsContactInfo.photos.Exists(p => p.typeName.ToLower() == usePhotoFrom.ToLower()))
                {
                    photoUrl = customerInsightsContactInfo.photos.Where(p => p.typeName.ToLower() == usePhotoFrom.ToLower() && !string.IsNullOrEmpty(p.url)).Select(p => p.url).FirstOrDefault();
                }

                if (string.IsNullOrEmpty(photoUrl))
                {
                    photoUrl = customerInsightsContactInfo.photos.Where(p => !string.IsNullOrEmpty(p.url)).Select(p => p.url).FirstOrDefault();
                }
            }

            if (!string.IsNullOrEmpty(photoUrl))
            {
                string resultMessage = string.Empty;
                string logoPath      = TeamSupport.Data.Quarantine.ServiceQ.GetAttachmentPath12(LoginUser, organizationParentId);
                string logoFullPath  = string.Format("{0}\\{1}avatar.jpg", logoPath, currentContactInfo.UserID.ToString());

                if (CustomerInsightsUtilities.DownloadImage(photoUrl, logoFullPath, currentContactInfo.OrganizationID, AttachmentProxy.References.Contacts, LoginUser, out resultMessage))
                {
                    string description = "TeamSupport System updated Photo for  '" + currentContactInfo.DisplayName + "'";
                    ActionLogs.AddActionLog(LoginUser, ActionLogType.Update, ReferenceType.Users, currentContactInfo.UserID, description);

                    //delete cached image
                    string cachePath = string.Empty;
                    string pattern   = string.Empty;
                    try
                    {
                        cachePath = TeamSupport.Data.Quarantine.ServiceQ.GetAttachmentPath13(LoginUser, organizationParentId);
                        pattern   = currentContactInfo.UserID.ToString() + "-*.*";
                        string[] files = System.IO.Directory.GetFiles(cachePath, pattern, System.IO.SearchOption.TopDirectoryOnly);

                        foreach (String file in files)
                        {
                            System.IO.File.Delete(file);
                        }
                    }
                    catch (Exception ex)
                    {
                        Logs.WriteEvent("Exception deleting cached images for contact.");
                        Logs.WriteEventFormat("CachePath: {0}", cachePath.ToString());
                        Logs.WriteEventFormat("Pattern: {0}", pattern.ToString());
                        Logs.WriteEventFormat("Exception Message: {0}", ex.Message.ToString());
                        Logs.WriteEventFormat("Exception StackTrace: {0}", ex.StackTrace.ToString());
                    }
                }

                if (!string.IsNullOrEmpty(resultMessage))
                {
                    Logs.WriteEvent(resultMessage);
                }
            }
            else
            {
                Logs.WriteEvent("No photo url found");
            }

            return(isLinkedInUpdated || isTitleUpdated);
        }
        private bool UpdateCompanyInformation(CompanyObjects.RootObject customerInsightsOrganizationInfo, Organization currentCompanyInfo)
        {
            bool   isUpdated        = false;
            string useSocialProfile = CustomerInsightsUtilities.SocialProfiles.LinkedIn.ToString();

            if (customerInsightsOrganizationInfo.socialProfiles != null && customerInsightsOrganizationInfo.socialProfiles.Count > 0)
            {
                //We will use LinkedIn for bio, if not found then use the first one of the others with that information
                if (!customerInsightsOrganizationInfo.socialProfiles.Exists(p => p.typeName.ToLower() == useSocialProfile.ToLower()))
                {
                    useSocialProfile = string.Empty;
                    useSocialProfile = customerInsightsOrganizationInfo.socialProfiles.Where(p => !string.IsNullOrEmpty(p.bio)).Select(p => p.typeName).FirstOrDefault();
                }

                if (!string.IsNullOrEmpty(useSocialProfile))
                {
                    string bio = customerInsightsOrganizationInfo.socialProfiles.Where(p => p.typeName.ToLower() == useSocialProfile.ToLower() && !string.IsNullOrEmpty(p.bio)).Select(p => p.bio).FirstOrDefault();

                    if (CanUpdateCompanyBio(currentCompanyInfo, bio))
                    {
                        currentCompanyInfo.Description = bio;
                        isUpdated = true;
                    }
                }
                else
                {
                    Logs.WriteEvent("No bio found in any of the social profiles");
                }
            }
            else
            {
                Logs.WriteEvent("No social profile found");
            }


            if (!string.IsNullOrEmpty(customerInsightsOrganizationInfo.logo))
            {
                string resultMessage = string.Empty;
                string logoPath      = TeamSupport.Data.Quarantine.ServiceQ.GetAttachmentPath10(LoginUser, (int)currentCompanyInfo.ParentID);
                string logoFullPath  = string.Format("{0}\\{1}.png", logoPath, currentCompanyInfo.OrganizationID);

                if (CustomerInsightsUtilities.DownloadImage(customerInsightsOrganizationInfo.logo, logoFullPath, currentCompanyInfo.OrganizationID, AttachmentProxy.References.Organizations, LoginUser, out resultMessage))
                {
                    string description = string.Format("TeamSupport System updated Logo for '{0}'", currentCompanyInfo.Name);
                    ActionLogs.AddActionLog(LoginUser, ActionLogType.Update, ReferenceType.Organizations, currentCompanyInfo.OrganizationID, description);

                    //delete cached image
                    string cachePath = string.Empty;
                    string pattern   = string.Empty;
                    try
                    {
                        cachePath = TeamSupport.Data.Quarantine.ServiceQ.GetAttachmentPath11(LoginUser, currentCompanyInfo.ParentID.ToString());

                        if (System.IO.Directory.Exists(cachePath))
                        {
                            pattern = currentCompanyInfo.OrganizationID.ToString() + "-*.*";
                            string[] files = System.IO.Directory.GetFiles(cachePath, pattern, System.IO.SearchOption.TopDirectoryOnly);

                            foreach (String file in files)
                            {
                                System.IO.File.Delete(file);
                                Logs.WriteEvent(string.Format("Cached file {0} deleted.", file));
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logs.WriteEvent("Exception deleting cached images for company.");
                        Logs.WriteEventFormat("CachePath: {0}", cachePath.ToString());
                        Logs.WriteEventFormat("Pattern: {0}", pattern.ToString());
                        Logs.WriteEventFormat("Exception Message: {0}", ex.Message.ToString());
                        Logs.WriteEventFormat("Exception StackTrace: {0}", ex.StackTrace.ToString());
                    }
                }

                if (!string.IsNullOrEmpty(resultMessage))
                {
                    Logs.WriteEvent(resultMessage);
                }
            }
            else
            {
                Logs.WriteEvent("No logo found");
            }

            if (isUpdated)
            {
                currentCompanyInfo.Collection.Save();
                Logs.WriteEvent(string.Format("Bio pulled from {0}", useSocialProfile));
                string description = "TeamSupport System changed description for organization '" + currentCompanyInfo.Name + "'";
                ActionLogs.AddActionLog(LoginUser, ActionLogType.Update, ReferenceType.Organizations, currentCompanyInfo.OrganizationID, description);
            }

            return(isUpdated);
        }