/// <summary> /// Testing Method Only /// </summary> /// <returns></returns> public static List <string> GetAllSites2() { List <string> URL = new List <string>(); try { using (ClientContext userContext = Helper.CreateAuthenticatedUserContext(Program.AdminDomain, Program.AdminUsername, Program.AdminPassword, Constants.PortalRootSiteUrl)) { // Lists all site collections across all web applications... var spoTenant = new Microsoft.Online.SharePoint.TenantAdministration.Tenant(userContext); var getSite = spoTenant.GetSiteProperties(0, true); userContext.Load(getSite); userContext.ExecuteQuery(); foreach (var site in getSite) { URL.Add(site.Url); } return(URL); } } catch { return(URL); } }
public IHttpActionResult PostSite([FromBody] Website site) { List <Url> baseUrls = new List <Url>(); foreach (var item in dbCtx.Configurations) { baseUrls = item.Urls.Where(u => u.SiteCreationEnabled == true).ToList(); } if (baseUrls.Count == 0) { return(this.InternalServerError(new Exception("No base url with site creation enabled could be found!"))); } var realBaseUrl = (from u in baseUrls where u.Path.Equals(site.BaseUrl, StringComparison.InvariantCultureIgnoreCase) select u).ToList(); if (realBaseUrl.Count > 1) { return(this.InternalServerError(new Exception("Multiple matched base urls found! Please specify only one base url!"))); } // :) Url realRealBaseUrl = realBaseUrl.First(); using (ClientContext ctx = new ClientContext(realRealBaseUrl.Path)) { ICredentials credentials; if (realRealBaseUrl.IsOffice365) { credentials = CredentialManager.GetSharePointOnlineCredential("rmumsdn"); } else { credentials = CredentialManager.GetCredential("vdrmu009"); } if (credentials == null) { return(this.InternalServerError(new Exception("No valid credentials found!"))); } ctx.Credentials = credentials; Microsoft.Online.SharePoint.TenantAdministration.Tenant tenant = new Microsoft.Online.SharePoint.TenantAdministration.Tenant(ctx); site.ID = tenant.CreateSiteCollection(site.Url, site.Title, site.OwnerLogin, site.Type == WebsiteType.Collaboration ? "STS#0" : "STS#0", 100, 90, 3, 50, 40, site.Locale); ctx.ExecuteQuery(); } dbCtx.Websites.Add(site); dbCtx.SaveChangesAsync(); return(Ok(site.ID)); }
private static bool IsTenantAdminSite(ClientRuntimeContext clientContext) { if (clientContext.Url.ToLower().Contains(".sharepoint.")) { return(clientContext.Url.ToLower().Contains("-admin.sharepoint.")); } else { // fall back to old code in case of vanity domains try { var tenant = new Microsoft.Online.SharePoint.TenantAdministration.Tenant(clientContext); clientContext.ExecuteQueryRetry(); return(true); } catch (ServerException) { return(false); } } }
/// <summary> /// Applies a Provisioning Template Hierarchy to a target tenant /// </summary> /// <param name="targetSiteUrl">The URL of the target Site Collection</param> /// <param name="tenantTemplate">The Provisioning Template Hierarchy to apply</param> /// <param name="log">The TraceWriter to log activities</param> public static void ApplyTenantTemplate(String targetSiteUrl, ProvisioningHierarchy tenantTemplate, ILogger log) { ProvisioningTemplateApplyingInformation ptai = new ProvisioningTemplateApplyingInformation(); // We exclude Term Groups because they are not supported in AppOnly ptai.HandlersToProcess = Handlers.All; ptai.HandlersToProcess ^= Handlers.TermGroups; ptai.MessagesDelegate += delegate(string message, ProvisioningMessageType messageType) { log.LogDebug($"{messageType} - {message}"); }; ptai.ProgressDelegate += delegate(string message, int step, int total) { log.LogInformation($"{step:00}/{total:00} - {message}"); }; var tenantUrl = SPOUtilities.GetTenantAdministrationUrl(targetSiteUrl); using (var tenantContext = SPOContextProvider.BuildAppOnlyClientContext(tenantUrl)) { using (var pnpTenantContext = PnPClientContext.ConvertFrom(tenantContext)) { var tenant = new Microsoft.Online.SharePoint.TenantAdministration.Tenant(pnpTenantContext); // Prepare a dictionary to hold the access tokens var accessTokens = new Dictionary <String, String>(); // Get the Microsoft Graph Access Token var clientApplication = ConfidentialClientApplicationBuilder .Create(Environment.GetEnvironmentVariable("ClientId")) .WithTenantId(Environment.GetEnvironmentVariable("Tenant")) .WithClientSecret(Environment.GetEnvironmentVariable("ClientSecret")).Build(); try { string[] graphScopes = new string[] { "https://graph.microsoft.com/.default" }; var authenticationResult = clientApplication.AcquireTokenForClient(graphScopes).ExecuteAsync().GetAwaiter().GetResult(); var graphAccessToken = authenticationResult.AccessToken; accessTokens.Add(new Uri("https://graph.microsoft.com/").Authority, graphAccessToken); } catch (Exception ex) { log.LogError(ex.Message); throw; } // Configure the OAuth Access Tokens for the PnPClientContext, too pnpTenantContext.PropertyBag["AccessTokens"] = accessTokens; ptai.AccessTokens = accessTokens; // Define a PnPProvisioningContext scope to share the security context across calls using (var pnpProvisioningContext = new PnPProvisioningContext(async(r, s) => { if (accessTokens.Any(i => i.Key.Equals(r, StringComparison.InvariantCultureIgnoreCase) || r.ToLower().Contains(i.Key))) { // In this scenario we just use the dictionary of access tokens // in fact the overall operation for sure will take less than 1 hour var item = accessTokens.FirstOrDefault(i => i.Key.Equals(r, StringComparison.InvariantCultureIgnoreCase) || r.ToLower().Contains(i.Key)); return(await Task.FromResult(item.Value)); } else { return(null); } })) { log.LogInformation($"Hierarchy Provisioning Started: {DateTime.Now:hh.mm.ss}"); tenant.ApplyProvisionHierarchy(tenantTemplate, null, ptai); log.LogInformation($"Hierarchy Provisioning Completed: {DateTime.Now:hh.mm.ss}"); } } } }