Esempio n. 1
0
        private static bool IsActive(DirectoryEntry de)
        {
            if (de == null)
            {
                return(false);
            }
            if (de.NativeGuid == null)
            {
                return(false);
            }
            var status = true;

            try
            {
                var flags = (int)de.Properties["userAccountControl"].Value;
                status = !Convert.ToBoolean(flags & 0x0002);
            }
            catch (Exception e)
            {
                FoundationSync.LogMessage(505, FoundationSync.LogCategories.FoundationSync, TraceSeverity.Unexpected,
                                          string.Format("Unexpected exception attempting to determine if user is active: User: {0}. Status value: {1}. {2}", de.Username, status, e.StackTrace), null);
            }

            return(status);
        }
Esempio n. 2
0
        private static string SaveImage(Bitmap image, string siteUri, string fileName)
        {
            if (siteUri == null)
            {
                return(null);
            }
            try
            {
                using (SPSite site = new SPSite(siteUri))
                {
                    using (SPWeb web = site.RootWeb)
                    {
                        var library = (from SPList list in web.Lists
                                       where list.RootFolder.Name.Equals("UserPhotos")
                                       select list).FirstOrDefault();

                        if (library == null)
                        {
                            return(null);
                        }

                        var ms = new MemoryStream();

                        image.Save(ms, ImageFormat.Jpeg);
                        ms.Close();

                        var byteArray = ms.ToArray();

                        if (byteArray.Length > 0)
                        {
                            var file = library.RootFolder.Files.Add(fileName, byteArray, true);

                            return((string)file.Item[SPBuiltInFieldId.EncodedAbsUrl]);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                FoundationSync.LogMessage(405, FoundationSync.LogCategories.FoundationSync, TraceSeverity.Unexpected,
                                          exception.Message + exception.StackTrace, null);
            }

            return(null);
        }
        internal FoundationSyncSettings SyncSettings()
        {
            try
            {
                var foundationSyncSettings = FoundationSyncSettings.Local;

                if (foundationSyncSettings != null)
                {
                    return(foundationSyncSettings);
                }
            }
            catch (Exception e)
            {
                FoundationSync.LogMessage(504, FoundationSync.LogCategories.FoundationSync, TraceSeverity.Unexpected,
                                          "Unable to read FoundationSyncSetting object. " + e.StackTrace, null);
            }

            return(null);
        }
Esempio n. 4
0
        private static string GetDomain(string domainName)
        {
            string ldapPath = null;

            try
            {
                var objContext = new DirectoryContext(
                    DirectoryContextType.Domain, domainName);
                var objDomain = Domain.GetDomain(objContext);
                ldapPath = objDomain.Name;
            }
            catch (Exception e)
            {
                FoundationSync.LogMessage(410, FoundationSync.LogCategories.FoundationSync, TraceSeverity.Unexpected,
                                          string.Format("Unexpected exception attempting to retrieve domain name: {0}. {1}", domainName, e.StackTrace), null);
                return(null);
            }

            return(ldapPath);
        }
Esempio n. 5
0
        private static void RemoveUsers(SPUser objPrincipal, string siteUrl)
        {
            using (SPSite site = new SPSite(siteUrl))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    try
                    {
                        var user = web.SiteUsers[objPrincipal.LoginName];
                        if (user.IsSiteAdmin)
                        {
                            return;
                        }

                        web.SiteUsers.Remove(user.LoginName);
                    }
                    catch (Exception e)
                    {
                        FoundationSync.LogMessage(506, FoundationSync.LogCategories.FoundationSync, TraceSeverity.Unexpected,
                                                  string.Format("Unexpected exception attempting to remove user: User: {0} (ID: {1}). Url: {2}. {3}", objPrincipal.LoginName, objPrincipal.ID, siteUrl, e.StackTrace), null);
                    }
                }
            }
        }
Esempio n. 6
0
        public override void Execute(Guid targetInstanceId)
        {
            try
            {
                var farm            = SPFarm.Local;
                var ignoredUsers    = FoundationSyncSettings.Local.IgnoredUsers;
                var service         = farm.Services.GetValue <SPWebService>();
                var userAccounts    = new HashSet <SPUser>();
                var groupAccounts   = new HashSet <SPUser>();
                var webApplications = FoundationSyncSettings.Local.WebApplicationCollection.Count < 1
                    ? (IEnumerable <SPWebApplication>)service.WebApplications
                    : FoundationSyncSettings.Local.WebApplicationCollection;

                foreach (SPWebApplication webApplication in webApplications)
                {
                    var siteCollections = FoundationSyncSettings.Local.SPSiteCollection.Count < 1
                        ? (IEnumerable <SPSite>)webApplication.Sites
                        : FoundationSyncSettings.Local.SPSiteCollection;

                    foreach (SPSite site in siteCollections)
                    {
                        foreach (SPUser userPrincipal in from SPUser userPrincipal in site.RootWeb.SiteUsers
                                 let invalidUser = ignoredUsers.Any(word => userPrincipal.LoginName.Contains(word))
                                                   where !invalidUser
                                                   where !userPrincipal.IsDomainGroup
                                                   where userPrincipal.LoginName.Contains(@"\")
                                                   select userPrincipal)
                        {
                            userAccounts.Add(userPrincipal);
                        }

                        FoundationSync.LogMessage(100, FoundationSync.LogCategories.FoundationSync, TraceSeverity.Verbose,
                                                  string.Format("{0} user principals in site {1}", userAccounts.Count, site.Url), null);

                        PrincipalHandler.SearchPrincipals(userAccounts, webApplication, site, false);

                        userAccounts.Clear();

                        foreach (SPUser groupPrincipal in from SPUser groupPrincipal in site.RootWeb.SiteUsers
                                 let invalidGroup = ignoredUsers.Any(word => groupPrincipal.LoginName.Contains(word))
                                                    where !invalidGroup
                                                    where groupPrincipal.IsDomainGroup
                                                    select groupPrincipal)
                        {
                            groupAccounts.Add(groupPrincipal);
                        }

                        FoundationSync.LogMessage(101, FoundationSync.LogCategories.FoundationSync, TraceSeverity.Verbose,
                                                  string.Format("{0} group principals in site {1}", groupAccounts.Count, site.Url), null);

                        PrincipalHandler.SearchPrincipals(groupAccounts, webApplication, site, true);
                        groupAccounts.Clear();

                        site.Dispose();
                    }
                }
            }
            catch (IndexOutOfRangeException)
            {
                FoundationSync.LogMessage(102, FoundationSync.LogCategories.FoundationSync, TraceSeverity.Medium,
                                          null, null);
            }
        }
Esempio n. 7
0
        internal static void User(SPUser user, DirectoryEntry directoryEntry, SPListItemCollection listItems, int itemCount)
        {
            try
            {
                var j = 0;
                for (; j < itemCount; j++)
                {
                    shouldUpdate = false;

                    var item = listItems[j];

                    if (!string.Equals(item["Name"].ToString(), user.LoginName, StringComparison.CurrentCultureIgnoreCase))
                    {
                        continue;
                    }

                    var title = (directoryEntry.Properties["displayName"].Value == null)
                                        ? string.Empty
                                        : directoryEntry.Properties["displayName"].Value.ToString();

                    try
                    {
                        TryUpdateValue(item, "Title", (string)item["Title"], title);
                    }
                    catch (Exception)
                    {
                        FoundationSync.LogMessage(506, FoundationSync.LogCategories.FoundationSync, TraceSeverity.Unexpected,
                                                  string.Format("Unable to update {0} for user {1} (ID {2}) on Site Collection {3}.", "Title", item.DisplayName, item.ID, item.Web.Site.Url), null);
                    }

                    var eMail = (directoryEntry.Properties["mail"].Value == null)
                                        ? string.Empty
                                        : directoryEntry.Properties["mail"].Value.ToString();

                    try
                    {
                        TryUpdateValue(item, "EMail", (string)item["EMail"], eMail);
                    }
                    catch (Exception)
                    {
                        FoundationSync.LogMessage(506, FoundationSync.LogCategories.FoundationSync, TraceSeverity.Unexpected,
                                                  string.Format("Unable to update {0} for user {1} (ID {2}) on Site Collection {3}.", "EMail", item.DisplayName, item.ID, item.Web.Site.Url), null);
                    }


                    var jobTitle = (directoryEntry.Properties["title"].Value == null)
                                           ? string.Empty
                                           : directoryEntry.Properties["title"].Value.ToString();

                    try
                    {
                        TryUpdateValue(item, "JobTitle", (string)item["JobTitle"], jobTitle);
                    }
                    catch (Exception)
                    {
                        FoundationSync.LogMessage(506, FoundationSync.LogCategories.FoundationSync, TraceSeverity.Unexpected,
                                                  string.Format("Unable to update {0} for user {1} (ID {2}) on Site Collection {3}.", "JobTitle", item.DisplayName, item.ID, item.Web.Site.Url), null);
                    }


                    var mobilePhone = (directoryEntry.Properties["mobile"].Value == null)
                                              ? string.Empty
                                              : directoryEntry.Properties["mobile"].Value.ToString();
                    try
                    {
                        TryUpdateValue(item, "MobilePhone", (string)item["MobilePhone"], mobilePhone);
                    }
                    catch (Exception)
                    {
                        FoundationSync.LogMessage(506, FoundationSync.LogCategories.FoundationSync, TraceSeverity.Unexpected,
                                                  string.Format("Unable to update {0} for user {1} (ID {2}) on Site Collection {3}.", "MobilePhone", item.DisplayName, item.ID, item.Web.Site.Url), null);
                    }

                    if (user.SystemUserKey != null)
                    {
                        var uri = ThumbnailHandler.GetThumbnail(user, directoryEntry);

                        try
                        {
                            if (!string.IsNullOrEmpty(uri))
                            {
                                TryUpdateValue(item, "Picture", (string)item["Picture"], uri);
                            }
                            else if (string.IsNullOrEmpty(uri))
                            {
                                TryUpdateValue(item, "Picture", (string)item["Picture"], string.Empty);
                            }
                        }
                        catch (Exception)
                        {
                            FoundationSync.LogMessage(506, FoundationSync.LogCategories.FoundationSync, TraceSeverity.Unexpected,
                                                      string.Format("Unable to update {0} for user {1} (ID {2}) on Site Collection {3}.", "Picture", item.DisplayName, item.ID, item.Web.Site.Url), null);
                        }
                    }

                    try
                    {
                        if (directoryEntry.Properties["proxyAddresses"].Value != null)
                        {
                            var array = (Array)directoryEntry.Properties["proxyAddresses"].Value;

                            foreach (var o in from string o in array
                                     where o.Contains(("sip:"))
                                     select o)
                            {
                                var sipAddress = o.Remove(0, 4);

                                try
                                {
                                    TryUpdateValue(item, "SipAddress", (string)item["SipAddress"],
                                                   sipAddress);
                                }
                                catch (Exception)
                                {
                                    FoundationSync.LogMessage(506, FoundationSync.LogCategories.FoundationSync, TraceSeverity.Unexpected,
                                                              string.Format("Unable to update {0} for user {1} (ID {2}) on Site Collection {3}.", "SipAddress", item.DisplayName, item.ID, item.Web.Site.Url), null);
                                }
                            }
                        }
                    }
                    catch (InvalidCastException)
                    {
                        if (directoryEntry.Properties["proxyAddresses"].Value.ToString().Contains("sip:"))
                        {
                            var sipAddress = directoryEntry.Properties["proxyAddresses"].Value.ToString().Remove(0, 4);

                            try
                            {
                                TryUpdateValue(item, "SipAddress", (string)item["SipAddress"],
                                               sipAddress);
                            }
                            catch (Exception)
                            {
                                FoundationSync.LogMessage(506, FoundationSync.LogCategories.FoundationSync, TraceSeverity.Unexpected,
                                                          string.Format("Unable to update {0} for user {1} (ID {2}) on Site Collection {3}.", "SipAddress", item.DisplayName, item.ID, item.Web.Site.Url), null);
                            }
                        }
                        else
                        {
                            try
                            {
                                item["SipAddress"] = string.Empty;
                            }
                            catch (Exception)
                            {
                                FoundationSync.LogMessage(506, FoundationSync.LogCategories.FoundationSync, TraceSeverity.Unexpected,
                                                          string.Format("Unable to update {0} for user {1} (ID {2}) on Site Collection {3}.", "SipAddress", item.DisplayName, item.ID, item.Web.Site.Url), null);
                            }
                        }
                    }

                    var department = (directoryEntry.Properties["department"].Value == null)
                                             ? string.Empty
                                             : directoryEntry.Properties["department"].Value.ToString();

                    try
                    {
                        TryUpdateValue(item, "Department", (string)item["Department"], department);
                    }
                    catch (Exception)
                    {
                        FoundationSync.LogMessage(506, FoundationSync.LogCategories.FoundationSync, TraceSeverity.Unexpected,
                                                  string.Format("Unable to update {0} for user {1} (ID {2}) on Site Collection {3}.", "Department", item.DisplayName, item.ID, item.Web.Site.Url), null);
                    }

                    try
                    {
                        var additionalAttributes = FoundationSyncSettings.Local.AdditionalUserAttributes;

                        foreach (var ldapAttribute in additionalAttributes)
                        {
                            var value = (directoryEntry.Properties[ldapAttribute.Value].Value == null)
                                                   ? string.Empty
                                                   : directoryEntry.Properties[ldapAttribute.Value].Value.ToString();

                            TryUpdateValue(item, ldapAttribute.Key, (string)item[ldapAttribute.Key], value);
                        }
                    }
                    catch (Exception)
                    {
                        FoundationSync.LogMessage(506, FoundationSync.LogCategories.FoundationSync, TraceSeverity.Unexpected,
                                                  string.Format("Unable to update {0} for user {1} (ID {2}) on Site Collection {3}.", "AdditionalAttribues Value", item.DisplayName, item.ID, item.Web.Site.Url), null);
                    }

                    if (shouldUpdate)
                    {
                        FoundationSync.LogMessage(201, FoundationSync.LogCategories.FoundationSync, TraceSeverity.Verbose,
                                                  string.Format("Updating user {0} (ID {1}) on Site Collection {2}.", item.DisplayName, item.ID, item.Web.Site.Url), null);
                        item.Update();
                    }

                    return;
                }
            }
            catch (SPException exception)
            {
                FoundationSync.LogMessage(401, FoundationSync.LogCategories.FoundationSync,
                                          TraceSeverity.Unexpected, exception.Message + " " + exception.StackTrace, null);
            }
        }
Esempio n. 8
0
        internal static void SearchPrincipals(HashSet <SPUser> objPrincipals,
                                              SPWebApplication webApplication, SPSite site, bool isGroup)
        {
            var chasing = webApplication.PeoplePickerSettings.ReferralChasingOption;

            {
                var listItems = site.RootWeb.SiteUserInfoList.Items;
                var itemCount = listItems.Count;

                foreach (SPUser objPrincipal in objPrincipals)
                {
                    var           claimProvider = SPClaimProviderManager.Local;
                    string        loginName, filter;
                    List <string> userProperties = new List <string> {
                        "displayName", "mail", "title", "mobile", "proxyAddresses", "department",
                        "sn", "givenName", "telephoneNumber", "wWWHomePage", "physicalDeliveryOfficeName", "thumbnailPhoto"
                    };
                    List <string> groupProperties = new List <string> {
                        "sAMAccountName", "mail", "proxyAddresses"
                    };

                    if (isGroup)
                    {
                        if (claimProvider != null && objPrincipal.LoginName.Contains(@"c:0+.w"))
                        {
                            var sid = claimProvider.DecodeClaim(objPrincipal.LoginName).Value;
                            FoundationSync.LogMessage(202, FoundationSync.LogCategories.FoundationSync, TraceSeverity.VerboseEx,
                                                      string.Format("IsGroup:{0}. RootWeb: {1}.", objPrincipal.LoginName, site.RootWeb.Url), null);

                            try
                            {
                                loginName = new SecurityIdentifier(sid).Translate(typeof(NTAccount)).ToString();
                            }
                            catch (Exception exception)
                            {
                                FoundationSync.LogMessage(503, FoundationSync.LogCategories.FoundationSync,
                                                          TraceSeverity.High,
                                                          exception.Message + exception.StackTrace, null);
                                continue;
                            }
                        }
                        else
                        {
                            loginName = objPrincipal.LoginName;
                        }

                        var ldapPath = GetDomain(loginName.Split('\\')[0]);

                        var entry   = new DirectoryEntry(@"LDAP://" + ldapPath);
                        var i       = loginName.LastIndexOf('\\');
                        var objName = loginName.Remove(0, i + 1);
                        filter = string.Format("(&(objectClass=group)(sAMAccountName={0}))", objName);

                        var searcher = new DirectorySearcher(entry, filter, groupProperties.ToArray())
                        {
                            ReferralChasing = chasing
                        };

                        try
                        {
                            var result         = searcher.FindOne();
                            var directoryEntry = result.GetDirectoryEntry();
                            UpdateGroup.Group(objPrincipal, directoryEntry, listItems, itemCount);
                        }
                        catch (DirectoryServicesCOMException exception)
                        {
                            FoundationSync.LogMessage(403, FoundationSync.LogCategories.FoundationSync, TraceSeverity.Unexpected,
                                                      string.Format("IsGroup:{0}. RootWeb: {1}. {2}{3}", objPrincipal.LoginName,
                                                                    site.RootWeb.Url, exception.Message, exception.StackTrace), null);
                        }
                    }
                    else
                    {
                        FoundationSync.LogMessage(203, FoundationSync.LogCategories.FoundationSync, TraceSeverity.VerboseEx,
                                                  string.Format("IsUser:{0}. RootWeb: {1}.", objPrincipal.LoginName, site.RootWeb.Url), null);

                        if (claimProvider != null && objPrincipal.LoginName.Contains(@"i:0#.w"))
                        {
                            loginName = claimProvider.DecodeClaim(objPrincipal.LoginName).Value;
                        }
                        else
                        {
                            loginName = objPrincipal.LoginName;
                        }

                        try
                        {
                            foreach (var attribute in FoundationSyncSettings.Local.AdditionalUserAttributes)
                            {
                                userProperties.Add(attribute.Value);
                            }
                        }
                        catch (Exception)
                        { }

                        var ldapPath = GetDomain(loginName.Split('\\')[0]);

                        if (string.IsNullOrEmpty(ldapPath))
                        {
                            continue;
                        }

                        var entry = new DirectoryEntry("LDAP://" + ldapPath);

                        filter = string.Format("(&(objectClass=user)(sAMAccountName={0}))", loginName.Split('\\')[1]);
                        var searcher = new DirectorySearcher(entry, filter, userProperties.ToArray())
                        {
                            ReferralChasing = chasing
                        };

                        try
                        {
                            var result = searcher.FindOne();

                            if (result == null)
                            {
                                if (FoundationSyncSettings.Local.DeleteUsers)
                                {
                                    RemoveUsers(objPrincipal, site.Url);
                                }
                                continue;
                            }

                            if (!IsActive(result.GetDirectoryEntry()))
                            {
                                if (FoundationSyncSettings.Local.DeleteDisabledUsers)
                                {
                                    RemoveUsers(objPrincipal, site.Url);
                                }
                                continue;
                            }

                            var directoryEntry = result.GetDirectoryEntry();
                            UpdateUser.User(objPrincipal, directoryEntry, listItems, itemCount);
                        }
                        catch (DirectoryServicesCOMException exception)
                        {
                            FoundationSync.LogMessage(404, FoundationSync.LogCategories.FoundationSync, TraceSeverity.Unexpected,
                                                      string.Format("IsUser:{0}. RootWeb: {1}. {2}{3}", objPrincipal.LoginName,
                                                                    site.RootWeb.Url, exception.Message, exception.StackTrace), null);
                        }
                        catch (Exception exception)
                        {
                            FoundationSync.LogMessage(405, FoundationSync.LogCategories.FoundationSync, TraceSeverity.Unexpected,
                                                      string.Format("Unknown error: {0}{1}", exception.Message, exception.StackTrace), null);
                        }
                    }
                }
            }
        }
Esempio n. 9
0
        internal static void Group(SPUser group, DirectoryEntry directoryEntry,
                                   SPListItemCollection listItems, int itemCount)
        {
            try
            {
                var j = 0;
                for (; j < itemCount; j++)
                {
                    shouldUpdate = false;

                    var item = listItems[j];

                    if (item["Name"].ToString().ToLower() != group.LoginName.ToLower())
                    {
                        continue;
                    }

                    var eMail = (directoryEntry.Properties["mail"].Value == null)
                        ? string.Empty
                        : directoryEntry.Properties["mail"].Value.ToString();

                    try
                    {
                        TryUpdateValue(item, "EMail", (string)item["EMail"], eMail);
                    }
                    catch (Exception)
                    {
                        FoundationSync.LogMessage(506, FoundationSync.LogCategories.FoundationSync, TraceSeverity.Unexpected,
                                                  string.Format("Unable to update {0} for group {1} (ID {2}) on Site Collection {3}.", "EMail", item.DisplayName, item.ID, item.Web.Site.Url), null);
                    }

                    try
                    {
                        if (directoryEntry.Properties["proxyAddresses"].Value != null)
                        {
                            var array = (Array)directoryEntry.Properties["proxyAddresses"].Value;

                            foreach (var o in from string o in array
                                     where o.Contains(("sip:"))
                                     select o)
                            {
                                var sipAddress = o.Remove(0, 4);

                                try
                                {
                                    TryUpdateValue(item, "SipAddress", (string)item["SipAddress"],
                                                   sipAddress);
                                }
                                catch (Exception)
                                {
                                    FoundationSync.LogMessage(506, FoundationSync.LogCategories.FoundationSync, TraceSeverity.Unexpected,
                                                              string.Format("Unable to update {0} for group {1} (ID {2}) on Site Collection {3}.", "SipAddress", item.DisplayName, item.ID, item.Web.Site.Url), null);
                                }
                            }
                        }
                    }
                    catch (InvalidCastException)
                    {
                        if (directoryEntry.Properties["proxyAddresses"].Value.ToString().Contains("sip:"))
                        {
                            var sipAddress = directoryEntry.Properties["proxyAddresses"].Value.ToString().Remove(0, 4);

                            try
                            {
                                TryUpdateValue(item, "SipAddress", (string)item["SipAddress"],
                                               sipAddress);
                            }
                            catch (Exception)
                            {
                                FoundationSync.LogMessage(506, FoundationSync.LogCategories.FoundationSync, TraceSeverity.Unexpected,
                                                          string.Format("Unable to update {0} for user {1} (ID {2}) on Site Collection {3}.", "SipAddress", item.DisplayName, item.ID, item.Web.Site.Url), null);
                            }
                        }
                        else
                        {
                            item["SipAddress"] = string.Empty;
                        }
                    }

                    if (shouldUpdate)
                    {
                        FoundationSync.LogMessage(200, FoundationSync.LogCategories.FoundationSync, TraceSeverity.Verbose,
                                                  string.Format("Updating group {0} (ID {1}) on Site Collection {2}.", item.DisplayName, item.ID, item.Web.Site.Url), null);
                        item.Update();
                    }

                    return;
                }
            }
            catch (SPException exception)
            {
                FoundationSync.LogMessage(400, FoundationSync.LogCategories.FoundationSync,
                                          TraceSeverity.Unexpected, exception.Message + " " + exception.StackTrace, null);
            }
        }
Esempio n. 10
0
        internal static string GetThumbnail(SPUser user, DirectoryEntry directoryEntry)
        {
            if (FoundationSyncSettings.Local.PictureExpiryDays <= -1)
            {
                return(null);
            }
            var siteUri = FoundationSyncSettings.Local.PictureStorageUrl;

            if (siteUri == null)
            {
                return(null);
            }
            if (string.IsNullOrEmpty(siteUri.AbsoluteUri))
            {
                return(null);
            }

            var fileUri = string.Empty;

            //One-way hash of SystemUserKey, typically a SID.
            var sHash          = SHA1.Create();
            var encoding       = new ASCIIEncoding();
            var userBytes      = encoding.GetBytes(user.SystemUserKey);
            var userHash       = sHash.ComputeHash(userBytes);
            var userHashString = Convert.ToBase64String(userHash);

            //The / is the only illegal character for SharePoint in a Base64 string
            //Replacing it with $, which is not valid in a Base64 string, but works for our purposes

            userHashString = userHashString.Replace("/", "$");

            var fileName = string.Format("{0}{1}", userHashString, ".jpg");

            try
            {
                using (SPSite site = new SPSite(siteUri.AbsoluteUri))
                {
                    var web    = site.RootWeb;
                    var list   = web.GetList("UserPhotos");
                    var folder = list.RootFolder;
                    var file   = folder.Files[fileName];

                    if (file.Length > 1)
                    {
                        var pictureExpiryDays = 1;

                        try
                        {
                            pictureExpiryDays = FoundationSyncSettings.Local.PictureExpiryDays;
                        }
                        catch (InvalidCastException)
                        {
                            FoundationSyncSettings.Local.PictureExpiryDays = 1;
                            pictureExpiryDays = 1;
                        }
                        catch (OverflowException)
                        {
                            FoundationSyncSettings.Local.PictureExpiryDays = 1;
                            pictureExpiryDays = 1;
                        }

                        if ((file.TimeLastModified - DateTime.Now).TotalDays < pictureExpiryDays)
                        {
                            return((string)file.Item[SPBuiltInFieldId.EncodedAbsUrl]);
                        }
                    }
                }
            }
            catch (ArgumentNullException)
            {
                return(null);
            }
            catch (FileNotFoundException)
            {
                FoundationSync.LogMessage(1004, FoundationSync.LogCategories.FoundationSync, TraceSeverity.Unexpected,
                                          string.Format("Invalid Site URL specified for Picture Site Collection URL."), null);
                return(null);
            }
            catch (Exception)
            {
                FoundationSync.LogMessage(2001, FoundationSync.LogCategories.FoundationSync, TraceSeverity.Verbose,
                                          string.Format("Error retrieving picture file from UserPhotos library, continuing to pull new picture."), null);
            }

            if (FoundationSyncSettings.Local.UseExchange)
            {
                var ewsPictureSize = "648x648";

                if (FoundationSyncSettings.Local.EwsPictureSize != null)
                {
                    ewsPictureSize = FoundationSyncSettings.Local.EwsPictureSize;
                }

                var uri = new UriBuilder(string.Format("{0}/s/GetUserPhoto?email={1}&size=HR{2}", FoundationSyncSettings.Local.EwsUrl, user.Email, ewsPictureSize));

                SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    var request = (HttpWebRequest)WebRequest.Create(uri.Uri);
                    request.UseDefaultCredentials = true;

                    try
                    {
                        using (var response = (HttpWebResponse)request.GetResponse())
                        {
                            if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.NotModified)
                            {
                                if (response.GetResponseStream() != null)
                                {
                                    var image = new Bitmap(response.GetResponseStream());
                                    fileUri   = SaveImage(image, siteUri.AbsoluteUri, fileName);
                                }
                            }
                            else if (response.StatusCode == HttpStatusCode.NotFound ||
                                     response.StatusCode == HttpStatusCode.InternalServerError ||
                                     response.StatusCode == HttpStatusCode.ServiceUnavailable)
                            {
                                fileUri = string.Empty;
                            }
                            //else Exchange is not online, incorrect URL, etc.
                        }
                    }
                    catch (Exception exception)
                    {
                        FoundationSync.LogMessage(601, FoundationSync.LogCategories.FoundationSync, TraceSeverity.Medium,
                                                  exception.Message + exception.StackTrace, null);
                    }
                });
            }
            else
            {
                try
                {
                    var byteArray = (byte[])directoryEntry.Properties["thumbnailPhoto"].Value;

                    if (byteArray.Length > 0)
                    {
                        using (var ms = new MemoryStream(byteArray))
                        {
                            var image = new Bitmap(ms);
                            fileUri = SaveImage(image, siteUri.AbsoluteUri, fileName);
                        }
                    }
                }
                catch (Exception)
                {
                    return(string.Empty);
                }
            }

            return(!string.IsNullOrEmpty(fileUri) ? fileUri : null);
        }