public SPOSite(SiteProperties props, bool?disableSharingForNonOwnersStatus) { AllowDownloadingNonWebViewableFiles = props.AllowDownloadingNonWebViewableFiles; AllowEditing = props.AllowEditing; AllowSelfServiceUpgrade = props.AllowSelfServiceUpgrade; AnonymousLinkExpirationInDays = props.AnonymousLinkExpirationInDays; BlockDownloadLinksFileType = props.BlockDownloadLinksFileType; CommentsOnSitePagesDisabled = props.CommentsOnSitePagesDisabled; CompatibilityLevel = props.CompatibilityLevel; ConditionalAccessPolicy = props.ConditionalAccessPolicy; DefaultLinkPermission = props.DefaultLinkPermission; DefaultLinkToExistingAccess = props.DefaultLinkToExistingAccess; DefaultSharingLinkType = props.DefaultSharingLinkType; DenyAddAndCustomizePages = props.DenyAddAndCustomizePages; Description = props.Description; DisableAppViews = props.DisableAppViews; DisableCompanyWideSharingLinks = props.DisableCompanyWideSharingLinks; DisableFlows = props.DisableFlows; DisableSharingForNonOwnersStatus = disableSharingForNonOwnersStatus; ExternalUserExpirationInDays = props.ExternalUserExpirationInDays; GroupId = props.GroupId; HubSiteId = props.HubSiteId; IsHubSite = props.IsHubSite; LastContentModifiedDate = props.LastContentModifiedDate; LimitedAccessFileType = props.LimitedAccessFileType; LocaleId = props.Lcid; LockIssue = props.LockIssue; LockState = props.LockState; Owner = props.Owner; OwnerEmail = props.OwnerEmail; OwnerLoginName = props.OwnerLoginName; OwnerName = props.OwnerName; OverrideTenantAnonymousLinkExpirationPolicy = props.OverrideTenantAnonymousLinkExpirationPolicy; OverrideTenantExternalUserExpirationPolicy = props.OverrideTenantExternalUserExpirationPolicy; PWAEnabled = props.PWAEnabled; RelatedGroupId = props.RelatedGroupId; ResourceQuota = props.UserCodeMaximumLevel; ResourceQuotaWarningLevel = props.UserCodeWarningLevel; ResourceUsageAverage = props.AverageResourceUsage; ResourceUsageCurrent = props.CurrentResourceUsage; RestrictedToGeo = props.RestrictedToRegion; SandboxedCodeActivationCapability = props.SandboxedCodeActivationCapability; SensitivityLabel = props.SensitivityLabel2; SharingAllowedDomainList = props.SharingAllowedDomainList; SharingBlockedDomainList = props.SharingBlockedDomainList; SharingCapability = props.SharingCapability; SharingDomainRestrictionMode = props.SharingDomainRestrictionMode; ShowPeoplePickerSuggestionsForGuestUsers = props.ShowPeoplePickerSuggestionsForGuestUsers; SiteDefinedSharingCapability = props.SiteDefinedSharingCapability; SocialBarOnSitePagesDisabled = props.SocialBarOnSitePagesDisabled; Status = props.Status; StorageQuota = props.StorageMaximumLevel; StorageQuotaType = props.StorageQuotaType; StorageQuotaWarningLevel = props.StorageWarningLevel; StorageUsageCurrent = props.StorageUsage; Template = props.Template; Title = props.Title; WebsCount = props.WebsCount; Url = props.Url; }
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); } }
public bool DoesURLExist(string _inputSiteCollectionTitle) { bool isSiteCollectionURLExisting = false; string siteCollectionUrl = SPOAdminURL; string _inputSiteCollectionURL = Constants.RootSiteCollectionURL + Constants.ManagedPath + _inputSiteCollectionTitle; try { ClientContext clientContext; using (clientContext = GetClientContext(siteCollectionUrl, clientID, clientSecret)) { clientContext.ExecuteQuery(); Tenant currentO365Tenant = new Tenant(clientContext); clientContext.ExecuteQuery(); SPOSitePropertiesEnumerable sitePropEnumerable = currentO365Tenant.GetSiteProperties(0, true); clientContext.Load(sitePropEnumerable); clientContext.ExecuteQuery(); List <SiteProperties> sitePropertyCollection = new List <SiteProperties>(); sitePropertyCollection.AddRange(sitePropEnumerable); SiteProperties property1 = sitePropertyCollection.Find(s => s.Url.ToLower().Equals(_inputSiteCollectionURL.ToLower())); isSiteCollectionURLExisting = property1 != null ? true : false; } } catch (Exception ex) { isSiteCollectionURLExisting = false; } return(isSiteCollectionURLExisting); }
protected void sitecollections_SelectedIndexChanged(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 (siteProp.SharingCapability) { case SharingCapabilities.Disabled: lblStatus.Text = "External sharing is disabled."; rblSharingOptions.SelectedValue = "Disabled"; break; case SharingCapabilities.ExternalUserSharingOnly: lblStatus.Text = "External sharing is for authenticated users."; rblSharingOptions.SelectedValue = "ExternalUserSharingOnly"; break; case SharingCapabilities.ExternalUserAndGuestSharing: lblStatus.Text = "External sharing is for authenticated and guest users."; rblSharingOptions.SelectedValue = "ExternalUserAndGuestSharing"; break; default: break; } lblStatus.Text = string.Format("Sharing status resolved for site collection at URL: {0}", siteUrl); } }
public static void WaitSiteCreateFinished(ClientContext context, Tenant tenant, List <string> siteUrls) { foreach (var siteUrl in siteUrls) { SiteProperties siteProperties = null; bool errorOccurred = false; logger.InfoFormat("Satrt check {0} site status", siteUrl); do { errorOccurred = false; try { System.Threading.Thread.Sleep(10000); siteProperties = tenant.GetSitePropertiesByUrl(siteUrl, false); context.Load(siteProperties); context.ExecuteQuery(); if (siteProperties != null) { logger.InfoFormat("Site Collection Url: {0}, Site Collection Status:{1}", siteUrl, siteProperties.Status); } } catch (Exception e) { string message = e.Message; logger.Warn("An error occurred while getting site properties. Error:{0}", e); errorOccurred = true; } }while (errorOccurred || siteProperties == null || string.Equals("Creating", siteProperties.Status, StringComparison.OrdinalIgnoreCase)); logger.InfoFormat("Create site collction {0} successfully", siteUrl); } }
/// <summary> /// Method to create site collections /// </summary> /// <param name="clientContext">SharePoint Client Context</param> /// <param name="configVal">Values in Config sheet</param> /// <param name="clientUrl">Url for Site Collection</param> /// <param name="clientTitle">Name of Site Collection</param> internal static void CreateSiteCollections(ClientContext clientContext, Dictionary <string, string> configVal, string clientUrl, string clientTitle) { try { Tenant tenant = new Tenant(clientContext); clientContext.Load(tenant); clientContext.ExecuteQuery(); //login into SharePoint Online SPOSitePropertiesEnumerable spoSiteProperties = tenant.GetSiteProperties(0, true); clientContext.Load(spoSiteProperties); clientContext.ExecuteQuery(); SiteProperties siteProperties = (from properties in spoSiteProperties where properties.Url.ToString().ToUpper() == clientUrl.ToUpper() select properties).FirstOrDefault(); if (null != siteProperties) { // site exists Console.WriteLine(clientUrl + " already exists..."); return; } else { // site does not exists SiteCreationProperties newSite = new SiteCreationProperties() { Url = clientUrl, Owner = configVal["Username"], Template = ConfigurationManager.AppSettings["template"], //using the team site template, check the MSDN if you want to use other template StorageMaximumLevel = Convert.ToInt64(ConfigurationManager.AppSettings["storageMaximumLevel"], CultureInfo.InvariantCulture), //1000 UserCodeMaximumLevel = Convert.ToDouble(ConfigurationManager.AppSettings["userCodeMaximumLevel"], CultureInfo.InvariantCulture), //300 Title = clientTitle, CompatibilityLevel = 15, //15 means SharePoint online 2013, 14 means SharePoint online 2010 }; SpoOperation spo = tenant.CreateSite(newSite); clientContext.Load(tenant); clientContext.Load(spo, operation => operation.IsComplete); clientContext.ExecuteQuery(); Console.WriteLine("Creating site collection at " + clientUrl); Console.WriteLine("Loading."); //Check if provisioning of the SiteCollection is complete. while (!spo.IsComplete) { Console.Write("."); //Wait for 30 seconds and then try again System.Threading.Thread.Sleep(30000); spo.RefreshLoad(); clientContext.ExecuteQuery(); } Console.WriteLine("Site Collection: " + clientUrl + " is created successfully"); } } catch (Exception exception) { Console.WriteLine("Exception occurred while creating site collection: " + exception.Message); } }
public void UpdatesRemote() { // Setup var mockClient = new Mock <IWebsitesClient>(); string slot = WebsiteSlotName.Staging.ToString(); SiteProperties props = new SiteProperties() { Properties = new List <NameValuePair>() { new NameValuePair() { Name = "RepositoryUri", Value = "https://[email protected]:443/website.git" }, new NameValuePair() { Name = "PublishingUsername", Value = "test" } } }; mockClient.Setup(c => c.GetWebsiteSlots("website1")) .Returns( new List <Site> { new Site { Name = "website1", WebSpace = "webspace1", SiteProperties = props }, new Site { Name = "website1(staging)", WebSpace = "webspace1", SiteProperties = props } }); mockClient.Setup(c => c.GetSlotName("website1")) .Returns(WebsiteSlotName.Production.ToString()) .Verifiable(); mockClient.Setup(c => c.GetSlotName("website1(staging)")) .Returns(WebsiteSlotName.Staging.ToString()) .Verifiable(); // Test UpdateAzureWebsiteRepositoryCommand cmdlet = new UpdateAzureWebsiteRepositoryCommand { CommandRuntime = new MockCommandRuntime(), WebsitesClient = mockClient.Object, Name = "website1", }; currentProfile = new AzureSMProfile(); var subscription = new AzureSubscription { Id = new Guid(base.subscriptionId) }; subscription.Properties[AzureSubscription.Property.Default] = "True"; currentProfile.Subscriptions[new Guid(base.subscriptionId)] = subscription; // Switch existing website cmdlet.ExecuteCmdlet(); mockClient.Verify(c => c.GetSlotName("website1(staging)"), Times.Once()); mockClient.Verify(c => c.GetSlotName("website1"), Times.Once()); }
/// <summary> /// Get the external sharing settings for the provided site. Only works in Office 365 Multi-Tenant /// </summary> /// <param name="web">Tenant administration web</param> /// <param name="siteUrl">Site to get the sharing capabilities from</param> /// <returns>Sharing capabilities of the site collection</returns> public static string GetSharingCapabilitiesTenant(this Web web, Uri siteUrl) { Tenant tenant = new Tenant(web.Context); SiteProperties site = tenant.GetSitePropertiesByUrl(siteUrl.OriginalString, true); web.Context.Load(site); web.Context.ExecuteQuery(); return(site.SharingCapability.ToString()); }
/// <summary> /// /// </summary> /// <param name="siteUrl"></param> public virtual bool isSiteExternalSharingEnabled(string siteUrl) { ConfigManager _manager = new ConfigManager(); var _tenantAdminUrl = _manager.GetAppSettingsKey("TenantAdminUrl"); var _returnResult = false; AbstractSiteProvisioningService _siteService = new Office365SiteProvisioningService(); _siteService.Authentication = new AppOnlyAuthenticationTenant(); _siteService.Authentication.TenantAdminUrl = _tenantAdminUrl; _siteService.UsingContext(ctx => { try { Tenant _tenant = new Tenant(ctx); SiteProperties _siteProps = _tenant.GetSitePropertiesByUrl(siteUrl, false); ctx.Load(_tenant); ctx.Load(_siteProps); ctx.ExecuteQuery(); var _tenantSharingCapability = _tenant.SharingCapability; var _siteSharingCapability = _siteProps.SharingCapability; if (_tenantSharingCapability != SharingCapabilities.Disabled) { if (_siteSharingCapability != SharingCapabilities.Disabled) { // Enabled _returnResult = true; } else { // Disabled _returnResult = false; } } else { // Disabled _returnResult = false; } } catch (Exception _ex) { Log.Warning("AbstractSiteProvisioningService.IsSiteExternalSharingEnabled", PCResources.SiteExternalSharing_Enabled_Error_Message, siteUrl, _ex); } }); return(_returnResult); }
private static bool CheckUserDomainFrom(SiteProperties siteProps, string emailAddress) { var allowedListDomainFromSite = siteProps.SharingAllowedDomainList.Split(',').Select(x => x.Trim().ToUpper()).ToList(); MailAddress address = new MailAddress(emailAddress); string host = address.Host.ToUpper(); if (allowedListDomainFromSite.Contains(host)) { return(true); } return(false); }
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(); }
private void EditSiteButton_Tapped(object sender, TappedRoutedEventArgs e) { var selectedSite = (Model.Site)SitesView.SelectedItem; SetSelectionEnabled(false); SiteProperties.Operation = Controls.FormOperation.Edit; SiteProperties.Site = selectedSite ?? throw new Exception("Edit site button should not be active when no device is selected"); SiteProperties.Visibility = Visibility.Visible; SiteProperties.SetInitialFocus(); }
/// <summary> /// Used to set External Sharing /// </summary> /// <param name="siteInfo"></param> public override void SetExternalSharing(SiteInformation siteInfo) { UsingContext(ctx => { try { Stopwatch _timespan = Stopwatch.StartNew(); Tenant _tenant = new Tenant(ctx); //_tenant.SetSiteProperties(siteInfo.Url, null, null, SharingCapabilities.ExternalUserSharingOnly, null, null, null, null); SiteProperties _siteProps = _tenant.GetSitePropertiesByUrl(siteInfo.Url, false); ctx.Load(_tenant); ctx.Load(_siteProps); ctx.ExecuteQuery(); var _tenantSharingCapability = _tenant.SharingCapability; var _siteSharingCapability = _siteProps.SharingCapability; var _targetSharingCapability = SharingCapabilities.Disabled; if (!siteInfo.EnableExternalSharing && _tenantSharingCapability != SharingCapabilities.Disabled) { _targetSharingCapability = SharingCapabilities.Disabled; _siteProps.SharingCapability = _targetSharingCapability; _siteProps.Update(); ctx.ExecuteQuery(); Log.Info("Provisioning.Common.Office365SiteProvisioningService.SetExternalSharing", PCResources.ExternalSharing_Successful, siteInfo.Url); } if (siteInfo.EnableExternalSharing && _tenantSharingCapability != SharingCapabilities.Disabled) { _targetSharingCapability = SharingCapabilities.ExternalUserSharingOnly; _siteProps.SharingCapability = _targetSharingCapability; _siteProps.Update(); ctx.ExecuteQuery(); Log.Info("Provisioning.Common.Office365SiteProvisioningService.SetExternalSharing", PCResources.ExternalSharing_Successful, siteInfo.Url); } _timespan.Stop(); Log.TraceApi("SharePoint", "Office365SiteProvisioningService.SetExternalSharing", _timespan.Elapsed, "SiteUrl={0}", siteInfo.Url); } catch (ServerException _ex) { Log.Info("Provisioning.Common.Office365SiteProvisioningService.SetExternalSharing", PCResources.ExternalSharing_Exception, siteInfo.Url, _ex); } catch (Exception _ex) { Log.Info("Provisioning.Common.Office365SiteProvisioningService.SetExternalSharing", PCResources.ExternalSharing_Exception, siteInfo.Url, _ex); } }); }
/// <summary> /// Get the external sharing settings for the provided site. Only works in Office 365 Multi-Tenant /// </summary> /// <param name="web">Tenant administration web</param> /// <param name="siteUrl">Site to get the sharing capabilities from</param> /// <returns>Sharing capabilities of the site collection</returns> public static string GetSharingCapabilitiesTenant(this Web web, Uri siteUrl) { if (siteUrl == null) { throw new ArgumentNullException("siteUrl"); } Tenant tenant = new Tenant(web.Context); SiteProperties site = tenant.GetSitePropertiesByUrl(siteUrl.OriginalString, true); web.Context.Load(site); web.Context.ExecuteQueryRetry(); return(site.SharingCapability.ToString()); }
/// <summary> /// Sets the Site Collection External Sharing Setting using the SharePoint Tenant API /// </summary> /// <param name="adminCC"></param> /// <param name="siteCollectionURl"></param> /// <param name="shareSettings"></param> public static void SetSiteSharing(ClientContext adminCC, string siteCollectionURl, SharingCapabilities shareSettings) { var _tenantAdmin = new Tenant(adminCC); SiteProperties _siteprops = _tenantAdmin.GetSitePropertiesByUrl(siteCollectionURl, true); adminCC.Load(_tenantAdmin); adminCC.Load(_siteprops); adminCC.ExecuteQuery(); SharingCapabilities _tenantSharing = _tenantAdmin.SharingCapability; var _currentShareSettings = _siteprops.SharingCapability; bool _isUpdatable = false; if (_tenantSharing == SharingCapabilities.Disabled) { Console.WriteLine("Sharing is currently disabled in your tenant! I am unable to work on it."); } else { if (shareSettings == SharingCapabilities.Disabled) { _isUpdatable = true; } else if (shareSettings == SharingCapabilities.ExternalUserSharingOnly) { _isUpdatable = true; } else if (shareSettings == SharingCapabilities.ExternalUserAndGuestSharing) { if (_tenantSharing == SharingCapabilities.ExternalUserAndGuestSharing) { _isUpdatable = true; } else { Console.WriteLine("ExternalUserAndGuestSharing is currently disabled in your tenant! I am unable to work on it."); } } } if (_currentShareSettings != shareSettings && _isUpdatable) { _siteprops.SharingCapability = shareSettings; _siteprops.Update(); adminCC.ExecuteQuery(); Console.WriteLine("Set Sharing on site {0} to {1}.", siteCollectionURl, shareSettings); } }
/// <summary> /// Method for deleting site collections /// </summary> /// <param name="clientContext">SharePoint Client Context</param> /// <param name="clientUrl">Url for Site Collection</param> internal static void DeleteSiteCollection(ClientContext clientContext, string clientUrl) { try { Tenant tenant = new Tenant(clientContext); clientContext.Load(tenant); clientContext.ExecuteQuery(); //login into SharePoint online SPOSitePropertiesEnumerable spSiteProperties = tenant.GetSiteProperties(0, true); clientContext.Load(spSiteProperties); clientContext.ExecuteQuery(); SiteProperties siteProperties = (from properties in spSiteProperties where properties.Url.ToString().ToUpper() == clientUrl.ToUpper() select properties).FirstOrDefault(); if (null != siteProperties) { // site exists // delete the site SpoOperation spoOperation = tenant.RemoveSite(clientUrl); clientContext.Load(spoOperation, operation => operation.IsComplete); clientContext.ExecuteQuery(); while (!spoOperation.IsComplete) { Console.Write("."); //Wait for 30 seconds and then try again System.Threading.Thread.Sleep(30000); spoOperation.RefreshLoad(); clientContext.ExecuteQuery(); } Console.WriteLine("Site Collection: " + clientUrl + " is deleted successfully"); } else { // site does not exists return; } } catch (Exception exception) { Console.WriteLine("Exception occurred while deleting site collection: " + exception.Message); } }
private void SetSiteView() { var sites = tree1.SelectedFolders; if (sites.Length > 1) { //SetView(ratingTableView); //ratingTableView.Draw(sites); } else // view edit single measurement { siteEditor1 = new SiteProperties(DB); SetView(siteEditor1); siteEditor1.Draw(sites[0].Name); } toolStripProgressBar1.Visible = false; }
private void AddSiteButton_Tapped(object sender, TappedRoutedEventArgs e) { var selectedTenant = TenantsView.SelectedItem as Model.Tenant; if (selectedTenant == null) { throw new Exception("It should not be possible to select add site if no tenant is selected"); } SetSelectionEnabled(false); SiteProperties.Operation = Controls.FormOperation.Add; SiteProperties.Site = null; SiteProperties.ClearForm(); SiteProperties.TenantId = selectedTenant.Id; SiteProperties.Visibility = Visibility.Visible; SiteProperties.SetInitialFocus(); }
private void tabControl1_SelectedIndexChanged(object sender, EventArgs e) { if (this.tabControl1.SelectedTab == tabPageLinux && m_siteMetaData == null) { var db = Database.DB(); m_siteMetaData = new SiteProperties(db); m_siteMetaData.Parent = tabPageSites; m_siteMetaData.Dock = DockStyle.Fill; } if (this.tabControl1.SelectedTab == tabPageEquations && m_equationEditorTable1 == null) { m_equationEditorTable1 = new EquationEditorTable(); m_equationEditorTable1.Parent = tabPageEquations; m_equationEditorTable1.Dock = DockStyle.Fill; } }
public static string GetSiteCollectionStatusByUrl(ClientContext clientContext, string url) { var tenant = new Tenant(clientContext); var sitePropertiesColl = tenant.GetSiteProperties(0, true); var q = clientContext.LoadQuery(sitePropertiesColl.Where(n => n.Url == url)); clientContext.ExecuteQuery(); if (q.Count() > 0) { SiteProperties prop = q.FirstOrDefault() as SiteProperties; return(prop.Status); } else { return("None"); } }
public void UpdatesRemote() { // Setup var mockClient = new Mock<IWebsitesClient>(); string slot = WebsiteSlotName.Staging.ToString(); SiteProperties props = new SiteProperties() { Properties = new List<NameValuePair>() { new NameValuePair() { Name = "RepositoryUri", Value = "https://[email protected]:443/website.git" }, new NameValuePair() { Name = "PublishingUsername", Value = "test" } } }; mockClient.Setup(c => c.GetWebsiteSlots("website1")) .Returns( new List<Site> { new Site { Name = "website1", WebSpace = "webspace1", SiteProperties = props }, new Site { Name = "website1(staging)", WebSpace = "webspace1", SiteProperties = props } }); mockClient.Setup(c => c.GetSlotName("website1")) .Returns(WebsiteSlotName.Production.ToString()) .Verifiable(); mockClient.Setup(c => c.GetSlotName("website1(staging)")) .Returns(WebsiteSlotName.Staging.ToString()) .Verifiable(); // Test UpdateAzureWebsiteRepositoryCommand cmdlet = new UpdateAzureWebsiteRepositoryCommand { CommandRuntime = new MockCommandRuntime(), WebsitesClient = mockClient.Object, Name = "website1", CurrentSubscription = new WindowsAzureSubscription { SubscriptionId = base.subscriptionId }, }; // Switch existing website cmdlet.ExecuteCmdlet(); mockClient.Verify(c => c.GetSlotName("website1(staging)"), Times.Once()); mockClient.Verify(c => c.GetSlotName("website1"), Times.Once()); }
protected override void ExecuteCmdlet() { if (ParameterSetName == ParamSet_ById) { HubSiteProperties sourceProperties = Tenant.GetHubSitePropertiesById(Source); ClientContext.Load(sourceProperties); sourceProperties.ParentHubSiteId = Target; sourceProperties.Update(); ClientContext.ExecuteQueryRetry(); } else { SiteProperties sourceSiteProperties = Tenant.GetSitePropertiesByUrl(SourceUrl, true); ClientContext.Load(sourceSiteProperties); ClientContext.ExecuteQueryRetry(); SiteProperties destSiteProperties = Tenant.GetSitePropertiesByUrl(TargetUrl, true); ClientContext.Load(destSiteProperties); ClientContext.ExecuteQueryRetry(); if (!sourceSiteProperties.IsHubSite) { throw new PSInvalidOperationException("Source site collection needs to be a Hub site."); } if (!destSiteProperties.IsHubSite) { throw new PSInvalidOperationException("Destination site collection needs to be a Hub site."); } HubSiteProperties sourceProperties = Tenant.GetHubSitePropertiesByUrl(SourceUrl); ClientContext.Load(sourceProperties); Microsoft.SharePoint.Client.Site targetSite = Tenant.GetSiteByUrl(TargetUrl); ClientContext.Load(targetSite); ClientContext.ExecuteQueryRetry(); sourceProperties.ParentHubSiteId = targetSite.HubSiteId; sourceProperties.Update(); ClientContext.ExecuteQueryRetry(); } }
public bool IsSiteCollectionExternalSharingEnabled(string _inputSiteCollectionUrl) { bool isSiteCollectionExternalShaingEnabled = false; string siteCollectionUrl = SPOAdminURL; string message = string.Empty; ClientContext clientContext; try { using (clientContext = GetClientContext(siteCollectionUrl, clientID, clientSecret)) { clientContext.ExecuteQuery(); Tenant currentO365Tenant = new Tenant(clientContext); clientContext.Load(currentO365Tenant, O365t => O365t.SharingCapability); clientContext.ExecuteQuery(); SiteProperties _siteprops = currentO365Tenant.GetSitePropertiesByUrl(_inputSiteCollectionUrl, true); clientContext.Load(_siteprops); clientContext.ExecuteQuery(); var _currentShareSettings = _siteprops.SharingCapability; if (_currentShareSettings == SharingCapabilities.Disabled) { isSiteCollectionExternalShaingEnabled = false; } else { isSiteCollectionExternalShaingEnabled = true; } } } catch (Exception ex) { message = ex.Message; } return(isSiteCollectionExternalShaingEnabled); }
/// <summary> /// the following code uses tenant admin rights to get information from the Tenant API. /// this requires a tenatn administrator to trust the app /// </summary> /// <param name="siteCollectionUrl">The Url of the site collection for information</param> private void GetTenantInformation(string siteCollectionUrl) { string tenantName = ConfigurationManager.AppSettings["TenantName"]; Uri tenantAdminUri = new Uri(string.Format("https://{0}-admin.sharepoint.com", tenantName)); string adminRealm = TokenHelper.GetRealmFromTargetUrl(tenantAdminUri); string adminToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, tenantAdminUri.Authority, adminRealm).AccessToken; //tenant app-only context to admin site collection using (var clientContext = TokenHelper.GetClientContextWithAccessToken(tenantAdminUri.ToString(), adminToken)) { var tenant = new Tenant(clientContext); clientContext.Load(tenant); clientContext.ExecuteQuery(); SiteProperties properties = tenant.GetSitePropertiesByUrl(siteCollectionUrl, true); clientContext.Load(properties); clientContext.ExecuteQuery(); lblLastModified.Text = properties.LastContentModifiedDate.ToString(); lblWebsCount.Text = properties.WebsCount.ToString(); } }
public bool IsSiteCollectionStorageQuotaUpdated(string _strURL, int _intNewQuota) { bool isStorageUpdated = false; string siteCollectionUrl = SPOAdminURL; try { ClientContext clientContext; using (clientContext = GetClientContext(siteCollectionUrl, clientID, clientSecret)) { clientContext.ExecuteQuery(); Tenant currentO365Tenant = new Tenant(clientContext); clientContext.ExecuteQuery(); SiteProperties propertyColl = currentO365Tenant.GetSitePropertiesByUrl(_strURL, true); if (propertyColl != null) { clientContext.Load(propertyColl); clientContext.ExecuteQuery(); //propertyColl.Title += "_storage Updated By Bot"; propertyColl.StorageMaximumLevel += (_intNewQuota * 1024); propertyColl.Update(); clientContext.Load(propertyColl); clientContext.ExecuteQuery(); isStorageUpdated = true; } } } catch (Exception ex) { isStorageUpdated = false; } return(isStorageUpdated); }
/// <summary> /// /// </summary> /// <param name="siteInfo"></param> public override void SetExternalSharing(SiteInformation siteInfo) { UsingContext(ctx => { try { Tenant _tenant = new Tenant(ctx); SiteProperties _siteProps = _tenant.GetSitePropertiesByUrl(siteInfo.Url, false); ctx.Load(_tenant); ctx.Load(_siteProps); ctx.ExecuteQuery(); bool _shouldBeUpdated = false; var _tenantSharingCapability = _tenant.SharingCapability; var _siteSharingCapability = _siteProps.SharingCapability; var _targetSharingCapability = SharingCapabilities.Disabled; if (siteInfo.EnableExternalSharing && _tenantSharingCapability != SharingCapabilities.Disabled) { _targetSharingCapability = SharingCapabilities.ExternalUserSharingOnly; _shouldBeUpdated = true; } if (_siteSharingCapability != _targetSharingCapability && _shouldBeUpdated) { _siteProps.SharingCapability = _targetSharingCapability; _siteProps.Update(); ctx.ExecuteQuery(); Log.Info("Provisioning.Common.Office365SiteProvisioningService.SetExternalSharing", PCResources.ExternalSharing_Successful, siteInfo.Url); } } catch (Exception _ex) { Log.Info("Provisioning.Common.Office365SiteProvisioningService.SetExternalSharing", PCResources.ExternalSharing_Exception, siteInfo.Url, _ex); } }); }
/// <summary> /// Load the latest site collection status from SharePoint /// </summary> /// <param name="e">Timer job event arguments</param> /// <param name="tenant">The tenant object</param> /// <param name="site">The site object</param> /// <param name="properties">The site properties object</param> private void LoadSiteStatus(TimerJobRunEventArgs e, out Tenant tenant, out Site site, out SiteProperties properties) { var tenantClientContext = e.TenantClientContext; Log.Info(base.Name, TimerJobsResources.SynchJob_GetSiteStatus, e.Url); tenant = new Tenant(tenantClientContext); site = tenant.GetSiteByUrl(e.Url); properties = tenant.GetSitePropertiesByUrl(e.Url, includeDetail: false); tenantClientContext.Load(tenant, t => t.SharingCapability); tenantClientContext.Load(site, s => s.RootWeb.Title, s => s.RootWeb.Description, s => s.RootWeb.Language, s => s.RootWeb.Created, s => s.Id); tenantClientContext.Load(properties, s => s.StorageMaximumLevel, s => s.StorageWarningLevel, s => s.UserCodeMaximumLevel, s => s.UserCodeWarningLevel, s => s.TimeZoneId, s => s.SharingCapability); tenantClientContext.ExecuteQueryRetry(); }
public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "havePermission")] HttpRequestMessage req, TraceWriter log) { try { // Gets data from request body. dynamic data = await req.Content.ReadAsAsync <object>(); string siteUrl = data.SiteUrl; //test comment string currentEmail = data.CurrentUser_EmailAddress; if (String.IsNullOrEmpty(siteUrl) || String.IsNullOrEmpty(currentEmail)) { return(req.CreateResponse(HttpStatusCode.BadRequest, "Please pass parametes site URL and Email Address in request body!")); } // Fetches client id and client secret from app settings. string clientId = Environment.GetEnvironmentVariable("ClientId", EnvironmentVariableTarget.Process); string clientSecret = Environment.GetEnvironmentVariable("ClientSecret", EnvironmentVariableTarget.Process); string urlAdminSite = Environment.GetEnvironmentVariable("UrlAdminSite", EnvironmentVariableTarget.Process); // Obtains client context using the client id and client secret. var ctx = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(urlAdminSite, clientId, clientSecret); Tenant tenant = new Tenant(ctx); SiteProperties siteProp = tenant.GetSitePropertiesByUrl(siteUrl, true); Site site = tenant.GetSiteByUrl(siteUrl); Web web = site.RootWeb; RoleAssignmentCollection roleAssignments = web.RoleAssignments; //Get the current user by email address. User currentUser = web.EnsureUser(currentEmail); ctx.Load(site, s => s.RootWeb, s => s.RootWeb.CurrentUser); ctx.Load(siteProp); ctx.Load(currentUser); ctx.Load(web, w => w.CurrentUser, w => w.SiteGroups, w => w.Url, w => w.Title); ctx.Load(roleAssignments, roleAssignement => roleAssignement.Include(r => r.Member, r => r.RoleDefinitionBindings)); ctx.ExecuteQuery(); var allowedListDomainFromSite = siteProp.SharingAllowedDomainList.Split(',').Select(x => x.Trim().ToUpper()).ToList(); if (!siteProp.SharingCapability.ToString().Equals("Disabled")) { if (allowedListDomainFromSite.Count() != 0) { if (currentUser.IsSiteAdmin || CheckUserInAdminGroups(ctx, web, roleAssignments, currentUser)) // check if the current user have full control { return(req.CreateResponse(HttpStatusCode.OK, true)); } } } else { return(req.CreateResponse(HttpStatusCode.OK, false)); } return(req.CreateResponse(HttpStatusCode.OK, false)); } catch (Exception e) { return(req.CreateResponse(HttpStatusCode.InternalServerError, e.Message)); } }
private void ValidateExternalUsersTimerJob_TimerJobRun(object sender, TimerJobRunEventArgs e) { Console.WriteLine("Starting job"); var web = e.SiteClientContext.Web; Tenant tenant = new Tenant(e.TenantClientContext); var siteAdmins = e.SiteClientContext.LoadQuery(web.SiteUsers.Include(u => u.Email).Where(u => u.IsSiteAdmin)); e.SiteClientContext.ExecuteQueryRetry(); List <string> adminEmails = new List <string>(); foreach (var siteAdmin in siteAdmins) { adminEmails.Add(siteAdmin.Email); } SiteProperties p = tenant.GetSitePropertiesByUrl(e.SiteClientContext.Url, true); var sharingCapability = p.EnsureProperty(s => s.SharingCapability); if (sharingCapability != Microsoft.Online.SharePoint.TenantManagement.SharingCapabilities.Disabled) { DateTime checkDate = DateTime.Now; var lastCheckDate = e.WebClientContext.Web.GetPropertyBagValueString(PNPCHECKDATEPROPERTYBAGKEY, string.Empty); if (lastCheckDate == string.Empty) { // new site. Temporary set the check date to less than one Month checkDate = checkDate.AddMonths(-2); } else { if (!DateTime.TryParse(lastCheckDate, out checkDate)) { // Something went wrong with trying to parse the date in the propertybag. Do the check anyway. checkDate = checkDate.AddMonths(-2); } } if (checkDate.AddMonths(1) < DateTime.Now) { e.SiteClientContext.Web.EnsureProperty(w => w.Url); e.WebClientContext.Web.EnsureProperty(w => w.Url); EmailProperties mailProps = new EmailProperties(); mailProps.Subject = "Review required: external users with access to your site"; StringBuilder bodyBuilder = new StringBuilder(); bodyBuilder.AppendFormat("<html><head>{0}</head><body style=\"font-family:sans-serif\">", CSSSTYLE); bodyBuilder.AppendFormat("<p>Your site with address {0} has one or more external users registered. Please review the following list and take appropriate action if such access is not wanted anymore for a user.</p>", e.SiteClientContext.Web.Url); bodyBuilder.Append("<table class=\"tg\"><tr><th>Name</th><th>Invited by</th><th>Created</th><th>Invited As</th><th>Accepted As</th></tr>"); var externalusers = e.TenantClientContext.Web.GetExternalUsersForSiteTenant(new Uri(e.WebClientContext.Web.Url)); if (externalusers.Any()) { foreach (var externalUser in externalusers) { bodyBuilder.AppendFormat("<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td></tr>", externalUser.DisplayName, externalUser.InvitedBy, externalUser.WhenCreated, externalUser.InvitedAs, externalUser.AcceptedAs); } bodyBuilder.Append("</table></body></html>"); mailProps.Body = bodyBuilder.ToString(); mailProps.To = adminEmails.ToArray(); Utility.SendEmail(e.SiteClientContext, mailProps); e.SiteClientContext.ExecuteQueryRetry(); } e.WebClientContext.Web.SetPropertyBagValue(PNPCHECKDATEPROPERTYBAGKEY, DateTime.Now.ToString()); } } Console.WriteLine("Ending job"); }
protected void btnSave_Click(object sender, EventArgs e) { siteURL = Page.Request["SPHostUrl"]; var spContext = SharePointContextProvider.Current.GetSharePointContext(Context); using (var clientContext = spContext.CreateUserClientContextForSPHost()) { clientContext.Load(clientContext.Site); clientContext.ExecuteQuery(); if (clientContext.Site.ShareByEmailEnabled) { initialSharingSetting = _shared; } else { initialSharingSetting = _notshared; } } try { if (rdbList.SelectedValue == "allowed" && initialSharingSetting == _notshared) { Log.LogFileSystem(string.Format("Start enabling external sharing...")); Log.LogFileSystem(string.Format("\t" + "Start getting Context...")); var ctx = GetContext(TenantAdminUrl); using (ctx) { Tenant _tenant = new Tenant(ctx); Log.LogFileSystem(string.Format("\t" + "Loading site properties...")); SiteProperties _siteProps = _tenant.GetSitePropertiesByUrl(siteURL, false); ctx.Load(_tenant); ctx.Load(_siteProps); ctx.ExecuteQuery(); bool _shouldBeUpdated = false; var _tenantSharingCapability = _tenant.SharingCapability; var _siteSharingCapability = _siteProps.SharingCapability; var _targetSharingCapability = SharingCapabilities.Disabled; //if (siteInfo.EnableExternalSharing && _tenantSharingCapability != SharingCapabilities.Disabled) //{ _targetSharingCapability = SharingCapabilities.ExternalUserSharingOnly; _shouldBeUpdated = true; //} if (_siteSharingCapability != _targetSharingCapability && _shouldBeUpdated) { Log.LogFileSystem(string.Format("\t" + "Enabling sharing setting...")); _siteProps.SharingCapability = _targetSharingCapability; ctx.Load(_siteProps); SpoOperation op = _siteProps.Update(); ctx.Load(op, i => i.IsComplete); ctx.ExecuteQuery(); while (!op.IsComplete) { Log.LogFileSystem(string.Format("\t" + "Refreshing update...")); //wait 30seconds and try again System.Threading.Thread.Sleep(3000); op.RefreshLoad(); ctx.ExecuteQuery(); } Log.LogFileSystem(string.Format("\t" + "Update completed!")); } } try { Log.LogFileSystem(string.Format("\t" + "Start enabling the banner...")); //Enable Banner var clientContextSC = GetContext(siteURL); using (clientContextSC) { Site site = clientContextSC.Site; clientContextSC.Load(site); clientContextSC.ExecuteQuery(); var existingActions = site.UserCustomActions; clientContextSC.Load(existingActions); clientContextSC.ExecuteQuery(); UserCustomAction targetAction = existingActions.Add(); targetAction.Name = "External_Sharing_Banner"; targetAction.Description = "External_Sharing_Banner"; targetAction.Location = "ScriptLink"; targetAction.ScriptBlock = "var headID = document.getElementsByTagName('head')[0]; var externalSharingTag = document.createElement('script'); externalSharingTag.type = 'text/javascript'; externalSharingTag.src = '" + JavaScriptFile + "';headID.appendChild(externalSharingTag);"; targetAction.ScriptSrc = ""; targetAction.Update(); clientContextSC.ExecuteQuery(); Log.LogFileSystem(string.Format("\t" + "Banner successfully enabled!")); EventLog.WriteEntry(source, string.Format("Changing External Sharing Settings is completed successfully. The Site Collection is externally shared and the banner is enabled."), EventLogEntryType.Information, 6000); } } catch (Exception ex) { EventLog.WriteEntry(source, string.Format("Error occurred in changing External Sharing Settings. The error is {0}", ex.Message), EventLogEntryType.Error, 6001); } } else if (rdbList.SelectedValue == "notallowed" && initialSharingSetting == _shared) { Log.LogFileSystem(string.Format("Start disabling external sharing...")); Log.LogFileSystem(string.Format("\t" + "Start getting Context...")); var ctx = GetContext(TenantAdminUrl); using (ctx) { Tenant _tenant = new Tenant(ctx); Log.LogFileSystem(string.Format("\t" + "Loading site properties...")); SiteProperties _siteProps = _tenant.GetSitePropertiesByUrl(siteURL, false); ctx.Load(_tenant); ctx.Load(_siteProps); ctx.ExecuteQuery(); bool _shouldBeUpdated = false; var _tenantSharingCapability = _tenant.SharingCapability; var _siteSharingCapability = _siteProps.SharingCapability; var _targetSharingCapability = SharingCapabilities.Disabled; _targetSharingCapability = SharingCapabilities.Disabled; _shouldBeUpdated = true; if (_siteSharingCapability != _targetSharingCapability && _shouldBeUpdated) { Log.LogFileSystem(string.Format("\t" + "Disabling sharing setting...")); _siteProps.SharingCapability = _targetSharingCapability; ctx.Load(_siteProps); SpoOperation op = _siteProps.Update(); ctx.Load(op, i => i.IsComplete); ctx.ExecuteQuery(); while (!op.IsComplete) { Log.LogFileSystem(string.Format("\t" + "Refreshing update...")); //wait 30seconds and try again System.Threading.Thread.Sleep(3000); op.RefreshLoad(); ctx.ExecuteQuery(); } } } try { Log.LogFileSystem(string.Format("\t" + "Start disabling the banner...")); //Disable Banner var clientContextSC = GetContext(siteURL); using (clientContextSC) { Site site = clientContextSC.Site; clientContextSC.Load(site); clientContextSC.ExecuteQuery(); var existingActions = site.UserCustomActions; clientContextSC.Load(existingActions); clientContextSC.ExecuteQuery(); var actions = existingActions.ToArray(); foreach (var action in actions) { if (action.Name == "External_Sharing_Banner" && action.Location == "ScriptLink") { action.DeleteObject(); clientContextSC.ExecuteQuery(); Log.LogFileSystem(string.Format("\t" + "Banner successfully disabled!")); break; } } } EventLog.WriteEntry(source, string.Format("Changing External Sharing Settings is completed successfully. The Site Collection is not externally shared and the banner is disabled."), EventLogEntryType.Information, 6000); } catch (Exception ex) { EventLog.WriteEntry(source, string.Format("Error occurred in changing External Sharing Settings. The error is {0}", ex.Message), EventLogEntryType.Error, 6001); } } Log.LogFileSystem(string.Format(string.Format("External Sharing is now {0} ", rdbList.SelectedValue))); Log.LogFileSystem(string.Format("External Sharing setting is changed successfully for Site Collection - {0} ", Page.Request["SPHostUrl"])); Log.LogFileSystem(string.Empty); //Response.Redirect((string.IsNullOrEmpty(siteURL) ? Page.Request["SPHostUrl"] : siteURL) + "/_layouts/15/settings.aspx"); ScriptManager.RegisterStartupScript(this, this.GetType(), "successMessageBanner", "alert('External Sharing setting is changed successfully!!'); window.location='" + (string.IsNullOrEmpty(siteURL) ? Page.Request["SPHostUrl"] : siteURL) + "/_layouts/15/settings.aspx';", true); } catch (System.Threading.ThreadAbortException ex) { Response.Redirect((string.IsNullOrEmpty(siteURL) ? Page.Request["SPHostUrl"] : siteURL) + "/_layouts/15/settings.aspx", false); } catch (Exception ex) { Log.LogFileSystem(string.Format("Error occured in changing External Sharing Settings for Site Collection - {0}, error is {1} ", (string.IsNullOrEmpty(siteURL) ? Page.Request["SPHostUrl"] : siteURL), ex.Message)); Log.LogFileSystem(string.Empty); EventLog.WriteEntry(source, string.Format("Error occured in changing External Sharing Settings. The error is {0}", ex.Message), EventLogEntryType.Error, 6001); ScriptManager.RegisterStartupScript(this, GetType(), "ErrorMessageBanner", "document.getElementById('spanErrorMsg').style.display = 'block';", true); ScriptManager.RegisterStartupScript(this, GetType(), "ErrorCursor", " document.body.style.cursor = 'default';", true); } }