private void EnableAnonumous(SPFeatureReceiverProperties properties) { try { if (webApp != null) { SPUrlZone urlZone = SPUrlZone.Default; //SPWebApplication specifiedWebApplication = specifiedSite.WebApplication; SPIisSettings iisSettings = webApp.IisSettings[urlZone]; iisSettings.AuthenticationMode = AuthenticationMode.Windows; iisSettings.AllowAnonymous = true; try { SPWebConfigModificationExtensions.WaitForOnetimeJobToFinish(webApp.Farm, "job-webconfig-modification", 180); webApp.Farm.Services.GetValue <SPWebService>().ApplyWebConfigModifications(); ////webApp.WebService.ApplyWebConfigModifications(); webApp.Update(); } catch (Exception ex) { SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data); //ex.ToString(); } } } catch (Exception ex) { SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data); //ex.ToString(); } }
public static SPListItem GetClaimProvider(SPWebApplication webApp, SPUrlZone zone) { SPAdministrationWebApplication adminWebApp = SPAdministrationWebApplication.Local; using (SPSite siteCollection = new SPSite(adminWebApp.Sites[0].Url)) { using (SPWeb site = siteCollection.OpenWeb()) { SPList list = site.Lists.TryGetList("Nauplius.ADLDS.FBA - WebApplicationSettings"); if (list != null) { if (list.ItemCount >= 1) { foreach (SPListItem item in list.Items) { if (item["WebApplicationUrl"].ToString() == webApp.GetResponseUri(zone).AbsoluteUri) { return(item); } } } } } } return(null); }
public static void RunWithSiteAdminPrivileges(Guid siteId, SPUrlZone urlZone, CodeToRunElevatedWithSite codeToRunElevatedWithSite) { RunWithoutAccessDenied( () => RunWithUserTokenPrivilege(siteId, urlZone, GetSiteAdminUserToken(siteId, urlZone), codeToRunElevatedWithSite)); }
public static void RunWithSystemAccountPrivileges(Guid siteId, Guid webId, SPUrlZone urlZone, CodeToRunElevatedWithWeb codeToRunElevatedWithWeb) { RunWithoutAccessDenied( () => RunWithUserTokenPrivilege(siteId, webId, urlZone, GetSystemAccountUserToken(siteId, urlZone), codeToRunElevatedWithWeb)); }
public WebSiteZoneModifier(SPWebApplication application, SPUrlZone zone, string url, bool delete) : base("Zone Modifier for " + application.Name, application, null, SPJobLockType.None) { this._delete = delete; this.Zone = zone; this.Url = url; }
private static SPUserToken GetSiteAdminUserToken(Guid siteId, SPUrlZone urlZone) { SPUserToken siteAdminUserToken = null; RunWithElevatedPrivileges(delegate { using (SPSite site = new SPSite(siteId, urlZone)) { using (SPSite site2 = new SPSite(siteId, urlZone, site.SystemAccount.UserToken)) { IEnumerator enumerator = site2.RootWeb.SiteUsers.GetEnumerator(); SPUser current; while (enumerator.MoveNext()) { current = (SPUser)enumerator.Current; if (current.IsSiteAdmin) { goto Label_0061; } } return; Label_0061: siteAdminUserToken = current.UserToken; } } }); return(siteAdminUserToken); }
/// <summary> /// Extends the web app. /// </summary> /// <param name="webApplication">The web application.</param> /// <param name="description">The description.</param> /// <param name="hostHeader">The host header.</param> /// <param name="port">The port.</param> /// <param name="loadBalancedUrl">The load balanced URL.</param> /// <param name="path">The path.</param> /// <param name="allowAnonymous">if set to <c>true</c> [allow anonymous].</param> /// <param name="useNtlm">if set to <c>true</c> [use NTLM].</param> /// <param name="useSsl">if set to <c>true</c> [use SSL].</param> /// <param name="zone">The zone.</param> public static void ExtendWebApp(SPWebApplication webApplication, string description, string hostHeader, int port, string loadBalancedUrl, string path, bool allowAnonymous, bool useNtlm, bool useSsl, SPUrlZone zone) { SPServerBinding serverBinding = null; SPSecureBinding secureBinding = null; if (!useSsl) { serverBinding = new SPServerBinding(); serverBinding.Port = port; serverBinding.HostHeader = hostHeader; } else { secureBinding = new SPSecureBinding(); secureBinding.Port = port; } SPIisSettings settings = new SPIisSettings(description, allowAnonymous, useNtlm, serverBinding, secureBinding, new DirectoryInfo(path.Trim())); settings.PreferredInstanceId = GetPreferredInstanceId(description); webApplication.IisSettings.Add(zone, settings); webApplication.AlternateUrls.SetResponseUrl(new SPAlternateUrl(new Uri(loadBalancedUrl), zone)); webApplication.AlternateUrls.Update(); webApplication.Update(); webApplication.ProvisionGlobally(); }
/// <summary> /// Iterates through all site collections in this web application. /// </summary> /// <param name="webApplication"></param> /// <param name="urlZone"></param> /// <param name="methodToCall">Method to call on each site collection visit. Method should return true for continuing the iteration or false to end and return.</param> public static void ForEachSite(this SPWebApplication webApplication, SPUrlZone urlZone, Func<SPSite, bool> methodToCall) { string webAppUrl = webApplication.GetResponseUri(urlZone).ToString(); string[] siteUrls = webApplication.Sites.Names; foreach (string siteUrl in siteUrls) { string url = webAppUrl; if (webAppUrl.EndsWith("/")) { url = webAppUrl.Substring(0, webAppUrl.Length - 1); } if (siteUrl.StartsWith("/")) { url += siteUrl; } else { url += "/" + siteUrl; } using (SPSite site = new SPSite(url)) { bool bContinue = methodToCall.Invoke(site); if (!bContinue) return; } } }
public static void RemoveMapping(SPWebApplication webApp, SPUrlZone zone) { if (webApp == null) { return; } webApp.SiteDataServers.Remove(zone); webApp.Update(); }
ProviderSettings GetMembershipProvider(SPWebApplication webApplication, SPUrlZone zone, string providerName) { ConfigurationSection section; var manager = WebConfigurationManager.OpenWebConfiguration("/", webApplication.Name); var membershipSection = (MembershipSection)manager.GetSection("configuration/system.web/membership"); var providerSettings = membershipSection.Providers[providerName]; return(providerSettings); }
private static void RunWithUserTokenPrivilege(Guid siteId, SPUrlZone urlZone, SPUserToken userToken, CodeToRunElevatedWithSite codeToRunElevatedWithSite) { RunWithoutAccessDenied(() => { using (SPSite site = new SPSite(siteId, urlZone, userToken)) { codeToRunElevatedWithSite(site); } }); }
public List <IdentityProvider> getIdentityProviders() { UPSBrowserLogger.LogDebug(loggingCategory, "getIdentityProviders invoked"); List <IdentityProvider> identityProvidersToReturn = new List <IdentityProvider>(); try { SPSecurity.RunWithElevatedPrivileges(delegate() { UPSBrowserLogger.LogDebug(loggingCategory, "Running with elevated privileges"); try { SPContext spContext = Microsoft.SharePoint.SPContext.Current; SPWebApplication webApp = spContext.Site.WebApplication; SPUrlZone spUrlZone = spContext.Site.Zone; SPIisSettings spIisSettings = webApp.GetIisSettingsWithFallback(spUrlZone); SPSecurityTokenServiceManager sptMgr = SPSecurityTokenServiceManager.Local; foreach (SPAuthenticationProvider prov in spIisSettings.ClaimsAuthenticationProviders) { if (prov.GetType() == typeof(Microsoft.SharePoint.Administration.SPTrustedAuthenticationProvider)) { var lp = from SPTrustedLoginProvider spt in sptMgr.TrustedLoginProviders where spt.DisplayName == prov.DisplayName select spt; if ((lp != null) && (lp.Count() > 0)) { SPTrustedLoginProvider loginProv = lp.First(); identityProvidersToReturn.Add(new IdentityProvider { Name = loginProv.Name, DisplayName = loginProv.DisplayName, Description = loginProv.Description, }); } } } } catch (Exception e) { UPSBrowserLogger.LogError(loggingCategory, e.Message); }; }); } catch (System.Exception e) { UPSBrowserLogger.LogError(loggingCategory, $"Error while trying to elevate privileges: {e.Message}"); }; return(identityProvidersToReturn); }
/// <summary> /// Uns the extend. /// </summary> /// <param name="webApp">The web app.</param> /// <param name="zone">The zone.</param> /// <param name="deleteIis">if set to <c>true</c> [delete IIS].</param> public static void UnExtend(SPWebApplication webApp, SPUrlZone zone, bool deleteIis) { webApp.UnprovisionGlobally(deleteIis); webApp.IisSettings.Remove(zone); if (zone != SPUrlZone.Default) { webApp.AlternateUrls.UnsetResponseUrl(zone); webApp.AlternateUrls.Update(); } webApp.Update(); }
private static void RunWithUserTokenPrivilege(Guid siteId, Guid webId, SPUrlZone urlZone, SPUserToken userToken, CodeToRunElevatedWithWeb codeToRunElevatedWithWeb) { RunWithoutAccessDenied(() => { using (SPSite site = new SPSite(siteId, urlZone, userToken)) { using (SPWeb web = site.OpenWeb(webId)) { codeToRunElevatedWithWeb(web); } } }); }
private static SPUserToken GetSystemAccountUserToken(Guid siteId, SPUrlZone urlZone) { SPUserToken systemAccountUserToken = null; RunWithElevatedPrivileges(delegate { using (SPSite site = new SPSite(siteId, urlZone)) { systemAccountUserToken = site.SystemAccount.UserToken; } }); return(systemAccountUserToken); }
public static void RunWithAccountsChainPrivileges(Guid siteId, Guid webId, SPUrlZone urlZone, CodeToRunElevatedWithWeb codeToRunElevatedWithWeb) { try { RunWithSystemAccountPrivileges(siteId, webId, urlZone, codeToRunElevatedWithWeb); } catch { try { RunWithSiteAdminPrivileges(siteId, webId, urlZone, codeToRunElevatedWithWeb); } catch (Exception exception) { throw new CanNotPrivilegesElevationException(exception); } } }
/// <summary> /// Runs the specified command. /// </summary> /// <param name="command">The command.</param> /// <param name="keyValues">The key values.</param> /// <param name="output">The output.</param> /// <returns></returns> public override int Execute(string command, System.Collections.Specialized.StringDictionary keyValues, out string output) { output = string.Empty; string url = Params["url"].Value; bool deleteIis = Params["deleteiiswebsite"].UserTypedIn; SPWebApplication webApp = SPWebApplication.Lookup(new Uri(url)); SPUrlZone zone = (SPUrlZone)Enum.Parse(typeof(SPUrlZone), Params["zone"].Value, true); UnExtend(webApp, zone, deleteIis); return((int)ErrorCodes.NoError); }
protected void btnDelete_OnDelete(object sender, EventArgs e) { for (int i = 0; i < GvItems.Rows.Count; i++) { var chkDelete = (CheckBox)GvItems.Rows[i].Cells[0].FindControl("chkId"); if (chkDelete.Checked) { var lblZone = (Label)GvItems.Rows[i].Cells[1].FindControl("lblZone"); SPUrlZone zone; SPUrlZone.TryParse(lblZone.Text, out zone); Mapping.RemoveMapping(_webApplication, zone); } } PopulateGridView(); }
/// <summary> /// Runs the specified command. /// </summary> /// <param name="command">The command.</param> /// <param name="keyValues">The key values.</param> /// <param name="output">The output.</param> /// <returns></returns> public override int Execute(string command, System.Collections.Specialized.StringDictionary keyValues, out string output) { output = string.Empty; SPWebApplication webApplication = SPWebApplication.Lookup(new Uri(Params["url"].Value.TrimEnd('/'))); string description = Params["vsname"].Value; bool useSsl = Params["usessl"].UserTypedIn; string hostHeader = Params["hostheader"].Value; int port = int.Parse(Params["port"].Value); bool allowAnonymous = Params["allowanonymous"].UserTypedIn; bool useNtlm = Params["exclusivelyusentlm"].UserTypedIn; string path = Params["path"].Value; SPUrlZone zone = (SPUrlZone)Enum.Parse(typeof(SPUrlZone), Params["zone"].Value, true); string loadBalancedUrl = Params["loadbalancedurl"].Value; ExtendWebApp(webApplication, description, hostHeader, port, loadBalancedUrl, path, allowAnonymous, useNtlm, useSsl, zone); return((int)ErrorCodes.NoError); }
public override void LoadChildren() { foreach (var item in this.Collection) { SPUrlZone zone = item.Key; var iisSettings = item.Value; var node = new SPIisSettingsNode(); var index = this.Children.Count; node.NodeProvider = this.NodeProvider; node.SPObjectType = iisSettings.GetType(); node.SPObject = iisSettings; node.ID = iisSettings.GetType().FullName + index; node.Index = index; node.Setup(this); node.Text = zone.ToString(); this.Children.Add(node); } }
public static void AddMapping(SPWebApplication webApp, SPUrlZone zone, SPServer server) { if (webApp == null || server == null) { return; } var uri = new Uri("http://" + server.Name); var list = new List <System.Uri>(1) { uri }; try { webApp.SiteDataServers.Add(zone, list); webApp.Update(); } catch (ArgumentException) //duplicate key { } }
public static string GetPulsusConfigPath(this SPWebApplication application, SPUrlZone zone) { return Path.Combine(application.GetIisSettingsWithFallback(zone).Path.FullName, Constants.PulsusConfigFileName); }
protected virtual bool SetSPTrustInCurrentContext(Uri context) { var webApp = SPWebApplication.Lookup(context); if (webApp == null) { return(false); } SPSite site = null; try { site = new SPSite(context.AbsoluteUri); } catch (Exception) { // The root site doesn't exist this.associatedSPTrustedLoginProvider = Utils.GetSPTrustAssociatedWithCP(ProviderInternalName); if (this.associatedSPTrustedLoginProvider != null && this.associatedSPTrustedLoginProvider.IdentityClaimTypeInformation != null) { this.identifierClaimType = this.associatedSPTrustedLoginProvider.IdentityClaimTypeInformation.InputClaimType; } return(this.associatedSPTrustedLoginProvider != null); } if (site == null) { return(false); } SPUrlZone currentZone = site.Zone; SPIisSettings iisSettings = webApp.GetIisSettingsWithFallback(currentZone); site.Dispose(); if (!iisSettings.UseTrustedClaimsAuthenticationProvider) { return(false); } // Get the list of authentication providers associated with the zone foreach (SPAuthenticationProvider prov in iisSettings.ClaimsAuthenticationProviders) { if (prov.GetType() == typeof(Microsoft.SharePoint.Administration.SPTrustedAuthenticationProvider)) { // Check if the current SPTrustedAuthenticationProvider is associated with the claim provider if (prov.ClaimProviderName == ProviderInternalName) { this.associatedSPTrustedLoginProvider = Utils.GetSPTrustAssociatedWithCP(ProviderInternalName); if (this.associatedSPTrustedLoginProvider != null && this.associatedSPTrustedLoginProvider.IdentityClaimTypeInformation != null) { this.identifierClaimType = this.associatedSPTrustedLoginProvider.IdentityClaimTypeInformation.InputClaimType; } return(this.associatedSPTrustedLoginProvider != null); } } } return(false); }
protected override void OnLoad(EventArgs e) { if (!IsPostBack) { if (SPContext.Current == null) { return; } if (SPContext.Current.Site == null) { return; } if (SPContext.Current.Site.WebApplication == null) { return; } SPWebApplication app = SPContext.Current.Site.WebApplication; SignInConfiguration config = app.GetChild <SignInConfiguration>("SignInConfig"); if (config == null) { throw new NullReferenceException("Config was not found"); } SPAlternateUrl u = app.AlternateUrls[Request.Url]; if (u == null) { throw new NullReferenceException("Could not find " + Request.Url + " in alternate URLs"); } SPUrlZone zone = u.UrlZone; string components = Request.Url.GetComponents(UriComponents.Query, UriFormat.SafeUnescaped); if (!app.IisSettings.ContainsKey(zone)) { zone = SPUrlZone.Default; } //throw new KeyNotFoundException("IIS settings did not have zone " + zone); SPIisSettings settings = app.IisSettings[zone]; bool isMappingFound = false; IPAddress ipv4 = IpNetworking.GetIP4Address(); string targetProvider; try { KeyValuePair <IPNetwork, string> providerMapping = config.ProviderMappings .Select(kvp => new KeyValuePair <IPNetwork, string>(IPNetwork.Parse(kvp.Key), kvp.Value)) .Where(x => IPNetwork.Contains(x.Key, ipv4)) .OrderBy(x => x.Key.Cidr) .Last(); isMappingFound = true; targetProvider = providerMapping.Value; } catch { isMappingFound = false; targetProvider = null; } var signinPageMappings = config.SingInPageMappings; if (config != null && isMappingFound) { foreach (SPAuthenticationProvider provider in settings.ClaimsAuthenticationProviders) { if (string.Compare(provider.DisplayName, targetProvider, true, System.Globalization.CultureInfo.CurrentUICulture) == 0 || string.Compare(provider.ClaimProviderName, targetProvider, true, System.Globalization.CultureInfo.CurrentUICulture) == 0) { string url = provider.AuthenticationRedirectionUrl.ToString(); if (signinPageMappings.ContainsKey(provider.DisplayName)) { url = signinPageMappings[provider.DisplayName]; } if (provider is SPWindowsAuthenticationProvider) { components = EnsureReturnUrl(components); } SPUtility.Redirect(url, SPRedirectFlags.Default, this.Context, components); } } base.OnLoad(e); } else { string loginPage = string.Empty; if (signinPageMappings.ContainsKey("default")) { loginPage = signinPageMappings["default"]; } if (!string.IsNullOrEmpty(loginPage)) { SPUtility.Redirect(loginPage, SPRedirectFlags.Default, this.Context, components); base.OnLoad(e); } } } }
public static String GetUrlByZone(SPSite spSite, SPUrlZone zone) { try { SPAlternateUrlCollectionManager urlAccMgr = spSite.WebApplication.Farm.AlternateUrlCollections; Uri responseUri = urlAccMgr.RebaseUriWithAlternateUri(new Uri(spSite.Url), zone); return responseUri.OriginalString; } catch (Exception) { string returnUrl = string.Empty; SPSecurity.RunWithElevatedPrivileges(delegate { using (var site = new SPSite(spSite.Url)) { SPAlternateUrlCollectionManager urlAccMgr = site.WebApplication.Farm.AlternateUrlCollections; Uri responseUri = urlAccMgr.RebaseUriWithAlternateUri(new Uri(spSite.Url), zone); returnUrl = responseUri.OriginalString; } }); return returnUrl; } }
public static void Delete(SearchResultCollection users, string loginAttribute, SPWebApplication webApplication, string serverName, int portNumber, SPUrlZone zone) { SPSite site = null; try { site = new SPSite(WebApplication.GetResponseUri(zone).AbsoluteUri); SPIisSettings iisSettings = webApplication.GetIisSettingsWithFallback(zone); foreach (SPAuthenticationProvider provider in iisSettings.ClaimsAuthenticationProviders) { if (provider is SPFormsAuthenticationProvider) { SPFormsAuthenticationProvider formsProvider = provider as SPFormsAuthenticationProvider; SPServiceContext serviceContext = SPServiceContext.GetContext(site); UserProfileManager uPM = new UserProfileManager(serviceContext); SPSecurity.RunWithElevatedPrivileges(delegate() { string search = ClaimsIdentifier + "|" + formsProvider.MembershipProvider + "|"; List <UserProfile> uPAResults = uPM.Search(search).Cast <UserProfile>().ToList(); List <SearchResult> usersList = users.Cast <SearchResult>().ToList(); var query = usersList.Select(sr => sr.GetDirectoryEntry().Properties["distinguishedName"].Value.ToString()); HashSet <string> paths = new HashSet <string>(query); var profiles = uPAResults.Select(profile => new { ShouldKeep = paths.Contains(profile[PropertyConstants.DistinguishedName].Value.ToString()), Profile = profile }); foreach (var profile in profiles.Where(result => !result.ShouldKeep)) { try { uPM.RemoveProfile(profile.Profile); Logging.LogMessage(212, Logging.LogCategories.Profiles, TraceSeverity.Verbose, "Removed profile " + profile.Profile[PropertyConstants.DistinguishedName].Value, new object[] { null }); } catch (Exception ex) { Logging.LogMessage(502, Logging.LogCategories.Profiles, TraceSeverity.Unexpected, "Failed to delete profile " + profile.Profile[PropertyConstants.DistinguishedName].Value + " " + ex.Message, new object[] { null }); } } }); } } } catch (Exception ex) { Logging.LogMessage(502, Logging.LogCategories.Profiles, TraceSeverity.Unexpected, ex.Message, new object[] { null }); } finally { if (site != null) { site.Dispose(); } } }
public static string GetVirtualDirectoryPath(SPUrlZone zone, SPSite site) { try { return site.WebApplication.IisSettings[zone].Path.FullName; } catch (Exception) { return string.Empty; } }
internal static void AddUserPolicy(string login, string username, string[] permissions, SPWebApplication webApp, SPUrlZone[] zones) { foreach (SPUrlZone zone in zones) AddUserPolicy(login, username, permissions, webApp, webApp.ZonePolicies(zone)); }
protected void FillItems(SPWebApplication selectedWebApp, SPUrlZone zone) { using (var siteCollection = new SPSite(SPContext.Current.Site.ID)) { using (var site = siteCollection.OpenWeb()) { try { var list = site.Lists.TryGetList("Nauplius.ADLDS.FBA - WebApplicationSettings"); if (list != null) { if (selectedWebApp != null) { string webAppUrl = selectedWebApp.GetResponseUri(zone).AbsoluteUri; var items = list.Items; foreach (SPListItem item in items) { if (item["WebApplicationUrl"].ToString() == webAppUrl) { try { ddlZonePicker.SelectedValue = item["WebApplicationZone"].ToString(); } catch (Exception) { //In case someone manually modified the SPUrlZone in the list ddlZonePicker.SelectedValue = "Default"; } txtMemProv.Text = (item["WebApplicationMembershipProvider"] == null) ? String.Empty : item["WebApplicationMembershipProvider"].ToString(); txtRoleProv.Text = (item["WebApplicationRoleProvider"] == null) ? String.Empty : item["WebApplicationRoleProvider"].ToString(); txtCustomUrl.Text = (item["CustomUrl"] == null) ? String.Empty : item["CustomUrl"].ToString(); //AD LDS Server tBSN.Text = (item["ADLDSServer"] == null) ? String.Empty : item["ADLDSServer"].ToString(); tBPrtNo.Text = (item["ADLDSPort"] == null) ? String.Empty : item["ADLDSPort"].ToString(); cBUseSSL.Checked = (bool)item["ADLDSUseSSL"]; //User tBLoginAttrib.Text = (item["ADLDSLoginAttrib"] == null) ? String.Empty : item["ADLDSLoginAttrib"].ToString(); txtUsrDNAttrib.Text = (item["ADLDSUserDNAttrib"] == null) ? string.Empty : item["ADLDSUserDNAttrib"].ToString(); txtUsrContainer.Text = (item["ADLDSUserContainer"] == null) ? string.Empty : item["ADLDSUserContainer"].ToString(); txtUsrObjClass.Text = (item["ADLDSUserObjectClass"] == null) ? string.Empty : item["ADLDSUserObjectClass"].ToString(); txtUsrFilter.Text = (item["ADLDSUserFilter"] == null) ? string.Empty : item["ADLDSUserFilter"].ToString(); txtUsrScope.Text = (item["ADLDSUserScope"] == null) ? string.Empty : item["ADLDSUserScope"].ToString(); txtUsrOtherAttribs.Text = (item["ADLDSUserOtherReqAttrib"] == null) ? string.Empty : item["ADLDSUserOtherReqAttrib"].ToString(); //Group txtGrpContainer.Text = (item["ADLDSGroupContainer"] == null) ? string.Empty : item["ADLDSGroupContainer"].ToString(); txtGrpNameAttrib.Text = (item["ADLDSGroupNameAttrib"] == null) ? string.Empty : item["ADLDSGroupNameAttrib"].ToString(); txtGrpAltSearchAttrib.Text = (item["ADLDSGroupNameAltSearchAttrib"] == null) ? string.Empty : item["ADLDSGroupNameAltSearchAttrib"] .ToString(); txtGrpMemAttrib.Text = (item["ADLDSGroupMemAttrib"] == null) ? string.Empty : item["ADLDSGroupMemAttrib"].ToString(); txtGrpDNAttrib.Text = (item["ADLDSGroupDNAttrib"] == null) ? string.Empty : item["ADLDSGroupDNAttrib"].ToString(); txtGrpUsrFilter.Text = (item["ADLDSGroupUserFilter"] == null) ? string.Empty : item["ADLDSGroupUserFilter"].ToString(); txtGrpFilter.Text = (item["ADLDSGroupFilter"] == null) ? string.Empty : item["ADLDSGroupFilter"].ToString(); txtGrpScope.Text = (item["ADLDSGroupScope"] == null) ? string.Empty : item["ADLDSGroupScope"].ToString(); txtGrpUsrDnAttrib.Text = (item["ADLDSGroupUserDNAttrib"] == null) ? string.Empty : item["ADLDSGroupUserDNAttrib"].ToString(); } else { txtMemProv.Text = string.Empty; txtRoleProv.Text = string.Empty; txtCustomUrl.Text = string.Empty; tBSN.Text = string.Empty; tBPrtNo.Text = string.Empty; cBUseSSL.Checked = false; tBLoginAttrib.Text = string.Empty; txtUsrDNAttrib.Text = "distinguishedName"; txtUsrContainer.Text = string.Empty; txtUsrObjClass.Text = "user"; txtUsrFilter.Text = "(ObjectClass=*)"; txtUsrScope.Text = "Subtree"; txtUsrOtherAttribs.Text = "sn,givenname,cn"; txtGrpContainer.Text = string.Empty; txtGrpNameAttrib.Text = "cn"; txtGrpAltSearchAttrib.Text = "cn"; txtGrpMemAttrib.Text = "member"; txtGrpDNAttrib.Text = "distinguishedName"; txtGrpUsrFilter.Text = @"&(objectCategory=Group)(objectClass=group)"; txtGrpScope.Text = "Subtree"; txtGrpUsrDnAttrib.Text = "distinguishedName"; } } } } } catch (SPException) { } } } }
public static void CreateWildcardNode(bool removeModification, SPWebApplication webApp, SPUrlZone zone) { if (webApp.UseClaimsAuthentication) { string name1, xpath1, value1, name2, value2; SPListItem provider = GetClaimProvider(webApp, zone); xpath1 = "configuration/SharePoint/PeoplePickerWildcards"; name1 = String.Format("add[@key='{0}']", provider["WebApplicationMembershipProvider"]); value1 = String.Format("<add key='{0}' value='*' />", provider["WebApplicationMembershipProvider"]); name2 = String.Format("add[@key='{0}']", provider["WebApplicationRoleProvider"]); value2 = String.Format("<add key='{0}' value='*' />", provider["WebApplicationRoleProvider"]); var names = new List <string>(); names.Add(name1); names.Add(name2); if (removeModification) { RemoveAllModifications(webApp, names); try { webApp.Farm.Services.GetValue <SPWebService>().ApplyWebConfigModifications(); } catch (Exception) {} return; } ModifyWebConfig(webApp, name1, xpath1, value1, SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode); ModifyWebConfig(webApp, name2, xpath1, value2, SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode); try { webApp.Farm.Services.GetValue <SPWebService>().ApplyWebConfigModifications(); } catch (Exception ex) { RemoveAllModifications(webApp, names); throw ex; } } }
public static void CreateProviderNode(bool removeModification, SPWebApplication webApp, SPUrlZone zone) { if (webApp.UseClaimsAuthentication) { string name1, xpath1, value1, name2, xpath2, value2; SPListItem provider = GetClaimProvider(webApp, zone); name1 = string.Format("add[@name='{0}']", provider["WebApplicationMembershipProvider"]); xpath1 = "configuration/system.web/membership/providers"; value1 = String.Format("<add name='{0}' type='{1}' server='{2}' port='{3}' " + "useSSL='{4}' userDNAttribute='{5}' useDNAttribute='{6}' userNameAttribute='{7}' " + "userContainer='{8}' userObjectClass='{9}' userFilter='{10}' scope='{11}' " + "otherRequiredUserAttributes='{12}' />", provider["WebApplicationMembershipProvider"], ProviderMemberType, provider["ADLDSServer"], provider["ADLDSPort"], provider["ADLDSUseSSL"], provider["ADLDSUserDNAttrib"], "true", provider["ADLDSLoginAttrib"], provider["ADLDSUserContainer"], provider["ADLDSUserObjectClass"], provider["ADLDSUserFilter"], provider["ADLDSUserScope"], provider["ADLDSUserOtherReqAttrib"]); name2 = String.Format("add[@name='{0}']", provider["WebApplicationRoleProvider"]); xpath2 = "configuration/system.web/roleManager/providers"; value2 = String.Format("<add name='{0}' type='{1}' server='{2}' port='{3}' " + "useSSL='{4}' enableSearchMethods='{5}' groupNameAttribute='{6}' " + "groupContainer='{7}' groupNameAlterateSearchAttribute='{8}' groupMemberAttribute='{9}' " + "userNameAttribute='{10}' dnAttribute='{11}' useUserDNAttribute='{12}' scope='{13}' " + "userFilter=\"{14}\" groupFilter=\"{15}\" />", provider["WebApplicationRoleProvider"], ProviderRoleType, provider["ADLDSServer"], provider["ADLDSPort"], provider["ADLDSUseSSL"], "true", provider["ADLDSGroupNameAttrib"], provider["ADLDSGroupContainer"], provider["ADLDSGroupNameAltSearchAttrib"], provider["ADLDSGroupMemAttrib"], provider["ADLDSLoginAttrib"], provider["ADLDSGroupDNAttrib"], "true", provider["ADLDSGroupScope"], provider["ADLDSGroupUserFilter"], provider["ADLDSGroupFilter"]); var names = new List <string>(); names.Add(name1); names.Add(name2); if (removeModification) { RemoveAllModifications(webApp, names); try { webApp.Farm.Services.GetValue <SPWebService>().ApplyWebConfigModifications(); } catch (Exception) { } return; } ModifyWebConfig(webApp, name1, xpath1, value1, SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode); ModifyWebConfig(webApp, name2, xpath2, value2, SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode); try { webApp.Farm.Services.GetValue <SPWebService>().ApplyWebConfigModifications(); } catch (Exception ex) { RemoveAllModifications(webApp, names); throw ex; } } }
public static bool CreateStsProviderNode(bool removeModification, SPFeatureReceiverProperties properties, SPUrlZone zone) { string featureId = properties.Feature.DefinitionId.ToString(); SPWebApplication webApp = properties.Feature.Parent as SPWebApplication; if (webApp.UseClaimsAuthentication) { SPListItem provider = GetClaimProvider(webApp, zone); string value = String.Format("<add name='{0}' type='{1}' server='{2}' port='{3}' " + "useSSL='{4}' userDNAttribute='{5}' useDNAttribute='{6}' userNameAttribute='{7}' " + "userContainer='{8}' userObjectClass='{9}' userFilter='{10}' scope='{11}' " + "otherRequiredUserAttributes='{12}' />", provider["WebApplicationMembershipProvider"], ProviderMemberType, provider["ADLDSServer"], provider["ADLDSPort"], provider["ADLDSUseSSL"], provider["ADLDSUserDNAttrib"], "true", provider["ADLDSLoginAttrib"], provider["ADLDSUserContainer"], provider["ADLDSUserObjectClass"], provider["ADLDSUserFilter"], provider["ADLDSUserScope"], provider["ADLDSUserOtherReqAttrib"]); string value2 = String.Format("<add name='{0}' type='{1}' server='{2}' port='{3}' " + "useSSL='{4}' enableSearchMethods='{5}' groupNameAttribute='{6}' " + "groupContainer='{7}' groupNameAlterateSearchAttribute='{8}' groupMemberAttribute='{9}' " + "userNameAttribute='{10}' dnAttribute='{11}' useUserDNAttribute='{12}' scope='{13}' " + "userFilter=\"{14}\" groupFilter=\"{15}\" />", provider["WebApplicationRoleProvider"], ProviderRoleType, provider["ADLDSServer"], provider["ADLDSPort"], provider["ADLDSUseSSL"], "true", provider["ADLDSGroupNameAttrib"], provider["ADLDSGroupContainer"], provider["ADLDSGroupNameAltSearchAttrib"], provider["ADLDSGroupMemAttrib"], provider["ADLDSLoginAttrib"], provider["ADLDSGroupDNAttrib"], "true", provider["ADLDSGroupScope"], provider["ADLDSGroupUserFilter"], provider["ADLDSGroupFilter"]); using (SPSite siteCollection = new SPSite(SPContext.Current.Site.ID)) { using (SPWeb site = siteCollection.OpenWeb()) { try { SPList list = site.Lists.TryGetList("Nauplius.ADLDS.FBA - StsFarm"); if (list != null) { if (list.ItemCount >= 1) { foreach (SPListItem item in list.Items) { if (item["StsConfig"].ToString() == "MasterXmlFragment") { MasterXmlFragment.LoadXml((string)item["XMLStsConfig"]); XmlDocumentFragment xmlFrag1 = MasterXmlFragment.CreateDocumentFragment(); xmlFrag1.InnerXml = value2; try { string nvalue = xmlFrag1.FirstChild.Attributes.GetNamedItem("name").Value; XmlNode node = MasterXmlFragment.DocumentElement.SelectSingleNode( "roleManager/providers/add[@name='" + nvalue + "']"); node.ParentNode.RemoveChild(node); } catch (Exception) {} if (!removeModification) { MasterXmlFragment.DocumentElement.SelectSingleNode("roleManager/providers") .AppendChild(xmlFrag1); } XmlDocumentFragment xmlFrag2 = MasterXmlFragment.CreateDocumentFragment(); xmlFrag2.InnerXml = value; try { string nvalue = xmlFrag2.FirstChild.Attributes.GetNamedItem("name").Value; XmlNode node = MasterXmlFragment.DocumentElement.SelectSingleNode( "membership/providers/add[@name='" + nvalue + "']"); node.ParentNode.RemoveChild(node); } catch (Exception) { } if (!removeModification) { MasterXmlFragment.DocumentElement.SelectSingleNode("membership/providers") .AppendChild(xmlFrag2); } item["XMLStsConfig"] = MasterXmlFragment.OuterXml; item.Update(); return(true); } } } } } catch { return(false); } } } } return(true); }
public static void Create(SearchResultCollection users, string loginAttribute, SPWebApplication webApplication, string serverName, int portNumber, SPUrlZone zone) { foreach (SearchResult user in users) { DirectoryEntry de2 = user.GetDirectoryEntry(); SPSite site = null; try { site = new SPSite(WebApplication.GetResponseUri(zone).AbsoluteUri); SPIisSettings iisSettings = webApplication.GetIisSettingsWithFallback(zone); foreach (SPAuthenticationProvider provider in iisSettings.ClaimsAuthenticationProviders) { if (provider is SPFormsAuthenticationProvider) { SPFormsAuthenticationProvider formsProvider = provider as SPFormsAuthenticationProvider; SPServiceContext serviceContext = SPServiceContext.GetContext(site); UserProfileManager uPM = new UserProfileManager(serviceContext); SPSecurity.RunWithElevatedPrivileges(delegate() { if (de2.Properties[loginAttribute].Value != null) { if (!uPM.UserExists(ClaimsIdentifier + "|" + formsProvider.MembershipProvider + "|" + de2.Properties[loginAttribute].Value.ToString())) { Department = (de2.Properties[DepartmentAttrib].Value == null) ? String.Empty : de2.Properties[DepartmentAttrib].Value.ToString(); DistinguishedName = de2.Properties[DistinguishedNameAttrib].Value.ToString(); FirstName = (de2.Properties[FirstNameAttrib].Value == null) ? String.Empty : de2.Properties[FirstNameAttrib].Value.ToString(); LastName = (de2.Properties[LastNameAttrib].Value == null) ? String.Empty : de2.Properties[LastNameAttrib].Value.ToString(); Office = (de2.Properties[OfficeAttrib].Value == null) ? String.Empty : de2.Properties[OfficeAttrib].Value.ToString(); PreferredName = (de2.Properties[PreferredNameAttrib].Value == null) ? String.Empty : de2.Properties[PreferredNameAttrib].Value.ToString(); UserTitle = (de2.Properties[UserTitleAttrib].Value == null) ? String.Empty : de2.Properties[UserTitleAttrib].Value.ToString(); WebSite = (de2.Properties[WebSiteAttrib].Value == null) ? String.Empty : de2.Properties[WebSiteAttrib].Value.ToString(); WorkEmail = (de2.Properties[WorkEmailAttrib].Value == null) ? String.Empty : de2.Properties[WorkEmailAttrib].Value.ToString(); WorkPhone = (de2.Properties[WorkPhoneAttrib].Value == null) ? String.Empty : de2.Properties[WorkPhoneAttrib].Value.ToString(); UserProfile newProfile = uPM.CreateUserProfile(ClaimsIdentifier + "|" + formsProvider.MembershipProvider + "|" + de2.Properties[loginAttribute].Value.ToString(), PreferredName); newProfile[PropertyConstants.Department].Add(Department); newProfile[PropertyConstants.DistinguishedName].Add(DistinguishedName); newProfile[PropertyConstants.FirstName].Add(FirstName); newProfile[PropertyConstants.LastName].Add(LastName); newProfile[PropertyConstants.Office].Add(Office); newProfile[PropertyConstants.Title].Add(UserTitle); newProfile[PropertyConstants.WebSite].Add(WebSite); newProfile[PropertyConstants.WorkEmail].Add(WorkEmail); newProfile[PropertyConstants.WorkPhone].Add(WorkPhone); try { newProfile.Commit(); Logging.LogMessage(210, Logging.LogCategories.Profiles, TraceSeverity.Verbose, "Created profile " + DistinguishedName, new object[] { null }); } catch (Exception ex) { Logging.LogMessage(510, Logging.LogCategories.Profiles, TraceSeverity.Unexpected, "Failed to create profile " + DistinguishedName + " " + ex.Message, new object[] { null }); } } else if (uPM.UserExists(ClaimsIdentifier + "|" + formsProvider.MembershipProvider + "|" + de2.Properties[loginAttribute].Value.ToString())) { UserProfile updateProfile = uPM.GetUserProfile(ClaimsIdentifier + "|" + formsProvider.MembershipProvider + "|" + de2.Properties[loginAttribute].Value.ToString()); updateProfile[PropertyConstants.Department].Value = (de2.Properties[DepartmentAttrib].Value == null) ? String.Empty : de2.Properties[DepartmentAttrib].Value.ToString(); updateProfile[PropertyConstants.DistinguishedName].Value = de2.Properties[DistinguishedNameAttrib].Value.ToString(); updateProfile[PropertyConstants.FirstName].Value = (de2.Properties[FirstNameAttrib].Value == null) ? String.Empty : de2.Properties[FirstNameAttrib].Value.ToString(); updateProfile[PropertyConstants.LastName].Value = (de2.Properties[LastNameAttrib].Value == null) ? String.Empty : de2.Properties[LastNameAttrib].Value.ToString(); updateProfile[PropertyConstants.Office].Value = (de2.Properties[OfficeAttrib].Value == null) ? String.Empty : de2.Properties[OfficeAttrib].Value.ToString(); updateProfile[PropertyConstants.PreferredName].Value = (de2.Properties[PreferredNameAttrib].Value == null) ? String.Empty : de2.Properties[PreferredNameAttrib].Value.ToString(); updateProfile[PropertyConstants.Title].Value = (de2.Properties[UserTitleAttrib].Value == null) ? String.Empty : de2.Properties[UserTitleAttrib].Value.ToString(); updateProfile[PropertyConstants.WebSite].Value = (de2.Properties[WebSiteAttrib].Value == null) ? String.Empty : de2.Properties[WebSiteAttrib].Value.ToString(); updateProfile[PropertyConstants.WorkEmail].Value = (de2.Properties[WorkEmailAttrib].Value == null) ? String.Empty : de2.Properties[WorkEmailAttrib].Value.ToString(); updateProfile[PropertyConstants.WorkPhone].Value = (de2.Properties[WorkPhoneAttrib].Value == null) ? String.Empty : de2.Properties[WorkPhoneAttrib].Value.ToString(); try { updateProfile.Commit(); Logging.LogMessage(211, Logging.LogCategories.Profiles, TraceSeverity.Verbose, "Updated profile " + updateProfile[PropertyConstants.DistinguishedName].Value, new object[] { null }); } catch (Exception ex) { Logging.LogMessage(511, Logging.LogCategories.Profiles, TraceSeverity.Unexpected, "Failed to update profile " + updateProfile[PropertyConstants.DistinguishedName].Value + " " + ex.Message, new object[] { null }); } } } }); } } } catch (Exception ex) { Logging.LogMessage(502, Logging.LogCategories.Profiles, TraceSeverity.Unexpected, ex.Message, new object[] { null }); } finally { if (site != null) { site.Dispose(); } } } }
/// <summary> /// Opens wrapper for SPWeb and SPSite by their ID's /// </summary> /// <param name="site">SPSite id</param> /// <param name="web">SPWeb id</param> /// <param name="zone">site zone</param> /// <returns>abstract wrapper for SPWeb and SPSite objects</returns> public static IQueryWeb Open(Guid site, Guid web, SPUrlZone zone) { return(new QueryWeb(site, web, false, zone)); }
public static string GetWebApplicationZoneUrl(SPWebApplication webApplication, SPUrlZone urlZone = SPUrlZone.Default) { if (webApplication == null) { return(string.Empty); } try { return(webApplication.GetResponseUri(urlZone).AbsoluteUri); } catch { return(string.Empty); } }
public static void CreateAdminWildcardNode(bool removeModification, SPWebApplication webApp, SPUrlZone zone) { var adminWebApplication = SPAdministrationWebApplication.Local; string name1, xpath1, value1, name2, value2; SPListItem provider = GetClaimProvider(webApp, zone); xpath1 = "configuration/SharePoint/PeoplePickerWildcards"; name1 = String.Format("add[@key='{0}']", provider["WebApplicationMembershipProvider"]); value1 = String.Format("<add key='{0}' value='*' />", provider["WebApplicationMembershipProvider"]); name2 = String.Format("add[@key='{0}']", provider["WebApplicationRoleProvider"]); value2 = String.Format("<add key='{0}' value='*' />", provider["WebApplicationRoleProvider"]); var names = new List <string>(); names.Add(name1); names.Add(name2); if (removeModification) { RemoveAllAdminModifications(adminWebApplication, names); try { SPWebService.AdministrationService.WebApplications[adminWebApplication.Id].WebService.ApplyWebConfigModifications(); } catch (Exception) { } return; } ModifyAdminWebConfig(adminWebApplication, name1, xpath1, value1, SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode); ModifyAdminWebConfig(adminWebApplication, name2, xpath1, value2, SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode); try { SPWebService.AdministrationService.WebApplications[adminWebApplication.Id].WebService.ApplyWebConfigModifications(); } catch (Exception ex) { RemoveAllAdminModifications(adminWebApplication, names); throw ex; } }