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)
            {
                FoudationSync.LogMessage(505, FoudationSync.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);
        }
        private static void RemoveUsers(SPUser objPrincipal, string siteUrl, int j)
        {
            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);
                        ++j;
                    }
                    catch (Exception e)
                    {
                        FoudationSync.LogMessage(506, FoudationSync.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);
                    }
                }
            }
        }
Beispiel #3
0
        internal static void CreateReportStorage()
        {
            var settingsStorage = new FoundationSyncStorage();

            if (settingsStorage.SyncSettings() == null)
            {
                return;
            }
            if (!settingsStorage.SyncSettings().LoggingEx)
            {
                return;
            }
            try
            {
                var adminWebApplication = SPAdministrationWebApplication.Local;

                using (SPSite site = adminWebApplication.Sites[0])
                {
                    var web = site.OpenWeb(site.RootWeb.ID);

                    var library = (from SPList list in web.Lists
                                   where list.RootFolder.Name.Equals(reportLibrary)
                                   select list).FirstOrDefault();

                    if (library == null)
                    {
                        var listTemplates    = web.ListTemplates["Document Library"];
                        var documentTemplate = (from SPDocTemplate dt in web.DocTemplates
                                                where dt.Type == 100
                                                select dt).FirstOrDefault();
                        var listGuid = web.Lists.Add(reportLibrary,
                                                     "Reporting on FoundationSync activity.", listTemplates,
                                                     documentTemplate);

                        library = (SPDocumentLibrary)web.Lists[listGuid];
                        library.OnQuickLaunch        = true;
                        library.EnableFolderCreation = false;
                        library.Update();
                        settingsStorage.SyncSettings().LoggingExLibrary = (SPDocumentLibrary)library;
                    }
                    else
                    {
                        settingsStorage.SyncSettings().LoggingExLibrary = (SPDocumentLibrary)library;
                    }
                }
            }
            catch (Exception e)
            {
                FoudationSync.LogMessage(402, FoudationSync.LogCategories.FoundationSync, TraceSeverity.Unexpected,
                                         "Unable to create Report Storage in Central Administration for" +
                                         " FoundationSyncSetting object. " + e.StackTrace, null);
            }
        }
Beispiel #4
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)
            {
                FoudationSync.LogMessage(405, FoudationSync.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)
            {
                FoudationSync.LogMessage(504, FoudationSync.LogCategories.FoundationSync, TraceSeverity.Unexpected,
                                         "Unable to read FoundationSyncSetting object. " + e.StackTrace, null);
            }

            return(null);
        }
        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)
            {
                FoudationSync.LogMessage(410, FoudationSync.LogCategories.FoundationSync, TraceSeverity.Unexpected,
                                         string.Format("Unexpected exception attempting to retrieve domain name: {0}. {1}", domainName, e.StackTrace), null);
                return(null);
            }

            return(ldapPath);
        }
        internal static void SearchPrincipals(HashSet <SPUser> objPrincipals,
                                              SPWebApplication webApplication, SPSite site, bool isGroup, int j, int u)
        {
            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;

                            try
                            {
                                loginName = new SecurityIdentifier(sid).Translate(typeof(NTAccount)).ToString();
                            }
                            catch (Exception exception)
                            {
                                FoudationSync.LogMessage(503, FoudationSync.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, u);
                        }
                        catch (DirectoryServicesCOMException exception)
                        {
                            FoudationSync.LogMessage(403, FoudationSync.LogCategories.FoundationSync, TraceSeverity.Unexpected,
                                                     exception.Message + exception.StackTrace, null);
                        }
                    }
                    else
                    {
                        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, j);
                                }
                                continue;
                            }

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

                            var directoryEntry = result.GetDirectoryEntry();
                            UpdateUser.User(objPrincipal, directoryEntry, listItems, itemCount, u);
                        }
                        catch (DirectoryServicesCOMException exception)
                        {
                            FoudationSync.LogMessage(404, FoudationSync.LogCategories.FoundationSync, TraceSeverity.Unexpected,
                                                     exception.Message + exception.StackTrace, null);
                        }
                    }
                }
            }
        }
Beispiel #8
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)
            {
                FoudationSync.LogMessage(1004, FoudationSync.LogCategories.FoundationSync, TraceSeverity.Unexpected,
                                         string.Format("Invalid Site URL specified for Picture Site Collection URL."), null);
                return(null);
            }
            catch (Exception)
            {
                FoudationSync.LogMessage(2001, FoudationSync.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)
                    {
                        FoudationSync.LogMessage(601, FoudationSync.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);
        }
Beispiel #9
0
        internal static void User(SPUser user, DirectoryEntry directoryEntry, SPListItemCollection listItems, int itemCount, int u)
        {
            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)
                    {
                        FoudationSync.LogMessage(506, FoudationSync.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)
                    {
                        FoudationSync.LogMessage(506, FoudationSync.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)
                    {
                        FoudationSync.LogMessage(506, FoudationSync.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)
                    {
                        FoudationSync.LogMessage(506, FoudationSync.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))
                            {
                                item["Picture"] = uri;
                            }
                            else if (string.IsNullOrEmpty(uri))
                            {
                                item["Picture"] = string.Empty;
                            }
                        }
                        catch (Exception)
                        {
                            FoudationSync.LogMessage(506, FoudationSync.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)
                                {
                                    FoudationSync.LogMessage(506, FoudationSync.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)
                            {
                                FoudationSync.LogMessage(506, FoudationSync.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)
                            {
                                FoudationSync.LogMessage(506, FoudationSync.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)
                    {
                        FoudationSync.LogMessage(506, FoudationSync.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)
                    {
                        FoudationSync.LogMessage(506, FoudationSync.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)
                    {
                        FoudationSync.LogMessage(201, FoudationSync.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();
                        ++u;
                    }

                    return;
                }
            }
            catch (SPException exception)
            {
                FoudationSync.LogMessage(401, FoudationSync.LogCategories.FoundationSync,
                                         TraceSeverity.Unexpected, exception.Message + " " + exception.StackTrace, null);
            }
        }
Beispiel #10
0
        public override void Execute(Guid targetInstanceId)
        {
            LoggingEx.CreateReportStorage();

            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);
                        }

                        if (_loggingEx)
                        {
                            LoggingExData(string.Format("{0} user principals in site {1}",
                                                        userAccounts.Count, site.Url), LoggingEx.LoggingExType.UsersFoundCount);
                        }

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

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

                        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);
                        }

                        if (_loggingEx)
                        {
                            LoggingExData(string.Format("{0} group principals in site {1}",
                                                        groupAccounts.Count, site.Url), LoggingEx.LoggingExType.UsersFoundCount);
                        }

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

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

                        site.Dispose();
                    }
                }

                if (_loggingEx)
                {
                    LoggingExData(string.Format("{0} user principals deleted",
                                                j), LoggingEx.LoggingExType.UsersDeletedCount);
                }

                if (_loggingEx)
                {
                    LoggingExData(string.Format("{0} users and groups updated",
                                                u), LoggingEx.LoggingExType.UsersUpdatedCount);
                }

                LoggingEx.SaveReport();
            }
            catch (IndexOutOfRangeException)
            {
                FoudationSync.LogMessage(102, FoudationSync.LogCategories.FoundationSync, TraceSeverity.Medium,
                                         string.Format("Index was out of range."), null);
            }
        }
Beispiel #11
0
        //Flow: Record group in report on Groups sheet (A), record any updated property (B), record overall updated (C)
        internal static void Group(SPUser group, DirectoryEntry directoryEntry,
                                   SPListItemCollection listItems, int itemCount, int u)
        {
            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)
                    {
                        FoudationSync.LogMessage(506, FoudationSync.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)
                                {
                                    FoudationSync.LogMessage(506, FoudationSync.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)
                            {
                                FoudationSync.LogMessage(506, FoudationSync.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)
                    {
                        FoudationSync.LogMessage(200, FoudationSync.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();
                        ++u;
                    }

                    return;
                }
            }
            catch (SPException exception)
            {
                FoudationSync.LogMessage(400, FoudationSync.LogCategories.FoundationSync,
                                         TraceSeverity.Unexpected, exception.Message + " " + exception.StackTrace, null);
            }
        }