private static void CreateSiteCollectionFromTemplate(ClientContext cc, string tenantUrl, string newSiteUrl, string userName) { Tenant tenant = new Tenant(cc); SiteCreationProperties newsiteProp = new SiteCreationProperties(); newsiteProp.Lcid = 1033; newsiteProp.Owner = userName; newsiteProp.Title = "New Site"; newsiteProp.Url = newSiteUrl; newsiteProp.StorageMaximumLevel = 100; //MB newsiteProp.UserCodeMaximumLevel = 10; SpoOperation spoO = tenant.CreateSite(newsiteProp); cc.Load(spoO, i => i.IsComplete); cc.ExecuteQuery(); while (!spoO.IsComplete) { //Wait for 30 seconds and then try again System.Threading.Thread.Sleep(10000); spoO.RefreshLoad(); cc.ExecuteQuery(); Console.WriteLine("Site creation status: " + (spoO.IsComplete ? "completed" : "waiting")); } Console.WriteLine("SiteCollection Created."); }
public async Task CreateTenant(CreateTenantInput input) { //Create tenant var tenant = new Tenant(input.TenancyName, input.Name); var defaultEdition = await _editionManager.FindByNameAsync(EditionManager.DefaultEditionName); if (defaultEdition != null) { tenant.EditionId = defaultEdition.Id; } CheckErrors(await TenantManager.CreateAsync(tenant)); await CurrentUnitOfWork.SaveChangesAsync(); //To get new tenant's id. //We are working entities of new tenant, so changing tenant filter using (CurrentUnitOfWork.SetFilterParameter(AbpDataFilters.MayHaveTenant, AbpDataFilters.Parameters.TenantId, tenant.Id)) { //Create static roles for new tenant CheckErrors(await _roleManager.CreateStaticRoles(tenant.Id)); await CurrentUnitOfWork.SaveChangesAsync(); //To get static role ids //grant all permissions to admin role var adminRole = _roleManager.Roles.Single(r => r.Name == StaticRoleNames.Tenants.Admin); await _roleManager.GrantAllPermissionsAsync(adminRole); //Create admin user for the tenant var adminUser = User.CreateTenantAdminUser(tenant.Id, input.AdminEmailAddress, User.DefaultPassword); CheckErrors(await UserManager.CreateAsync(adminUser)); await CurrentUnitOfWork.SaveChangesAsync(); //To get admin user's id //Assign admin user to role! CheckErrors(await UserManager.AddToRoleAsync(adminUser.Id, adminRole.Name)); await CurrentUnitOfWork.SaveChangesAsync(); } }
public static void AddAdministratorsTenant(this Web web, IEnumerable<UserEntity> adminLogins, Uri siteUrl, bool addToOwnersGroup = false) { Tenant tenant = new Tenant(web.Context); tenant.AddAdministrators(adminLogins, siteUrl, addToOwnersGroup); }
public OperationResult Get() { var siteUrl = Request.GetQueryNameValuePairs().FirstOrDefault(p => p.Key == "siteUrl").Value; var ret = new OperationResult() { IsSuccess = true }; UsingTenantContext(context => { try { var tenant = new Tenant(context); tenant.SetSiteLockState(siteUrl, SiteLockState.Unlock, wait: true); } catch (Exception e) { ret.IsSuccess = false; ret.Message = e.Message; return; } }); if (ret.IsSuccess) { DbRepository.UsingContext(dbContext => { var site = dbContext.GetSite(siteUrl); if (site != null) site.ComplianceState.IsLocked = false; dbContext.SaveChanges(); }); } return ret; }
public string ProcessSiteCreationRequest(ClientContext ctx, SiteCollectionRequest siteRequest) { // Resolve full URL var webFullUrl = String.Format("https://{0}.sharepoint.com/{1}/{2}", siteRequest.TenantName, siteRequest.ManagedPath, siteRequest.Url); // Resolve the actual SP template to use string siteTemplate = SolveActualTemplate(siteRequest); Tenant tenant = new Tenant(ctx); if (tenant.SiteExists(webFullUrl)) { // Abort... can't proceed, URL taken. throw new InvalidDataException(string.Format("site already existed with same URL as {0}. Process aborted.", webFullUrl)); } else { // Create new site collection with storage limits and settings from the form tenant.CreateSiteCollection(webFullUrl, siteRequest.Title, siteRequest.Owner, siteTemplate, (int)siteRequest.StorageMaximumLevel, (int)(siteRequest.StorageMaximumLevel * 0.75), siteRequest.TimeZoneId, 0, 0, siteRequest.Lcid); return webFullUrl; } }
public List<SiteProperties> Execute(ClientContext tenantAdminCtx) { Logger.Verbose($"About to execute {nameof(GetTenantSiteCollections)}"); var tenant = new Tenant(tenantAdminCtx); tenantAdminCtx.Load(tenant); tenantAdminCtx.ExecuteQuery(); return GetTenantSiteCollectionsRecursive(tenant, new List<SiteProperties>(), 0); }
public void CreateDeleteCreateSiteCollectionTest() { using (var tenantContext = TestCommon.CreateTenantClientContext()) { var tenant = new Tenant(tenantContext); //Create site collection test string siteToCreateUrl = CreateTestSiteCollection(tenant, sitecollectionName); var siteExists = tenant.SiteExists(siteToCreateUrl); Assert.IsTrue(siteExists, "Site collection creation failed"); //Delete site collection test: move to recycle bin tenant.DeleteSiteCollection(siteToCreateUrl, true); bool recycled = tenant.CheckIfSiteExists(siteToCreateUrl, "Recycled"); Assert.IsTrue(recycled, "Site collection recycling failed"); //Remove from recycle bin tenant.DeleteSiteCollectionFromRecycleBin(siteToCreateUrl, true); var siteExists2 = tenant.SiteExists(siteToCreateUrl); Assert.IsFalse(siteExists2, "Site collection deletion from recycle bin failed"); //Create a site collection using the same url as the previously deleted site collection siteToCreateUrl = CreateTestSiteCollection(tenant, sitecollectionName); siteExists = tenant.SiteExists(siteToCreateUrl); Assert.IsTrue(siteExists, "Second site collection creation failed"); } }
public void RunGetsSurveyAnswersForIdFromStore() { var mockSurveyStore = new Mock<ISurveyStore>(); var mockSurveyAnswerStore = new Mock<ISurveyAnswerStore>(); var mockTenantStore = new Mock<ITenantStore>(); var mockSurveySqlStore = new Mock<ISurveySqlStore>(); var command = new TransferSurveysToSqlAzureCommand(mockSurveyAnswerStore.Object, mockSurveyStore.Object, mockTenantStore.Object, mockSurveySqlStore.Object); var message = new SurveyTransferMessage { Tenant = "tenant", SlugName = "slugName" }; var survey = new Survey("slugName") { Tenant = "tenant", }; survey.Questions.Add(new Question { Text = "What is your favorite food?", PossibleAnswers = "Coffee\nPizza\nSalad", Type = QuestionType.MultipleChoice }); mockSurveyStore.Setup(r => r.GetSurveyByTenantAndSlugName("tenant", "slugName", true)).Returns(survey); mockSurveyStore.Setup(r => r.GetSurveysByTenant("tenant")).Returns(new List<Survey> { survey }); mockSurveyAnswerStore.Setup(r => r.GetSurveyAnswerIds("tenant", "slugName")).Returns(new List<string> { "id" }); mockSurveyAnswerStore.Setup(r => r.GetSurveyAnswer("tenant", "slugName", "id")).Returns(new SurveyAnswer()); var tenant = new Tenant { SqlAzureConnectionString = "connectionString" }; mockTenantStore.Setup(r => r.GetTenant("tenant")).Returns(tenant); command.Run(message); mockSurveyAnswerStore.Verify(r => r.GetSurveyAnswer(message.Tenant, "slugName", "id")); }
protected void Button1_Click(object sender, EventArgs e) { Uri tenantAdministrationUrl = new Uri("https://dotnetrocks-admin.sharepoint.com/"); string accessToken = TokenHelper.GetAppOnlyAccessToken( TokenHelper.SharePointPrincipal, tenantAdministrationUrl.Authority, TokenHelper.GetRealmFromTargetUrl(tenantAdministrationUrl)).AccessToken; var newSite = new SiteCreationProperties() { Url = "https://dotnetrocks.sharepoint.com/sites/" + SiteName.Text, Owner = SiteOwner.Text, Template = "STS#0", // Team Site Title = "App Provisioned Site - " + SiteName.Text, StorageMaximumLevel = 1000, StorageWarningLevel = 500, TimeZoneId = 7, UserCodeMaximumLevel = 7, UserCodeWarningLevel = 1 }; using (var clientContext = TokenHelper.GetClientContextWithAccessToken(tenantAdministrationUrl.ToString(), accessToken)) { var tenant = new Tenant(clientContext); var spoOperation = tenant.CreateSite(newSite); clientContext.Load(spoOperation); clientContext.ExecuteQuery(); } }
internal static string CreateTestSiteCollection(Tenant tenant, string sitecollectionName) { try { string devSiteUrl = ConfigurationManager.AppSettings["SPODevSiteUrl"]; string siteToCreateUrl = GetTestSiteCollectionName(devSiteUrl, sitecollectionName); string siteOwnerLogin = ConfigurationManager.AppSettings["SPOUserName"]; if (TestCommon.AppOnlyTesting()) { using (var clientContext = TestCommon.CreateClientContext()) { List<UserEntity> admins = clientContext.Web.GetAdministrators(); siteOwnerLogin = admins[0].LoginName.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries)[2]; } } SiteEntity siteToCreate = new SiteEntity() { Url = siteToCreateUrl, Template = "STS#0", Title = "Test", Description = "Test site collection", SiteOwnerLogin = siteOwnerLogin, }; tenant.CreateSiteCollection(siteToCreate, false, true); return siteToCreateUrl; } catch (Exception ex) { Console.WriteLine(ex.ToString()); throw; } }
protected void btnUpdateSiteCollectionStatus_Click(object sender, EventArgs e) { string siteUrl = sitecollections.SelectedValue; using (var ctx = GetAdminContext()) { // get site collections. Tenant tenant = new Tenant(ctx); SiteProperties siteProp = tenant.GetSitePropertiesByUrl(siteUrl, true); ctx.Load(siteProp); ctx.ExecuteQuery(); switch (rblSharingOptions.SelectedValue) { case "Disabled": siteProp.SharingCapability = SharingCapabilities.Disabled; lblStatus.Text = "External sharing is for authenticated and guest users."; break; case "ExternalUserAndGuestSharing": siteProp.SharingCapability = SharingCapabilities.ExternalUserAndGuestSharing; lblStatus.Text = "External sharing is for authenticated and guest users."; break; case "ExternalUserSharingOnly": siteProp.SharingCapability = SharingCapabilities.ExternalUserSharingOnly; lblStatus.Text = "External sharing is for authenticated and guest users."; break; } // Update based on applied setting siteProp.Update(); ctx.ExecuteQuery(); lblStatus.Text = string.Format("Sharing status updated for site collection at URL: {0}", siteUrl); } }
static void Main(string[] args) { //gather settings from the host process config file string tenantName = ConfigurationManager.AppSettings["TenantName"]; string tenantUpnDomain = ConfigurationManager.AppSettings["TenantUpnDomain"]; Uri tenantAdminUri = new Uri(string.Format("https://{0}-admin.sharepoint.com", tenantName)); //get the ream and app-only access token string adminRealm = TokenHelper.GetRealmFromTargetUrl(tenantAdminUri); var adminToken = TokenHelper.GetAppOnlyAccessToken (TokenHelper.SharePointPrincipal, tenantAdminUri.Authority, adminRealm).AccessToken; //we use the app-only access token to authenticate without the interaction of the user using (ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(tenantAdminUri.ToString(), adminToken)) { //load the tenant object var tenant = new Tenant(clientContext); clientContext.Load(tenant); clientContext.ExecuteQuery(); //call the extension method to get all site collections IList<SiteEntity> siteCollections = tenant.GetSiteCollections(); //at this stage you could build aby report, like an Excel file with OpenXML //in this demo we generate a simple email EmailProperties emailProperties = GenerateEmailReport(siteCollections); //use the OffideDev PnP utilities to send out the email Utility.SendEmail(clientContext, emailProperties); clientContext.ExecuteQuery(); } }
protected void btnCheckUrl_Click(object sender, EventArgs e) { User currUser = ResolveCurrentUser(); //get the base tenant admin urls var tenantStr = Page.Request["SPHostUrl"].ToLower().Replace("-my", "").Substring(8); tenantStr = tenantStr.Substring(0, tenantStr.IndexOf(".")); var spContext = SharePointContextProvider.Current.GetSharePointContext(Context); // Let's resolve the admin URL and wanted new site URL var webUrl = String.Format("https://{0}.sharepoint.com/{1}/{2}", tenantStr, "sites", txtUrl.Text); var tenantAdminUri = new Uri(String.Format("https://{0}-admin.sharepoint.com", tenantStr)); // Creating new app only context for the operation string accessToken = TokenHelper.GetAppOnlyAccessToken( TokenHelper.SharePointPrincipal, tenantAdminUri.Authority, TokenHelper.GetRealmFromTargetUrl(tenantAdminUri)).AccessToken; using (var ctx = TokenHelper.GetClientContextWithAccessToken(tenantAdminUri.ToString(), accessToken)) { Tenant tenant = new Tenant(ctx); if (tenant.SiteExists(webUrl)) { lblStatus1.Text = string.Format("Site already existed. Used URL - {0}", webUrl); } else { lblStatus1.Text = string.Format("Site with given URL does not exist. Used URL - {0}", webUrl); } } }
/// <summary> /// Returns the next site collection number /// </summary> /// <param name="siteDirectoryUrl">Url to the site directory site</param> /// <returns>The next site collection Url</returns> public string GetNextSiteCollectionUrlTenant(ClientContext cc, Web web, ClientContext ccSiteDirectory, Web webSiteDirectory, string siteDirectoryUrl, string siteDirectoryListName, string baseSiteUrl) { int lastNumber = GetLastSiteCollectionNumber(ccSiteDirectory, webSiteDirectory, siteDirectoryUrl, siteDirectoryListName); lastNumber++; string nextSiteName = DateTime.Now.ToString("yyyy") + String.Format("{0:0000}", lastNumber); string nextUrl = String.Format("{0}{1}", baseSiteUrl, nextSiteName); bool validUrl = false; Tenant tenant = new Tenant(web.Context); while (!validUrl) { if (!tenant.SiteExists(nextUrl)) { validUrl = true; } else { lastNumber++; nextSiteName = DateTime.Now.ToString("yyyy") + String.Format("{0:0000}", lastNumber); nextUrl = String.Format("{0}{1}", baseSiteUrl, nextSiteName); } } return nextUrl; }
static void Main(string[] args) { string SHAREPOINT_PID = "00000003-0000-0ff1-ce00-000000000000"; //This is hard-coded for SharePoint Online (ie - all tenants) //The app must have tenant-level permissions and can be installed on any site in the tenancy. You must use the tenant //admin site url to get client context. var sharePointUrl = new Uri("https://<Office 365 domain>-admin.sharepoint.com"); string sharePointRealm = TokenHelper.GetRealmFromTargetUrl(sharePointUrl); var token = TokenHelper.GetAppOnlyAccessToken(SHAREPOINT_PID, sharePointUrl.Authority, sharePointRealm).AccessToken; //read the Sites.xml file and then release the file so we can save over it later string path = @"C:\<path>\Sites.xml"; XDocument doc; using (var fileStream = System.IO.File.OpenRead(path)) { doc = XDocument.Load(fileStream); } //get all the requested sites from the Sites.xml file and loop through each for processing var sites = doc.Root.Elements("site"); foreach (var site in sites) { using (var clientContext = TokenHelper.GetClientContextWithAccessToken(sharePointUrl.ToString(), token)) { clientContext.Load(clientContext.Web.Lists); clientContext.ExecuteQuery(); var siteUrl = site.Attribute("url").Value; var tenant = new Tenant(clientContext); var newSite = new SiteCreationProperties() { Url = siteUrl, Owner = "<admin user>@<Office 365 domain>.onmicrosoft.com", Template = "STS#0", Title = "Batch provisioning test site", //StorageMaximumLevel = 100, //StorageWarningLevel = 300, TimeZoneId = 7, UserCodeMaximumLevel = 7, UserCodeWarningLevel = 1, }; var spoOperation = tenant.CreateSite(newSite); clientContext.Load(spoOperation); clientContext.ExecuteQuery(); while (!spoOperation.IsComplete) { System.Threading.Thread.Sleep(2000); clientContext.Load(spoOperation); clientContext.ExecuteQuery(); } } } }
public static Guid CreateSiteCollectionTenant(this Web web, string url, string title, string siteOwnerLogin, string template, int storageMaximumLevel, int storageWarningLevel, int timeZoneId, int userCodeMaximumLevel, int userCodeWarningLevel, uint lcid, bool removeFromRecycleBin = false, bool wait = true) { Tenant tenant = new Tenant(web.Context); return tenant.AddSiteCollection(url, title, siteOwnerLogin, template, storageMaximumLevel, storageWarningLevel, timeZoneId, userCodeMaximumLevel, userCodeWarningLevel, lcid, removeFromRecycleBin, wait); }
public static void SetNoAccessRedirectUrl(string host) { UsingTenantContext(context => { var tenant = new Tenant(context); tenant.NoAccessRedirectUrl = string.Format("{0}/{1}", host, "App/index.html#/unlock/"); context.ExecuteQuery(); }); }
private async Task BuildForInternalAsync(Tenant tenant) { //Create Organization Units var organizationUnits = new List<OrganizationUnit>(); var producing = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Producing"); var researchAndDevelopment = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Research & Development", producing); var ivrProducts = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "IVR Related Products", researchAndDevelopment); var voiceTech = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Voice Technologies", researchAndDevelopment); var inhouseProjects = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Inhouse Projects", researchAndDevelopment); var qualityManagement = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Quality Management", producing); var testing = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Testing", producing); var selling = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Selling"); var marketing = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Marketing", selling); var sales = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Sales", selling); var custRelations = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Customer Relations", selling); var supporting = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Supporting"); var buying = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Buying", supporting); var humanResources = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Human Resources", supporting); //Create users var users = _randomUserGenerator.GetRandomUsers(RandomHelper.GetRandom(12, 26), tenant.Id); foreach (var user in users) { //Create the user await _userManager.CreateAsync(user); await CurrentUnitOfWork.SaveChangesAsync(); //Add to roles _userManager.AddToRole(user.Id, StaticRoleNames.Tenants.User); //Add to OUs var randomOus = RandomHelper.GenerateRandomizedList(organizationUnits).Take(RandomHelper.GetRandom(0, 3)); foreach (var ou in randomOus) { await _userManager.AddToOrganizationUnitAsync(user, ou); } //Set profile picture if (RandomHelper.GetRandom(100) < 70) //A user will have a profile picture in 70% probability. { await SetRandomProfilePictureAsync(user); } } //Set a picture to admin! var admin = _userManager.FindByName(User.AdminUserName); await SetRandomProfilePictureAsync(admin); }
/// <summary> /// With on-premises builds default groups are not created during site provisioning /// so we have to create them. /// </summary> /// <param name="properties"></param> public virtual void HandleDefaultGroups(SiteInformation properties) { string _ownerGroupDisplayName =string.Format(PCResources.Site_Web_OwnerGroup_Title, properties.Title); string _memberGroupDisplayName = string.Format(PCResources.Site_Web_MemberGroup_Title, properties.Title); string _vistorGroupDisplayName = string.Format(PCResources.Site_Web_VisitorGroup_Title, properties.Title); UsingContext(ctx => { Tenant tenant = new Tenant(ctx); var site = tenant.GetSiteByUrl(properties.Url); var web = site.RootWeb; ctx.Load(web.AssociatedOwnerGroup); ctx.Load(web.AssociatedMemberGroup); ctx.Load(web.AssociatedVisitorGroup); ctx.ExecuteQuery(); Group _ownerGroup; Group _memberGroup; Group _visitorGroup; if (web.AssociatedOwnerGroup.ServerObjectIsNull == true) { _ownerGroup = web.AddGroup(_ownerGroupDisplayName, PCResources.Site_Web_OwnerGroup_Description, true, false); } else { _ownerGroup = web.AssociatedOwnerGroup; } if (web.AssociatedMemberGroup.ServerObjectIsNull == true) { _memberGroup = web.AddGroup(_memberGroupDisplayName, PCResources.Site_Web_MemberGroup_Description, false, false); } else { _memberGroup = web.AssociatedMemberGroup; } if (web.AssociatedVisitorGroup.ServerObjectIsNull == true) { _visitorGroup = web.AddGroup(_vistorGroupDisplayName, PCResources.Site_Web_VisitorGroup_Description, false, false ); } else { _visitorGroup = web.AssociatedVisitorGroup; } web.AssociateDefaultGroups(_ownerGroup, _memberGroup, _visitorGroup); ctx.ExecuteQuery(); Log.Info("Provisioning.Common.OnPremSiteProvisioningService.HandleDefaultGroups", PCResources.Site_Web_DefaultGroups_Created, properties.Url); using (var newSiteCtx = ctx.Clone(properties.Url)) { newSiteCtx.Web.AddPermissionLevelToGroup(_ownerGroupDisplayName, RoleType.Administrator); newSiteCtx.Web.AddPermissionLevelToGroup(_memberGroupDisplayName, RoleType.Editor); newSiteCtx.Web.AddPermissionLevelToGroup(_vistorGroupDisplayName, RoleType.Reader); newSiteCtx.ExecuteQuery(); Log.Info("Provisioning.Common.OnPremSiteProvisioningService.HandleDefaultGroups", PCResources.Site_Web_Groups_Security_Permissions_Set, _ownerGroupDisplayName, _memberGroupDisplayName, _vistorGroupDisplayName); } }); }
public override void CreateSiteCollection(SiteInformation siteRequest, Template template) { Log.Info("Provisioning.Common.Office365SiteProvisioningService.CreateSiteCollection", PCResources.SiteCreation_Creation_Starting, siteRequest.Url); UsingContext(ctx => { try { Stopwatch _timespan = Stopwatch.StartNew(); Tenant _tenant = new Tenant(ctx); var _newsite = new SiteCreationProperties(); _newsite.Title = siteRequest.Title; _newsite.Url = siteRequest.Url; _newsite.Owner = siteRequest.SiteOwner.Name; _newsite.Template = template.RootTemplate; _newsite.Lcid = siteRequest.Lcid; _newsite.TimeZoneId = siteRequest.TimeZoneId; _newsite.StorageMaximumLevel = template.StorageMaximumLevel; _newsite.StorageWarningLevel = template.StorageWarningLevel; _newsite.UserCodeMaximumLevel = template.UserCodeMaximumLevel; _newsite.UserCodeMaximumLevel = template.UserCodeWarningLevel; SpoOperation op = _tenant.CreateSite(_newsite); ctx.Load(_tenant); ctx.Load(op, i => i.IsComplete); ctx.ExecuteQuery(); while (!op.IsComplete) { //wait 30seconds and try again System.Threading.Thread.Sleep(30000); op.RefreshLoad(); ctx.ExecuteQuery(); } var _site = _tenant.GetSiteByUrl(siteRequest.Url); var _web = _site.RootWeb; _web.Description = siteRequest.Description; _web.Update(); ctx.Load(_web); ctx.ExecuteQuery(); _timespan.Stop(); Log.TraceApi("SharePoint", "Office365SiteProvisioningService.CreateSiteCollection", _timespan.Elapsed, "SiteUrl={0}", siteRequest.Url); } catch (Exception ex) { Log.Error("Provisioning.Common.Office365SiteProvisioningService.CreateSiteCollection", PCResources.SiteCreation_Creation_Failure, siteRequest.Url, ex.Message, ex); throw; } Log.Info("Provisioning.Common.Office365SiteProvisioningService.CreateSiteCollection", PCResources.SiteCreation_Creation_Successful, siteRequest.Url); }); }
public static Guid AddSiteCollectionTenant(this Web web, SiteEntity properties) { Tenant tenant = new Tenant(web.Context); SiteCreationProperties newsite = new SiteCreationProperties(); newsite.Url = properties.Url; newsite.Owner = properties.SiteOwnerLogin; newsite.Template = properties.Template; newsite.Title = properties.Title; newsite.StorageMaximumLevel = properties.StorageMaximumLevel; newsite.StorageWarningLevel = properties.StorageWarningLevel; newsite.TimeZoneId = properties.TimeZoneId; newsite.UserCodeMaximumLevel = properties.UserCodeMaximumLevel; newsite.UserCodeWarningLevel = properties.UserCodeWarningLevel; newsite.Lcid = properties.Lcid; try { SpoOperation op = tenant.CreateSite(newsite); web.Context.Load(tenant); web.Context.Load(op, i => i.IsComplete, i => i.PollingInterval); web.Context.ExecuteQuery(); //check if site creation operation is complete while (!op.IsComplete) { System.Threading.Thread.Sleep(op.PollingInterval); op.RefreshLoad(); if (!op.IsComplete) { try { web.Context.ExecuteQuery(); } catch (WebException webEx) { // Context connection gets closed after action completed. // Calling ExecuteQuery again returns an error which can be ignored LoggingUtility.LogWarning(MSG_CONTEXT_CLOSED, webEx, EventCategory.Site); } } } } catch(Exception ex) { // Eat the siteSubscription exception to make the same code work for MT as on-prem april 2014 CU+ if (ex.Message.IndexOf("Parameter name: siteSubscription") == -1) { throw ex; } } // Get site guid and return var siteGuid = web.GetSiteGuidByUrlTenant(new Uri(properties.Url)); return siteGuid; }
public UserOrganizationUnit_Tests() { _defaultTenant = GetDefaultTenant(); _defaultTenantAdmin = GetDefaultTenantAdmin(); AbpSession.TenantId = _defaultTenant.Id; AbpSession.UserId = _defaultTenantAdmin.Id; _userManager = Resolve<UserManager>(); }
public void EnableExternalSharing(Tenant tenant, Site site) { ClientContext context = (ClientContext)site.Context; tenant.SetSiteProperties(site.Url, sharingCapability: SharingCapabilities.ExternalUserSharingOnly); SiteProperties siteProps = tenant.GetSitePropertiesByUrl(site.Url, false); context.Load(tenant); context.Load(siteProps); context.ExecuteQuery(); }
public Task<ITenant> Resolve(string tenantIdentifier) { var tenant = new Tenant { Name = "Tenant1", RequestIdentifiers = new[] { "localhost", "dev.local" } }; return Task.FromResult<ITenant>(tenant); }
public async Task<IActionResult> Create(Tenant tenant) { if (ModelState.IsValid) { await _dataAccess.AddTenant(tenant); return RedirectToAction("Index"); } return View(tenant); }
public void ProcessOneWayEvent(SPRemoteEventProperties properties) { string SHAREPOINT_PID = "00000003-0000-0ff1-ce00-000000000000"; //This is hard-coded for SharePoint Online (ie - all tenants) //The app must have tenant-level permissions and can be installed on any site in the tenancy. You must use the tenant //admin site url to get client context. Uri sharePointUrl = new Uri("https://<your-domain>-admin.sharepoint.com"); string myRealm = TokenHelper.GetRealmFromTargetUrl(sharePointUrl); try { string accessToken = TokenHelper.GetAppOnlyAccessToken(SHAREPOINT_PID, sharePointUrl.Authority, myRealm).AccessToken; using (ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(sharePointUrl.ToString(), accessToken)) { if (clientContext != null) { var requestTitle = properties.ItemEventProperties.AfterProperties["Title"]; var tenant = new Tenant(clientContext); var newSite = new SiteCreationProperties() { Url = "https://<your domain>.sharepoint.com/sites/" + requestTitle, Owner = "administrator@<your domain>.onmicrosoft.com", Template = "STS#0", Title = "Workflow provisioning test site two", StorageMaximumLevel = 1000, StorageWarningLevel = 500, TimeZoneId = 7, UserCodeMaximumLevel = 7, UserCodeWarningLevel = 1, }; var spoOperation = tenant.CreateSite(newSite); clientContext.Load(spoOperation); clientContext.ExecuteQuery(); while (!spoOperation.IsComplete) { System.Threading.Thread.Sleep(2000); clientContext.Load(spoOperation); clientContext.ExecuteQuery(); } } } } catch (Exception ex) { var exception = ex; } }
public static string CreateSiteCollection(ClientContext ctx, string hostWebUrl, string template, string title, string description, string userEmail) { //get the base tenant admin urls var tenantStr = hostWebUrl.ToLower().Replace("-my", "").Substring(8); tenantStr = tenantStr.Substring(0, tenantStr.IndexOf(".")); //create site collection using the Tenant object var webUrl = String.Format("https://{0}.sharepoint.com/{1}/{2}", tenantStr, "sites", title); var tenantAdminUri = new Uri(String.Format("https://{0}-admin.sharepoint.com", tenantStr)); string realm = TokenHelper.GetRealmFromTargetUrl(tenantAdminUri); var token = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, tenantAdminUri.Authority, realm).AccessToken; using (var adminContext = TokenHelper.GetClientContextWithAccessToken(tenantAdminUri.ToString(), token)) { var tenant = new Tenant(adminContext); var properties = new SiteCreationProperties() { Url = webUrl, Owner = userEmail, Title = title, Template = template, StorageMaximumLevel = 100, UserCodeMaximumLevel = 100 }; //start the SPO operation to create the site SpoOperation op = tenant.CreateSite(properties); adminContext.Load(tenant); adminContext.Load(op, i => i.IsComplete); adminContext.ExecuteQuery(); //check if site creation operation is complete while (!op.IsComplete) { //wait 30seconds and try again System.Threading.Thread.Sleep(30000); op.RefreshLoad(); adminContext.ExecuteQuery(); } } //get the new site collection var siteUri = new Uri(webUrl); token = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, siteUri.Authority, realm).AccessToken; using (var newWebContext = TokenHelper.GetClientContextWithAccessToken(siteUri.ToString(), token)) { var newWeb = newWebContext.Web; newWebContext.Load(newWeb); newWebContext.ExecuteQuery(); new LabHelper().SetThemeBasedOnName(newWebContext, newWeb, newWeb, "Orange"); // All done, let's return the newly created site return newWeb.Url; } }
public async Task CreateTenant(CreateTenantInput input) { //create tenant var tenant = new Tenant(input.TenancyName, input.Name) { IsActive = input.IsActive, EditionId = input.EditionId }; CheckErrors(await TenantManager.CreateAsync(tenant)); await CurrentUnitOfWork.SaveChangesAsync(); //We are working entities of new tenant, so changing tenant filter CurrentUnitOfWork.SetFilterParameter(AbpDataFilters.MayHaveTenant, AbpDataFilters.Parameters.TenantId, tenant.Id); //Create static roles for new tenant CheckErrors(await _roleManager.CreateStaticRoles(tenant.Id)); await CurrentUnitOfWork.SaveChangesAsync(); //To get static role ids //grant all permissions to admin role var adminRole = _roleManager.Roles.Single(r => r.Name == StaticRoleNames.Tenants.Admin); await _roleManager.GrantAllPermissionsAsync(adminRole); //User role should be default var userRole = _roleManager.Roles.Single(r => r.Name == StaticRoleNames.Tenants.User); userRole.IsDefault = true; CheckErrors(await _roleManager.UpdateAsync(userRole)); //Create admin user for the tenant if (input.AdminPassword.IsNullOrEmpty()) { input.AdminPassword = User.CreateRandomPassword(); } var adminUser = User.CreateTenantAdminUser(tenant.Id, input.AdminEmailAddress, input.AdminPassword); adminUser.ShouldChangePasswordOnNextLogin = input.ShouldChangePasswordOnNextLogin; adminUser.IsActive = input.IsActive; CheckErrors(await UserManager.CreateAsync(adminUser)); await CurrentUnitOfWork.SaveChangesAsync(); //To get admin user's id //Assign admin user to role! CheckErrors(await UserManager.AddToRoleAsync(adminUser.Id, adminRole.Name)); if (input.SendActivationEmail) { adminUser.SetNewEmailConfirmationCode(); await _userEmailer.SendEmailActivationLinkAsync(adminUser, input.AdminPassword); } await CurrentUnitOfWork.SaveChangesAsync(); //Changing back to original tenantId value. CurrentUnitOfWork.SetFilterParameter(AbpDataFilters.MayHaveTenant, AbpDataFilters.Parameters.TenantId, AbpSession.TenantId); }
public void GetTenantReturnsTenantFromBlobStorage() { var mockTenantBlobContainer = new Mock<IAzureBlobContainer<Tenant>>(); var store = new TenantStore(mockTenantBlobContainer.Object, null); var tenant = new Tenant(); mockTenantBlobContainer.Setup(c => c.Get("tenant")).Returns(tenant); var actualTenant = store.GetTenant("tenant"); Assert.AreSame(tenant, actualTenant); }
public void GetSiteCollectionsTest() { using (var tenantContext = TestCommon.CreateTenantClientContext()) { var tenant = new Tenant(tenantContext); var siteCols = tenant.GetSiteCollections(); Assert.IsTrue(siteCols.Any()); } }
public DeletePortalTask(Tenant tenant, string configPath) : base(tenant, configPath) { }
/// <summary> /// Initializes a new instance of the <see cref="LoggerAdapter{T}"/> class. /// </summary> /// <param name="loggerFactory">The logger factory.</param> /// <param name="tenant">The tenant.</param> public LoggerAdapter(ILoggerFactory loggerFactory, Tenant tenant) { _logger = loggerFactory.CreateLogger <T>(); _tenant = tenant; }
private void SetLogoUrlForTenant(string appPath, Tenant tenant) { ViewBag.TenantCustomLogoUrl = tenant != null && tenant.LogoId.HasValue ? appPath + "TenantCustomization/GetLogo" : appPath + "Common/Images/app-logo-on-light.png"; }
public abstract bool WillExtract(Tenant tenant, Model.ProvisioningHierarchy hierarchy, string sequenceId, ExtractConfiguration configuration);
private void CreateDefaultTenantAndUsers() { //Default tenant var defaultTenant = _context.Tenants.FirstOrDefault(t => t.TenancyName == Tenant.DefaultTenantName); if (defaultTenant == null) { defaultTenant = new Tenant(Tenant.DefaultTenantName, Tenant.DefaultTenantName); var defaultEdition = _context.Editions.FirstOrDefault(e => e.Name == EditionManager.DefaultEditionName); if (defaultEdition != null) { defaultTenant.EditionId = defaultEdition.Id; } defaultTenant = _context.Tenants.Add(defaultTenant); _context.SaveChanges(); } //Admin role for 'Default' tenant var adminRoleForDefaultTenant = _context.Roles.FirstOrDefault(r => r.TenantId == defaultTenant.Id && r.Name == StaticRoleNames.Tenants.Admin); if (adminRoleForDefaultTenant == null) { adminRoleForDefaultTenant = _context.Roles.Add(new Role(defaultTenant.Id, StaticRoleNames.Tenants.Admin, StaticRoleNames.Tenants.Admin) { IsStatic = true }); _context.SaveChanges(); } //User role for 'Default' tenant var userRoleForDefaultTenant = _context.Roles.FirstOrDefault(r => r.TenantId == defaultTenant.Id && r.Name == StaticRoleNames.Tenants.User); if (userRoleForDefaultTenant == null) { _context.Roles.Add(new Role(defaultTenant.Id, StaticRoleNames.Tenants.User, StaticRoleNames.Tenants.User) { IsStatic = true, IsDefault = true }); _context.SaveChanges(); } //admin user for 'Default' tenant var adminUserForDefaultTenant = _context.Users.FirstOrDefault(u => u.TenantId == defaultTenant.Id && u.UserName == User.AdminUserName); if (adminUserForDefaultTenant == null) { adminUserForDefaultTenant = User.CreateTenantAdminUser(defaultTenant.Id, "*****@*****.**", "123qwe"); adminUserForDefaultTenant.IsEmailConfirmed = true; adminUserForDefaultTenant.ShouldChangePasswordOnNextLogin = true; adminUserForDefaultTenant.IsActive = true; _context.Users.Add(adminUserForDefaultTenant); _context.SaveChanges(); //Assign Admin role to admin user _context.UserRoles.Add(new UserRole(adminUserForDefaultTenant.Id, adminRoleForDefaultTenant.Id)); _context.SaveChanges(); //Grant all permissions var permissions = PermissionFinder .GetAllPermissions(new AppAuthorizationProvider()) .Where(p => p.MultiTenancySides.HasFlag(MultiTenancySides.Tenant)) .ToList(); foreach (var permission in permissions) { if (!permission.IsGrantedByDefault) { _context.Permissions.Add( new RolePermissionSetting { Name = permission.Name, IsGranted = true, RoleId = adminRoleForDefaultTenant.Id }); } } _context.SaveChanges(); } }
public TenantContext(Tenant tenant) { Tenant = tenant; }
public abstract TokenParser ProvisionObjects(Tenant tenant, Model.ProvisioningHierarchy hierarchy, string sequenceId, TokenParser parser, ApplyConfiguration configuration);
private async Task BuildForInternalAsync(Tenant tenant) { //Create Organization Units var organizationUnits = new List <OrganizationUnit>(); var producing = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Producing"); var researchAndDevelopment = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Research & Development", producing); var ivrProducts = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "IVR Related Products", researchAndDevelopment); var voiceTech = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Voice Technologies", researchAndDevelopment); var inhouseProjects = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Inhouse Projects", researchAndDevelopment); var qualityManagement = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Quality Management", producing); var testing = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Testing", producing); var selling = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Selling"); var marketing = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Marketing", selling); var sales = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Sales", selling); var custRelations = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Customer Relations", selling); var supporting = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Supporting"); var buying = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Buying", supporting); var humanResources = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Human Resources", supporting); //Create users var users = _randomUserGenerator.GetRandomUsers(RandomHelper.GetRandom(12, 26), tenant.Id); foreach (var user in users) { //Create the user await _userManager.CreateAsync(user); await CurrentUnitOfWork.SaveChangesAsync(); //Add to roles _userManager.AddToRole(user.Id, StaticRoleNames.Tenants.User); //Add to OUs var randomOus = RandomHelper.GenerateRandomizedList(organizationUnits).Take(RandomHelper.GetRandom(0, 3)); foreach (var ou in randomOus) { await _userManager.AddToOrganizationUnitAsync(user, ou); } //Set profile picture if (RandomHelper.GetRandom(100) < 70) //A user will have a profile picture in 70% probability. { await SetRandomProfilePictureAsync(user); } } //Set a picture to admin! var admin = _userManager.FindByName(User.AdminUserName); await SetRandomProfilePictureAsync(admin); //Create Friendships var friends = RandomHelper.GenerateRandomizedList(users).Take(3).ToList(); foreach (var friend in friends) { _friendshipManager.CreateFriendship( new Friendship( admin.ToUserIdentifier(), friend.ToUserIdentifier(), tenant.TenancyName, friend.UserName, friend.ProfilePictureId, FriendshipState.Accepted) ); _friendshipManager.CreateFriendship( new Friendship( friend.ToUserIdentifier(), admin.ToUserIdentifier(), tenant.TenancyName, admin.UserName, admin.ProfilePictureId, FriendshipState.Accepted) ); } //Create chat message var friendWithMessage = RandomHelper.GenerateRandomizedList(friends).First(); _chatMessageRepository.InsertAndGetId( new ChatMessage( friendWithMessage.ToUserIdentifier(), admin.ToUserIdentifier(), ChatSide.Sender, L("Demo_SampleChatMessage"), ChatMessageReadState.Read ) ); _chatMessageRepository.InsertAndGetId( new ChatMessage( admin.ToUserIdentifier(), friendWithMessage.ToUserIdentifier(), ChatSide.Receiver, L("Demo_SampleChatMessage"), ChatMessageReadState.Unread ) ); }
private async Task <OrganizationUnit> CreateAndSaveOrganizationUnit(List <OrganizationUnit> organizationUnits, Tenant tenant, string displayName, OrganizationUnit parent = null) { var organizationUnit = new OrganizationUnit(tenant.Id, displayName, parent == null ? (long?)null : parent.Id); await _organizationUnitManager.CreateAsync(organizationUnit); await CurrentUnitOfWork.SaveChangesAsync(); organizationUnits.Add(organizationUnit); return(organizationUnit); }
/// <summary> /// Sets tenant site Properties /// </summary> /// <param name="tenant">A tenant object pointing to the context of a Tenant Administration site</param> /// <param name="siteFullUrl">full url of site</param> /// <param name="title">site title</param> /// <param name="allowSelfServiceUpgrade">Boolean value to allow serlf service upgrade</param> /// <param name="sharingCapability">SharingCapabilities enumeration value (i.e. Disabled/ExternalUserSharingOnly/ExternalUserAndGuestSharing/ExistingExternalUserSharingOnly)</param> /// <param name="storageMaximumLevel">A limit on all disk space used by the site collection</param> /// <param name="storageWarningLevel">A storage warning level for when administrators of the site collection receive advance notice before available storage is expended.</param> /// <param name="userCodeMaximumLevel">A value that represents the maximum allowed resource usage for the site/</param> /// <param name="userCodeWarningLevel">A value that determines the level of resource usage at which a warning e-mail message is sent</param> /// <param name="noScriptSite">Boolean value which allows to customize the site using scripts</param> /// <param name="wait">Id true this function only returns when the tenant properties are set, if false it will return immediately</param> /// <param name="timeoutFunction">An optional function that will be called while waiting for the tenant properties to be set. If set will override the wait variable. Return true to cancel the wait loop.</param> public static void SetSiteProperties(this Tenant tenant, string siteFullUrl, string title = null, bool?allowSelfServiceUpgrade = null, SharingCapabilities?sharingCapability = null, long?storageMaximumLevel = null, long?storageWarningLevel = null, double?userCodeMaximumLevel = null, double?userCodeWarningLevel = null, bool?noScriptSite = null, bool wait = true, Func <TenantOperationMessage, bool> timeoutFunction = null ) { var siteProps = tenant.GetSitePropertiesByUrl(siteFullUrl, true); tenant.Context.Load(siteProps); tenant.Context.ExecuteQueryRetry(); if (siteProps != null) { if (allowSelfServiceUpgrade != null) { siteProps.AllowSelfServiceUpgrade = allowSelfServiceUpgrade.Value; } if (sharingCapability != null) { siteProps.SharingCapability = sharingCapability.Value; } if (storageMaximumLevel != null) { siteProps.StorageMaximumLevel = storageMaximumLevel.Value; } if (storageWarningLevel != null) { siteProps.StorageWarningLevel = storageWarningLevel.Value; } if (userCodeMaximumLevel != null) { siteProps.UserCodeMaximumLevel = userCodeMaximumLevel.Value; } if (userCodeWarningLevel != null) { siteProps.UserCodeWarningLevel = userCodeWarningLevel.Value; } if (title != null) { siteProps.Title = title; } if (noScriptSite != null) { siteProps.DenyAddAndCustomizePages = (noScriptSite == true ? DenyAddAndCustomizePagesStatus.Enabled : DenyAddAndCustomizePagesStatus.Disabled); } var op = siteProps.Update(); tenant.Context.Load(op, i => i.IsComplete, i => i.PollingInterval); tenant.Context.ExecuteQueryRetry(); if (timeoutFunction != null) { wait = true; } if (wait) { WaitForIsComplete(tenant, op, timeoutFunction, TenantOperationMessage.SettingSiteProperties); } } }
protected override ApiRequest ParseRequestInfo(IDictionary <string, string> groups, Tenant t) { var folder = groups["folder"]; int id; if (!int.TryParse(folder, out id)) { folder = '@' + folder; } return(new ApiRequest(string.Format("files/{0}/upload", folder)) { FilesToPost = new List <RequestFileInfo>() }); }
/// <summary> /// Enables Site Classifications for the target tenant /// </summary> /// <param name="tenant">The target tenant</param> /// <param name="accessToken">The OAuth accessToken for Microsoft Graph with Azure AD</param> /// <param name="classificationsList">The list of classification values</param> /// <param name="defaultClassification">The default classification</param> /// <param name="usageGuidelinesUrl">The URL of a guidance page</param> public static void EnableSiteClassifications(this Tenant tenant, string accessToken, IEnumerable <string> classificationsList, string defaultClassification = "", string usageGuidelinesUrl = "") { SiteClassificationsUtility.EnableSiteClassifications(accessToken, classificationsList, defaultClassification, usageGuidelinesUrl); }
private ProvisioningHierarchy ExtractTemplate(ExtractConfiguration configuration) { configuration.ProgressDelegate = (message, step, total) => { var percentage = Convert.ToInt32((100 / Convert.ToDouble(total)) * Convert.ToDouble(step)); WriteProgress(new ProgressRecord(0, $"Extracting Tenant Template", message) { PercentComplete = percentage }); WriteProgress(new ProgressRecord(1, " ", " ") { RecordType = ProgressRecordType.Completed }); }; configuration.MessagesDelegate = (message, type) => { switch (type) { case ProvisioningMessageType.Warning: { WriteWarning(message); break; } case ProvisioningMessageType.Progress: { var activity = message; if (message.IndexOf("|") > -1) { var messageSplitted = message.Split('|'); if (messageSplitted.Length == 4) { var current = double.Parse(messageSplitted[2]); var total = double.Parse(messageSplitted[3]); subProgressRecord.RecordType = ProgressRecordType.Processing; subProgressRecord.Activity = messageSplitted[0]; subProgressRecord.StatusDescription = messageSplitted[1]; subProgressRecord.PercentComplete = Convert.ToInt32((100 / total) * current); WriteProgress(subProgressRecord); } else { subProgressRecord.Activity = "Processing"; subProgressRecord.RecordType = ProgressRecordType.Processing; subProgressRecord.StatusDescription = activity; subProgressRecord.PercentComplete = 0; WriteProgress(subProgressRecord); } } else { subProgressRecord.Activity = "Processing"; subProgressRecord.RecordType = ProgressRecordType.Processing; subProgressRecord.StatusDescription = activity; subProgressRecord.PercentComplete = 0; WriteProgress(subProgressRecord); } break; } case ProvisioningMessageType.Completed: { WriteProgress(new ProgressRecord(1, message, " ") { RecordType = ProgressRecordType.Completed }); break; } } }; using (var provisioningContext = new PnPProvisioningContext((resource, scope) => { // Get Azure AD Token if (PnPConnection.CurrentConnection != null) { var graphAccessToken = PnPConnection.CurrentConnection.TryGetAccessToken(Enums.TokenAudience.MicrosoftGraph); if (graphAccessToken != null) { // Authenticated using -Graph or using another way to retrieve the accesstoken with Connect-PnPOnline return(Task.FromResult(graphAccessToken)); } } if (PnPConnection.CurrentConnection.PSCredential != null) { // Using normal credentials return(Task.FromResult(TokenHandler.AcquireToken(resource, null))); } else { // No token... return(null); } })) { return(Tenant.GetTenantTemplate(configuration)); } }
/// <summary> /// Deletes a site collection /// </summary> /// <param name="tenant">A tenant object pointing to the context of a Tenant Administration site</param> /// <param name="siteFullUrl">Url of the site collection to delete</param> public static void DeleteSiteCollection(this Tenant tenant, string siteFullUrl) { tenant.RemoveSite(siteFullUrl); tenant.Context.ExecuteQueryRetry(); }
public abstract ProvisioningHierarchy ExtractObjects(Tenant tenant, Model.ProvisioningHierarchy hierarchy, ExtractConfiguration configuration);
public void OnAuthenticate(object sender, AuthenticateEventArgs e) { if (Page.IsValid) { SRPUser user = new SRPUser(); bool auth = SRPUser.Login(uxLogin.UserName, uxLogin.Password, Session.SessionID, Request.UserHostAddress == "::1" ? "127.0.0.1" : Request.UserHostAddress, Request.UserHostName == "::1" ? "localhost" : Request.UserHostName, Request.Browser.Browser + " - v" + Request.Browser.MajorVersion + Request.Browser.MinorVersionString); if (!auth) { uxMessageBox.Visible = true; FailureText.Text = SRPResources.BadUserPass; //Account Inactive // e.Authenticated = false; } else { e.Authenticated = true; } if (e.Authenticated) { // handle remember me if (uxLogin.RememberMeSet == true) { var rememberMe = new HttpCookie("ControlRoomUsername", uxLogin.UserName); rememberMe.Expires = DateTime.Now.AddDays(14); Response.Cookies.Set(rememberMe); } else { var rememberMe = new HttpCookie("ControlRoomUsername", string.Empty); rememberMe.Expires = DateTime.Now.AddDays(-1); Response.Cookies.Set(rememberMe); } // Put User Profile into Session. // Put Security roles into session // = ConfigurationManager.AppSettings["ApplicationName"]; user = SRPUser.FetchByUsername(uxLogin.UserName); Session[SessionData.IsLoggedIn.ToString()] = true; Session[SessionData.UserProfile.ToString()] = user; List <SRPPermission> perms = user.EffectiveUserPermissions(); //Session[SessionData.PermissionList.ToString()] = perms; string permList = ""; foreach (SRPPermission perm in perms) { permList += String.Format("#{0}", perm.Permission); } Session[SessionData.StringPermissionList.ToString()] = permList; Session["TenantID"] = user.TenID; Session[CRSessionKey.TenantID] = user.TenID; var tenant = Tenant.FetchObject(user.TenID); Session[CRSessionKey.IsMaster] = tenant.isMasterFlag; if (user.MustResetPassword) { this.Log().Info("Redirecting {0} to mandatory password reset.", user.Username); Response.Redirect("~/ControlRoom/PasswordReset.aspx"); } //List<CMSFolder> folders = user.EffectiveUserFolders(); //Session[SessionData.FoldersList.ToString()] = folders; //string foldersList = ""; //foreach (CMSFolder folder in folders) // foldersList += string.Format("#{0}", folder.Folder); //Session[SessionData.StringFoldersList.ToString()] = foldersList; ////// to do - make sure these are in the settings module/ complete the settings module ////string[] HideFolders = new string[] { ".svn", "CVS", "app_data", "properties", "bin", "obj", "controls", "core", "controlroom", "app_themes" }; ////CMSSettings.SetSetting("HideFolders", HideFolders, ","); ////string[] HideFiles = new string[] { ".*" }; ////CMSSettings.SetSetting("HideFiles", HideFiles, ","); ////string[] AllowedExtensions = new string[] { }; ////CMSSettings.SetSetting("AllowedExtensions", AllowedExtensions, ","); ////string[] DeniedExtensions = new string[] { }; ////CMSSettings.SetSetting("DeniedExtensions", DeniedExtensions, ","); ////// end to do FormsAuthentication.RedirectFromLoginPage(uxLogin.UserName, false); } } else { uxMessageBox.Visible = true; } }
public TenantFeaturesEditViewModel(Tenant tenant, GetTenantFeaturesEditOutput output) { Tenant = tenant; output.MapTo(this); }
public static bool SiteExists(this Tenant tenant, string siteFullUrl) { var exists = SiteExistsAnywhere(tenant, siteFullUrl); return(exists == SiteExistence.Yes || exists == SiteExistence.Recycled); }
public DBContextBase(ITenantResolver TenantResolver, IHttpContextAccessor accessor) { tenant = TenantResolver.GetTenant(); this.accessor = accessor; }
public TokenParser(Tenant tenant, Model.ProvisioningHierarchy hierarchy) : this(tenant, hierarchy, null) { }
public static void Map(TenantRequestModel tenantRequestModel, Tenant existingTenant) { existingTenant.name = tenantRequestModel.Name; existingTenant.region = tenantRequestModel.Region; existingTenant.metadata = tenantRequestModel.Metadata; }
/// <summary> /// Adds a SiteEntity by launching site collection creation and waits for the creation to finish /// </summary> /// <param name="tenant">A tenant object pointing to the context of a Tenant Administration site</param> /// <param name="properties">Describes the site collection to be created</param> /// <param name="removeFromRecycleBin">It true and site is present in recycle bin, it will be removed first from the recycle bin</param> /// <param name="wait">If true, processing will halt until the site collection has been created</param> /// <param name="timeoutFunction">An optional function that will be called while waiting for the site to be created. If set will override the wait variable. Return true to cancel the wait loop.</param> /// <returns>Guid of the created site collection and Guid.Empty is the wait parameter is specified as false. Returns Guid.Empty if the wait is cancelled.</returns> public static Guid CreateSiteCollection(this Tenant tenant, SiteEntity properties, bool removeFromRecycleBin = false, bool wait = true, Func <TenantOperationMessage, bool> timeoutFunction = null) { if (removeFromRecycleBin) { if (tenant.CheckIfSiteExists(properties.Url, SITE_STATUS_RECYCLED)) { tenant.DeleteSiteCollectionFromRecycleBin(properties.Url); } } SiteCreationProperties newsite = new SiteCreationProperties(); newsite.Url = properties.Url; newsite.Owner = properties.SiteOwnerLogin; newsite.Template = properties.Template; newsite.Title = properties.Title; newsite.StorageMaximumLevel = properties.StorageMaximumLevel; newsite.StorageWarningLevel = properties.StorageWarningLevel; newsite.TimeZoneId = properties.TimeZoneId; newsite.UserCodeMaximumLevel = properties.UserCodeMaximumLevel; newsite.UserCodeWarningLevel = properties.UserCodeWarningLevel; newsite.Lcid = properties.Lcid; SpoOperation op = tenant.CreateSite(newsite); tenant.Context.Load(tenant); tenant.Context.Load(op, i => i.IsComplete, i => i.PollingInterval); tenant.Context.ExecuteQueryRetry(); // Get site guid and return. If we create the site asynchronously, return an empty guid as we cannot retrieve the site by URL yet. Guid siteGuid = Guid.Empty; if (timeoutFunction != null) { wait = true; } if (wait) { // Let's poll for site collection creation completion if (WaitForIsComplete(tenant, op, timeoutFunction, TenantOperationMessage.CreatingSiteCollection)) { // Restore of original flow to validate correct working in edog after fix got committed if (properties.Url.ToLower().Contains("spoppe.com")) { siteGuid = tenant.GetSiteGuidByUrl(new Uri(properties.Url)); } else { // Return site guid of created site collection try { siteGuid = tenant.GetSiteGuidByUrl(new Uri(properties.Url)); } catch (Exception ex) { // Eat all exceptions cause there's currently (December 16) an issue in the service that can make tenant API calls fail in combination with app-only usage Log.Error("Temp eating exception due to issue in service (December 2016). Exception is {0}.", ex.ToDetailedString()); } } } } return(siteGuid); }
//public CustomerDbContext(DbContextOptions<CustomerDbContext> options) // : base(options) //{ //} // Comment this ctor, use above ctor for migrations. public CustomerDbContext(DbContextOptions <CustomerDbContext> options, ITenantProvider tenantProvider) : base(options) { _tenant = tenantProvider.GetTenant(); }
public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation) { using (var scope = new PnPMonitoredScope(this.Name)) { if (template.WebSettings != null) { // Check if this is not a noscript site as we're not allowed to update some properties bool isNoScriptSite = web.IsNoScriptSite(); web.EnsureProperties( #if !SP2013 && !SP2016 w => w.NoCrawl, w => w.CommentsOnSitePagesDisabled, w => w.ExcludeFromOfflineClient, w => w.MembersCanShare, w => w.DisableFlows, w => w.DisableAppViews, w => w.HorizontalQuickLaunch, #if !SP2019 w => w.SearchScope, w => w.SearchBoxInNavBar, #endif #endif w => w.RootFolder, w => w.Title, w => w.Description, w => w.WebTemplate, w => w.HasUniqueRoleAssignments); var webSettings = template.WebSettings; // Since the IsSubSite function can trigger an executequery ensure it's called before any updates to the web object are done. if (!web.IsSubSite() || (web.IsSubSite() && web.HasUniqueRoleAssignments)) { String requestAccessEmailValue = parser.ParseString(webSettings.RequestAccessEmail); if (!String.IsNullOrEmpty(requestAccessEmailValue) && requestAccessEmailValue.Length >= 255) { requestAccessEmailValue = requestAccessEmailValue.Substring(0, 255); } if (!String.IsNullOrEmpty(requestAccessEmailValue)) { web.RequestAccessEmail = requestAccessEmailValue; web.Update(); web.Context.ExecuteQueryRetry(); } } #if !SP2013 && !SP2016 if (!isNoScriptSite) { web.NoCrawl = webSettings.NoCrawl; } else { scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_WebSettings_SkipNoCrawlUpdate); } if (web.CommentsOnSitePagesDisabled != webSettings.CommentsOnSitePagesDisabled) { web.CommentsOnSitePagesDisabled = webSettings.CommentsOnSitePagesDisabled; } if (web.ExcludeFromOfflineClient != webSettings.ExcludeFromOfflineClient) { web.ExcludeFromOfflineClient = webSettings.ExcludeFromOfflineClient; } if (web.MembersCanShare != webSettings.MembersCanShare) { web.MembersCanShare = webSettings.MembersCanShare; } if (web.DisableFlows != webSettings.DisableFlows) { web.DisableFlows = webSettings.DisableFlows; } if (web.DisableAppViews != webSettings.DisableAppViews) { web.DisableAppViews = webSettings.DisableAppViews; } if (web.HorizontalQuickLaunch != webSettings.HorizontalQuickLaunch) { web.HorizontalQuickLaunch = webSettings.HorizontalQuickLaunch; } #if !SP2019 if (web.SearchScope.ToString() != webSettings.SearchScope.ToString()) { web.SearchScope = (SearchScopeType)Enum.Parse(typeof(SearchScopeType), webSettings.SearchScope.ToString(), true); } if (web.SearchBoxInNavBar.ToString() != webSettings.SearchBoxInNavBar.ToString()) { web.SearchBoxInNavBar = (SearchBoxInNavBarType)Enum.Parse(typeof(SearchBoxInNavBarType), webSettings.SearchBoxInNavBar.ToString(), true); } string searchCenterUrl = parser.ParseString(webSettings.SearchCenterUrl); if (!string.IsNullOrEmpty(searchCenterUrl) && web.GetWebSearchCenterUrl(true) != webSettings.SearchCenterUrl) { web.SetWebSearchCenterUrl(webSettings.SearchCenterUrl); } #endif #endif var masterUrl = parser.ParseString(webSettings.MasterPageUrl); if (!string.IsNullOrEmpty(masterUrl)) { if (!isNoScriptSite) { web.MasterUrl = masterUrl; } else { scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_WebSettings_SkipMasterPageUpdate); } } var customMasterUrl = parser.ParseString(webSettings.CustomMasterPageUrl); if (!string.IsNullOrEmpty(customMasterUrl)) { if (!isNoScriptSite) { web.CustomMasterUrl = customMasterUrl; } else { scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_WebSettings_SkipCustomMasterPageUpdate); } } if (!String.IsNullOrEmpty(webSettings.Title)) { var newTitle = parser.ParseString(webSettings.Title); if (newTitle != web.Title) { web.Title = newTitle; } } if (!String.IsNullOrEmpty(webSettings.Description)) { var newDescription = parser.ParseString(webSettings.Description); if (newDescription != web.Description) { web.Description = newDescription; } } if (webSettings.SiteLogo != null) { var logoUrl = parser.ParseString(webSettings.SiteLogo); if (template.BaseSiteTemplate == "SITEPAGEPUBLISHING#0" && web.WebTemplate == "GROUP") { // logo provisioning throws when applying across base template IDs; provisioning fails in this case // this is the error that is already (rightly so) shown beforehand in the console: WARNING: The source site from which the template was generated had a base template ID value of SITEPAGEPUBLISHING#0, while the current target site has a base template ID value of GROUP#0. This could cause potential issues while applying the template. WriteMessage("Applying site logo across base template IDs is not possible. Skipping site logo provisioning.", ProvisioningMessageType.Warning); } else { // Modern site? Then we assume the SiteLogo is actually a filepath if (web.WebTemplate == "GROUP") { #if !ONPREMISES if (!string.IsNullOrEmpty(logoUrl) && !logoUrl.ToLower().Contains("_api/groupservice/getgroupimage")) { var fileBytes = ConnectorFileHelper.GetFileBytes(template.Connector, logoUrl); if (fileBytes != null && fileBytes.Length > 0) { #if !NETSTANDARD2_0 var mimeType = MimeMapping.GetMimeMapping(logoUrl); #else var mimeType = ""; var imgUrl = logoUrl; if (imgUrl.Contains("?")) { imgUrl = imgUrl.Split(new[] { '?' })[0]; } if (imgUrl.EndsWith(".gif", StringComparison.InvariantCultureIgnoreCase)) { mimeType = "image/gif"; } if (imgUrl.EndsWith(".png", StringComparison.InvariantCultureIgnoreCase)) { mimeType = "image/png"; } if (imgUrl.EndsWith(".jpg", StringComparison.InvariantCultureIgnoreCase)) { mimeType = "image/jpeg"; } #endif Sites.SiteCollection.SetGroupImageAsync((ClientContext)web.Context, fileBytes, mimeType).GetAwaiter().GetResult(); } } #endif } else { web.SiteLogoUrl = logoUrl; } } } var welcomePage = parser.ParseString(webSettings.WelcomePage); if (!string.IsNullOrEmpty(welcomePage)) { if (welcomePage != web.RootFolder.WelcomePage) { web.RootFolder.WelcomePage = welcomePage; web.RootFolder.Update(); } } if (!string.IsNullOrEmpty(webSettings.AlternateCSS)) { var newAlternateCssUrl = parser.ParseString(webSettings.AlternateCSS); if (newAlternateCssUrl != web.AlternateCssUrl) { web.AlternateCssUrl = newAlternateCssUrl; } } // Temporary disabled as this change is a breaking change for folks that have not set this property in their provisioning templates //web.QuickLaunchEnabled = webSettings.QuickLaunchEnabled; web.Update(); web.Context.ExecuteQueryRetry(); #if !ONPREMISES if (webSettings.HubSiteUrl != null) { var hubsiteUrl = parser.ParseString(webSettings.HubSiteUrl); try { using (var tenantContext = web.Context.Clone(web.GetTenantAdministrationUrl(), applyingInformation.AccessTokens)) { var tenant = new Tenant(tenantContext); tenant.ConnectSiteToHubSite(web.Url, hubsiteUrl); tenantContext.ExecuteQueryRetry(); } } catch (Exception ex) { WriteMessage($"Hub site association failed: {ex.Message}", ProvisioningMessageType.Warning); } } #endif } } return(parser); }
public override ProvisioningTemplate ExtractObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo) { using (var scope = new PnPMonitoredScope(this.Name)) { web.EnsureProperties( #if !SP2013 && !SP2016 w => w.NoCrawl, w => w.CommentsOnSitePagesDisabled, w => w.ExcludeFromOfflineClient, w => w.MembersCanShare, w => w.DisableFlows, w => w.DisableAppViews, w => w.HorizontalQuickLaunch, w => w.QuickLaunchEnabled, #if !SP2019 w => w.SearchScope, w => w.SearchBoxInNavBar, #endif #endif //w => w.Title, //w => w.Description, w => w.MasterUrl, w => w.CustomMasterUrl, w => w.SiteLogoUrl, w => w.RequestAccessEmail, w => w.RootFolder, w => w.AlternateCssUrl, w => w.ServerRelativeUrl, w => w.Url ); var webSettings = new WebSettings(); #if !SP2013 && !SP2016 webSettings.NoCrawl = web.NoCrawl; webSettings.CommentsOnSitePagesDisabled = web.CommentsOnSitePagesDisabled; webSettings.ExcludeFromOfflineClient = web.ExcludeFromOfflineClient; webSettings.MembersCanShare = web.MembersCanShare; webSettings.DisableFlows = web.DisableFlows; webSettings.DisableAppViews = web.DisableAppViews; webSettings.HorizontalQuickLaunch = web.HorizontalQuickLaunch; webSettings.QuickLaunchEnabled = web.QuickLaunchEnabled; #if !SP2019 webSettings.SearchScope = (SearchScopes)Enum.Parse(typeof(SearchScopes), web.SearchScope.ToString(), true); webSettings.SearchBoxInNavBar = (SearchBoxInNavBar)Enum.Parse(typeof(SearchBoxInNavBar), web.SearchBoxInNavBar.ToString(), true); webSettings.SearchCenterUrl = web.GetWebSearchCenterUrl(true); #endif #endif // We're not extracting Title and Description //webSettings.Title = Tokenize(web.Title, web.Url); //webSettings.Description = Tokenize(web.Description, web.Url); webSettings.MasterPageUrl = Tokenize(web.MasterUrl, web.Url); webSettings.CustomMasterPageUrl = Tokenize(web.CustomMasterUrl, web.Url); webSettings.SiteLogo = TokenizeHost(web, Tokenize(web.SiteLogoUrl, web.Url)); // Notice. No tokenization needed for the welcome page, it's always relative for the site webSettings.WelcomePage = web.RootFolder.WelcomePage; webSettings.AlternateCSS = Tokenize(web.AlternateCssUrl, web.Url); webSettings.RequestAccessEmail = web.RequestAccessEmail; #if !ONPREMISES // Can we get the hubsite url? This requires Tenant Admin rights try { var site = ((ClientContext)web.Context).Site; site.EnsureProperties(s => s.HubSiteId, s => s.Id); if (site.HubSiteId != Guid.Empty && site.HubSiteId != site.Id) { using (var tenantContext = web.Context.Clone((web.Context as ClientContext).Web.GetTenantAdministrationUrl())) { var tenant = new Tenant(tenantContext); var hubsiteProperties = tenant.GetHubSitePropertiesById(site.HubSiteId); tenantContext.Load(hubsiteProperties); tenantContext.ExecuteQueryRetry(); webSettings.HubSiteUrl = hubsiteProperties.SiteUrl; } } } catch { } #endif if (creationInfo.PersistBrandingFiles) { if (!string.IsNullOrEmpty(web.MasterUrl)) { var masterUrl = web.MasterUrl.ToLower(); if (!masterUrl.EndsWith("default.master") && !masterUrl.EndsWith("custom.master") && !masterUrl.EndsWith("v4.master") && !masterUrl.EndsWith("seattle.master") && !masterUrl.EndsWith("oslo.master")) { if (PersistFile(web, creationInfo, scope, web.MasterUrl)) { template.Files.Add(GetTemplateFile(web, web.MasterUrl)); } } } if (!string.IsNullOrEmpty(web.CustomMasterUrl)) { var customMasterUrl = web.CustomMasterUrl.ToLower(); if (!customMasterUrl.EndsWith("default.master") && !customMasterUrl.EndsWith("custom.master") && !customMasterUrl.EndsWith("v4.master") && !customMasterUrl.EndsWith("seattle.master") && !customMasterUrl.EndsWith("oslo.master")) { if (PersistFile(web, creationInfo, scope, web.CustomMasterUrl)) { template.Files.Add(GetTemplateFile(web, web.CustomMasterUrl)); } } } // Extract site logo if property has been set and it's not dynamic image from _api URL if (!string.IsNullOrEmpty(web.SiteLogoUrl) && (!web.SiteLogoUrl.ToLowerInvariant().Contains("_api/"))) { // Convert to server relative URL if needed (web.SiteLogoUrl can be set to FQDN URL of a file hosted in the site (e.g. for communication sites)) Uri webUri = new Uri(web.Url); string webUrl = $"{webUri.Scheme}://{webUri.DnsSafeHost}"; string siteLogoServerRelativeUrl = web.SiteLogoUrl.Replace(webUrl, ""); if (PersistFile(web, creationInfo, scope, siteLogoServerRelativeUrl)) { template.Files.Add(GetTemplateFile(web, HttpUtility.UrlDecode(siteLogoServerRelativeUrl))); } } if (!string.IsNullOrEmpty(web.AlternateCssUrl)) { if (PersistFile(web, creationInfo, scope, web.AlternateCssUrl)) { template.Files.Add(GetTemplateFile(web, web.AlternateCssUrl)); } } var files = template.Files.Distinct().ToList(); template.Files.Clear(); template.Files.AddRange(files); } if (!creationInfo.PersistBrandingFiles) { if (creationInfo.BaseTemplate != null) { if (!webSettings.Equals(creationInfo.BaseTemplate.WebSettings)) { template.WebSettings = webSettings; } } else { template.WebSettings = webSettings; } } else { template.WebSettings = webSettings; } } return(template); }
protected override void ExecuteCmdlet() { Tenant.GrantSiteDesignRights(Identity.Id, Principals, Rights); ClientContext.ExecuteQueryRetry(); }
public OneBlinkPdfClient(string accessKey, string secretKey, Tenant tenant, int expiryInSeconds = 300) : base(accessKey, secretKey, expiryInSeconds) { this.tenant = tenant ?? new Tenant(TenantName.ONEBLINK); }
private void CreateSiteCollection(SiteCollectionProvisioningJob job) { Console.WriteLine("Creating Site Collection \"{0}\".", job.RelativeUrl); // Define the full Site Collection URL String siteUrl = String.Format("{0}{1}", PnPPartnerPackSettings.InfrastructureSiteUrl.Substring(0, PnPPartnerPackSettings.InfrastructureSiteUrl.IndexOf("sharepoint.com/") + 14), job.RelativeUrl); // Load the template from the source Templates Provider if (!String.IsNullOrEmpty(job.TemplatesProviderTypeName)) { ProvisioningTemplate template = null; var templatesProvider = PnPPartnerPackSettings.TemplatesProviders[job.TemplatesProviderTypeName]; if (templatesProvider != null) { template = templatesProvider.GetProvisioningTemplate(job.ProvisioningTemplateUrl); } if (template != null) { using (var adminContext = PnPPartnerPackContextProvider.GetAppOnlyTenantLevelClientContext()) { adminContext.RequestTimeout = Timeout.Infinite; // Configure the Site Collection properties SiteEntity newSite = new SiteEntity(); newSite.Description = job.Description; newSite.Lcid = (uint)job.Language; newSite.Title = job.SiteTitle; newSite.Url = siteUrl; newSite.SiteOwnerLogin = job.PrimarySiteCollectionAdmin; newSite.StorageMaximumLevel = job.StorageMaximumLevel; newSite.StorageWarningLevel = job.StorageWarningLevel; // Use the BaseSiteTemplate of the template, if any, otherwise // fallback to the pre-configured site template (i.e. STS#0) newSite.Template = !String.IsNullOrEmpty(template.BaseSiteTemplate) ? template.BaseSiteTemplate : PnPPartnerPackSettings.DefaultSiteTemplate; newSite.TimeZoneId = job.TimeZone; newSite.UserCodeMaximumLevel = job.UserCodeMaximumLevel; newSite.UserCodeWarningLevel = job.UserCodeWarningLevel; // Create the Site Collection and wait for its creation (we're asynchronous) var tenant = new Tenant(adminContext); tenant.CreateSiteCollection(newSite, true, true); // TODO: Do we want to empty Recycle Bin? Site site = tenant.GetSiteByUrl(siteUrl); Web web = site.RootWeb; adminContext.Load(site, s => s.Url); adminContext.Load(web, w => w.Url); adminContext.ExecuteQueryRetry(); // Enable Secondary Site Collection Administrator if (!String.IsNullOrEmpty(job.SecondarySiteCollectionAdmin)) { Microsoft.SharePoint.Client.User secondaryOwner = web.EnsureUser(job.SecondarySiteCollectionAdmin); secondaryOwner.IsSiteAdmin = true; secondaryOwner.Update(); web.SiteUsers.AddUser(secondaryOwner); adminContext.ExecuteQueryRetry(); } Console.WriteLine("Site \"{0}\" created.", site.Url); // Check if external sharing has to be enabled if (job.ExternalSharingEnabled) { EnableExternalSharing(tenant, site); // Enable External Sharing Console.WriteLine("Enabled External Sharing for site \"{0}\".", site.Url); } } // Move to the context of the created Site Collection using (ClientContext clientContext = PnPPartnerPackContextProvider.GetAppOnlyClientContext(siteUrl)) { clientContext.RequestTimeout = Timeout.Infinite; Site site = clientContext.Site; Web web = site.RootWeb; clientContext.Load(site, s => s.Url); clientContext.Load(web, w => w.Url); clientContext.ExecuteQueryRetry(); // Check if we need to enable PnP Partner Pack overrides if (job.PartnerPackExtensionsEnabled) { // Enable Responsive Design PnPPartnerPackUtilities.EnablePartnerPackOnSite(site.Url); Console.WriteLine("Enabled PnP Partner Pack Overrides on site \"{0}\".", site.Url); } // Check if the site has to be responsive if (job.ResponsiveDesignEnabled) { // Enable Responsive Design PnPPartnerPackUtilities.EnableResponsiveDesignOnSite(site.Url); Console.WriteLine("Enabled Responsive Design Template to site \"{0}\".", site.Url); } // Apply the Provisioning Template Console.WriteLine("Applying Provisioning Template \"{0}\" to site.", job.ProvisioningTemplateUrl); // We do intentionally remove taxonomies, which are not supported // in the AppOnly Authorization model // For further details, see the PnP Partner Pack documentation ProvisioningTemplateApplyingInformation ptai = new ProvisioningTemplateApplyingInformation(); // Write provisioning steps on console log ptai.MessagesDelegate += delegate(string message, ProvisioningMessageType messageType) { Console.WriteLine("{0} - {1}", messageType, messageType); }; ptai.ProgressDelegate += delegate(string message, int step, int total) { Console.WriteLine("{0:00}/{1:00} - {2}", step, total, message); }; // Exclude handlers not supported in App-Only ptai.HandlersToProcess ^= OfficeDevPnP.Core.Framework.Provisioning.Model.Handlers.TermGroups; ptai.HandlersToProcess ^= OfficeDevPnP.Core.Framework.Provisioning.Model.Handlers.SearchSettings; // Configure template parameters if (job.TemplateParameters != null) { foreach (var key in job.TemplateParameters.Keys) { if (job.TemplateParameters.ContainsKey(key)) { template.Parameters[key] = job.TemplateParameters[key]; } } } // Fixup Title and Description if (template.WebSettings != null) { template.WebSettings.Title = job.SiteTitle; template.WebSettings.Description = job.Description; } // Apply the template to the target site web.ApplyProvisioningTemplate(template, ptai); // Save the template information in the target site var info = new SiteTemplateInfo() { TemplateProviderType = job.TemplatesProviderTypeName, TemplateUri = job.ProvisioningTemplateUrl, TemplateParameters = template.Parameters, AppliedOn = DateTime.Now, }; var jsonInfo = JsonConvert.SerializeObject(info); web.SetPropertyBagValue(PnPPartnerPackConstants.PropertyBag_TemplateInfo, jsonInfo); // Set site policy template if (!String.IsNullOrEmpty(job.SitePolicy)) { web.ApplySitePolicy(job.SitePolicy); } // Apply Tenant Branding, if requested if (job.ApplyTenantBranding) { var brandingSettings = PnPPartnerPackUtilities.GetTenantBrandingSettings(); using (var repositoryContext = PnPPartnerPackContextProvider.GetAppOnlyClientContext( PnPPartnerPackSettings.InfrastructureSiteUrl)) { var brandingTemplate = BrandingJobHandler.PrepareBrandingTemplate(repositoryContext, brandingSettings); // Fixup Title and Description if (brandingTemplate != null) { if (brandingTemplate.WebSettings != null) { brandingTemplate.WebSettings.Title = job.SiteTitle; brandingTemplate.WebSettings.Description = job.Description; } // TO-DO: Need to handle exception here as there are multiple webs inside this where BrandingJobHandler.ApplyBrandingOnWeb(web, brandingSettings, brandingTemplate); } } } Console.WriteLine("Applyed Provisioning Template \"{0}\" to site.", job.ProvisioningTemplateUrl); } } } }
/// <summary> /// Enables Site Classifications for the target tenant /// </summary> /// <param name="tenant">The target tenant</param> /// <param name="accessToken">The OAuth accessToken for Microsoft Graph with Azure AD</param> /// <param name="siteClassificationsSettings">The site classifications settings to apply./param> public static void EnableSiteClassifications(this Tenant tenant, string accessToken, SiteClassificationsSettings siteClassificationsSettings) { SiteClassificationsUtility.EnableSiteClassifications(accessToken, siteClassificationsSettings); }
private async Task SeedDataAsync(Tenant tenant = null) { Logger.LogInformation($"Executing {(tenant == null ? "host" : tenant.Name + " tenant")} database seed..."); await _dataSeeder.SeedAsync(tenant?.Id); }