private static void GetAllSiteCollections() { SPOSitePropertiesEnumerable prop = null; var password = new SecureString(); foreach (char c in "MyPassword".ToCharArray()) { password.AppendChar(c); } var credentials = new SharePointOnlineCredentials("*****@*****.**", password); var ctx = new ClientContext("https://MyTenant-admin.sharepoint.com/"); ctx.Credentials = credentials; Tenant tenant = new Tenant(ctx); prop = tenant.GetSiteProperties(0, true); ctx.Load(prop); ctx.ExecuteQuery(); foreach (SiteProperties sp in prop) { Console.WriteLine(sp.Title + " => " + sp.Url); Console.WriteLine("---------------------------"); } }
public IEnumerable <SiteCollection> GetAllSites() { SPOSitePropertiesEnumerable spp = null; int startIndex = 0; var sites = new List <SiteCollection>(); while (spp == null || spp.Count > 0) { spp = _tenant.GetSiteProperties(startIndex, true); _ctx.Load(spp); _ctx.ExecuteQuery(); foreach (SiteProperties sp in spp) { sites.Add(new SiteCollection() { Title = sp.Title, Url = sp.Url, Owner = sp.Owner }); } startIndex += spp.Count; } return(sites); }
/// <summary> /// Get Classic Site Collections from SharePoint Online Tenant /// </summary> /// <param name="siteUrl"></param> /// <param name="userName"></param> /// <param name="password"></param> private static void getClassicSiteCollections(string siteUrl, string userName, SecureString password) { var credentials = new SharePointOnlineCredentials(userName, password); ClientContext ctx = new ClientContext(siteUrl); ctx.Credentials = credentials; //ctx.ExecutingWebRequest Tenant tenant = new Tenant(ctx); //var ac = ctx.GetAccessToken(); // ctx.AuthenticationMode = ClientAuthenticationMode.FormsAuthentication; var authCookie = credentials.GetAuthenticationCookie(new Uri(siteUrl)); var headers = new Dictionary <string, string>() { { "Cookie", authCookie } }; var allSites = CallSharePointOnlineAPI($@"https://brgrp-admin.sharepoint.com/_vti_bin/client.svc/lists/GetByTitle('DO_NOT_DELETE_SPLIST_TENANTADMIN_AGGREGATED_SITECOLLECTIONS')/items?$top=10&$filter=IsGroupConnected", HttpMethod.Get, null, headers, null, null).GetAwaiter().GetResult(); SPOSitePropertiesEnumerable siteProps = tenant.GetSitePropertiesFromSharePoint("0", true); //tenant.LegacyAuthProtocolsEnabled = false; ctx.Load(siteProps); ctx.ExecuteQuery(); Console.WriteLine("*************************************************"); Console.WriteLine("Total Classic Collections: " + siteProps.Count.ToString()); foreach (var site in siteProps) { Console.WriteLine("{0} - {1}", site.Title, site.Template.ToString()); } }
private static void GetSiteCollections() { //Make sure to update the admin url and the credentials string adminCenterUrl = "https://mpcjellycode-admin.sharepoint.com/"; string userName = "******"; string password = "******"; ClientContext adminCtx = new ClientContext(adminCenterUrl); SecureString secureString = new SecureString(); password.ToList().ForEach(secureString.AppendChar); adminCtx.Credentials = new SharePointOnlineCredentials(userName, secureString); Tenant tenant = new Tenant(adminCtx); SPOSitePropertiesEnumerable props = tenant.GetSiteProperties(0, true); adminCtx.Load(props); adminCtx.ExecuteQuery(); if (props != null && props.Count > 0) { Console.WriteLine("TITLE \t URL \t COMPATIBILITY LEVEL"); foreach (SiteProperties prop in props) { Console.WriteLine(prop.Title + "\t" + prop.Url + "\t" + prop.CompatibilityLevel.ToString()); } } Console.ReadLine(); }
public List <SharePointItem> SiteCollections() { List <SharePointItem> results = new List <SharePointItem>(); SPOSitePropertiesEnumerable prop = null; string tenantAdminURL = @"https://dddevops-admin.sharepoint.com/"; using (ClientContext context = new ClientContext(tenantAdminURL)) { SecureString securePassword = new SecureString(); foreach (char c in password.ToCharArray()) { securePassword.AppendChar(c); } context.Credentials = new SharePointOnlineCredentials(username, securePassword); Tenant tenant = new Tenant(context); prop = tenant.GetSiteProperties(0, true); context.Load(prop); context.ExecuteQuery(); foreach (SiteProperties sp in prop) { SharePointItem item = new SharePointItem() { Title = sp.Title, URL = sp.Url }; results.Add(item); } } return(results); }
/// <summary> /// Action for this SharePoint tenant /// </summary> public override void Process() { RunningManager.Logger.Debug($"TenantRunner Process() - {ActiveReceivers.Count} active receivers"); Context.Load(Element, t => t.RootSiteUrl); Context.ExecuteQuery(); RunningManager.Logger.Debug($"Tenant | URL: {Element.RootSiteUrl}"); // OnTenantRunningStart RunningManager.Logger.Debug("TenantRunner OnTenantRunningStart()"); ActiveReceivers.ForEach(r => r.OnTenantRunningStart(Element)); // If at least one receiver run term stores or deeper if (Manager.Receivers.Any(r => r.IsReceiverCalledOrDeeper(RunningLevel.TermStore))) { // Open taxonomy session TaxonomySession taxSession = TaxonomySession.GetTaxonomySession(Context); // Crawl term stores Context.Load(taxSession, s => s.TermStores); Context.ExecuteQuery(); List <TermStoreRunner> termStoreRunners = new List <TermStoreRunner>(); foreach (TermStore store in taxSession.TermStores) { termStoreRunners.Add(new TermStoreRunner(Manager, Context, store)); } termStoreRunners.ForEach(r => r.Process()); } // If at least one receiver run site collections or deeper if (Manager.Receivers.Any(r => r.IsReceiverCalledOrDeeper(RunningLevel.SiteCollection))) { // Get site collections URLs SPOSitePropertiesEnumerable properties = Element.GetSiteProperties(0, true); Context.Load(properties); Context.ExecuteQuery(); // Crawl among site collections List <string> siteCollectionUrls = properties.Select(p => p.Url).ToList(); List <SiteCollectionRunner> siteCollectionRunners = new List <SiteCollectionRunner>(); foreach (string siteCollectionUrl in siteCollectionUrls) { ClientContext ctx = new ClientContext(siteCollectionUrl) { Credentials = Context.Credentials }; siteCollectionRunners.Add(new SiteCollectionRunner(Manager, ctx, ctx.Site)); } siteCollectionRunners.ForEach(r => r.Process()); } // OnTenantRunningEnd RunningManager.Logger.Debug("TenantRunner OnTenantRunningEnd()"); ActiveReceivers.ForEach(r => r.OnTenantRunningEnd(Element)); }
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); }
/// <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); } }
/// <summary> /// Returns all site collections in the tenant /// </summary> /// <param name="includeProperties">Include all Site Collection properties</param> /// <returns></returns> public static List <SPOSiteCollectionModel> GetSPOSiteCollections(this Tenant tenantContext, bool includeProperties = false) { int startIndex = 0; var urls = new List <SPOSiteCollectionModel>(); SPOSitePropertiesEnumerable spenumerable = null; while (spenumerable == null || spenumerable.Count > 0) { spenumerable = tenantContext.GetSiteProperties(startIndex, includeProperties); tenantContext.Context.Load(spenumerable); tenantContext.Context.ExecuteQueryRetry(); foreach (SiteProperties sp in spenumerable) { SPOSiteCollectionModel model = null; if (includeProperties) { model = new SPOSiteCollectionModel() { Url = sp.Url.EnsureTrailingSlashLowered(), Title = sp.Title, Sandbox = sp.SandboxedCodeActivationCapability, AverageResourceUsage = sp.AverageResourceUsage, CompatibilityLevel = sp.CompatibilityLevel, CurrentResourceUsage = sp.CurrentResourceUsage, DenyAddAndCustomizePages = sp.DenyAddAndCustomizePages, DisableCompanyWideSharingLinks = sp.DisableCompanyWideSharingLinks, LastContentModifiedDate = sp.LastContentModifiedDate, Owner = sp.Owner, SharingCapability = sp.SharingCapability, Status = sp.Status, StorageMaximumLevel = sp.StorageMaximumLevel, StorageQuotaType = sp.StorageQuotaType, StorageUsage = sp.StorageUsage, StorageWarningLevel = sp.StorageWarningLevel, TimeZoneId = sp.TimeZoneId, WebsCount = sp.WebsCount, Template = sp.Template, UserCodeWarningLevel = sp.UserCodeWarningLevel, UserCodeMaximumLevel = sp.UserCodeMaximumLevel }; } else { model = new SPOSiteCollectionModel() { Url = sp.Url.EnsureTrailingSlashLowered(), Title = sp.Title }; } urls.Add(model); } startIndex += spenumerable.Count; } return(urls); }
protected override void ExecuteCmdlet() { if (SPOnlineConnection.CurrentConnection.ConnectionType == ConnectionType.OnPrem) { WriteObject(ClientContext.Site); } else { if (!string.IsNullOrEmpty(Url)) { var list = Tenant.GetSitePropertiesByUrl(Url, Detailed); list.Context.Load(list); list.Context.ExecuteQueryRetry(); WriteObject(list, true); } else { SPOSitePropertiesEnumerableFilter filter = null; if (IncludeOneDriveSites || WebTemplate != null || Filter != null) { filter = new SPOSitePropertiesEnumerableFilter() { IncludePersonalSite = IncludeOneDriveSites.IsPresent ? PersonalSiteFilter.Include : PersonalSiteFilter.UseServerDefault, StartIndex = "0", IncludeDetail = Detailed, Template = WebTemplate, Filter = Filter, }; } SPOSitePropertiesEnumerable list = null; var sites = new List <SiteProperties>(); do { list = filter == null?Tenant.GetSiteProperties(list?.NextStartIndex ?? 0, Detailed) : Tenant.GetSitePropertiesFromSharePointByFilters(filter); Tenant.Context.Load(list); Tenant.Context.ExecuteQueryRetry(); sites.AddRange(list.ToList()); if (filter != null) { filter.StartIndex = list.NextStartIndex.ToString(); } } while (list.NextStartIndex > 0); if (Template != null) { WriteObject(sites.Where(t => t.Template == Template).OrderBy(x => x.Url), true); } else { WriteObject(sites.OrderBy(x => x.Url), true); } } } }
protected override void ExecuteCmdlet() { if (!string.IsNullOrEmpty(Url)) { var list = Tenant.GetSitePropertiesByUrl(Url, Detailed); list.Context.Load(list); list.Context.ExecuteQueryRetry(); WriteObject(list, true); } else { #if !ONPREMISES SPOSitePropertiesEnumerableFilter filter = new SPOSitePropertiesEnumerableFilter() { IncludePersonalSite = IncludeOneDriveSites.IsPresent ? PersonalSiteFilter.Include : PersonalSiteFilter.UseServerDefault, IncludeDetail = Detailed, #pragma warning disable CS0618 // Type or member is obsolete Template = Template ?? WebTemplate, #pragma warning restore CS0618 // Type or member is obsolete Filter = Filter, }; #endif SPOSitePropertiesEnumerable sitesList = null; var sites = new List <SiteProperties>(); #if !ONPREMISES do { sitesList = Tenant.GetSitePropertiesFromSharePointByFilters(filter); Tenant.Context.Load(sitesList); Tenant.Context.ExecuteQueryRetry(); sites.AddRange(sitesList.ToList()); filter.StartIndex = sitesList.NextStartIndexFromSharePoint; } while (!string.IsNullOrWhiteSpace(sitesList.NextStartIndexFromSharePoint)); #else sitesList = Tenant.GetSiteProperties(0, Detailed); Tenant.Context.Load(sitesList); Tenant.Context.ExecuteQueryRetry(); sites.AddRange(sitesList.ToList()); #endif #if !ONPREMISES if (Template != null) { WriteObject(sites.Where(t => t.Template == Template).OrderBy(x => x.Url), true); } else { WriteObject(sites.OrderBy(x => x.Url), true); } #else WriteObject(sites.OrderBy(x => x.Url), true); #endif } }
protected override void ExecuteCmdlet() { if (!string.IsNullOrEmpty(Url)) { var siteProperties = Tenant.GetSitePropertiesByUrl(Url, Detailed); ClientContext.Load(siteProperties); ClientContext.ExecuteQueryRetry(); Model.SPOSite site = null; if (ParameterSpecified(nameof(DisableSharingForNonOwnersStatus))) { var office365Tenant = new Office365Tenant(ClientContext); var clientResult = office365Tenant.IsSharingDisabledForNonOwnersOfSite(Url); ClientContext.ExecuteQuery(); site = new Model.SPOSite(siteProperties, clientResult.Value); } else { site = new Model.SPOSite(siteProperties, null); } WriteObject(site, true); } else { SPOSitePropertiesEnumerableFilter filter = new SPOSitePropertiesEnumerableFilter() { IncludePersonalSite = IncludeOneDriveSites.IsPresent ? PersonalSiteFilter.Include : PersonalSiteFilter.UseServerDefault, IncludeDetail = Detailed, #pragma warning disable CS0618 // Type or member is obsolete Template = Template, #pragma warning restore CS0618 // Type or member is obsolete Filter = Filter, }; SPOSitePropertiesEnumerable sitesList = null; var sites = new List <SiteProperties>(); do { sitesList = Tenant.GetSitePropertiesFromSharePointByFilters(filter); Tenant.Context.Load(sitesList); Tenant.Context.ExecuteQueryRetry(); sites.AddRange(sitesList.ToList()); filter.StartIndex = sitesList.NextStartIndexFromSharePoint; } while (!string.IsNullOrWhiteSpace(sitesList.NextStartIndexFromSharePoint)); if (Template != null) { WriteObject(sites.Where(t => t.Template == Template).OrderBy(x => x.Url), true); } else { WriteObject(sites.OrderBy(x => x.Url), true); } } }
/// <summary> /// Returns all site collections in the current Tenant based on a startIndex. IncludeDetail adds additional properties to the SPSite object. EndIndex is the maximum number based on chunkcs of 300. /// </summary> /// <param name="tenant">Tenant object to operate against</param> /// <param name="startIndex">Start getting site collections from this index. Defaults to 0</param> /// <param name="endIndex">The index of the last site. Defaults to 100.000</param> /// <param name="includeDetail">Option to return a limited set of data</param> /// <returns>An IList of SiteEntity objects</returns> public static IList <SiteEntity> GetSiteCollections(this Tenant tenant, int startIndex = 0, int endIndex = 500000, bool includeDetail = true, bool includeOD4BSites = false) { var sites = new List <SiteEntity>(); SPOSitePropertiesEnumerable props = null; while (props == null || !string.IsNullOrEmpty(props.NextStartIndexFromSharePoint)) { // approach to be used as of Feb 2017 SPOSitePropertiesEnumerableFilter filter = new SPOSitePropertiesEnumerableFilter() { IncludePersonalSite = includeOD4BSites ? PersonalSiteFilter.Include : PersonalSiteFilter.UseServerDefault, StartIndex = props == null ? null : props.NextStartIndexFromSharePoint, IncludeDetail = includeDetail }; props = tenant.GetSitePropertiesFromSharePointByFilters(filter); // Previous approach, being replaced by GetSitePropertiesFromSharePointByFilters which also allows to fetch OD4B sites //props = tenant.GetSitePropertiesFromSharePoint(props == null ? null : props.NextStartIndexFromSharePoint, includeDetail); tenant.Context.Load(props); tenant.Context.ExecuteQueryRetry(); foreach (var prop in props) { var siteEntity = new SiteEntity(); siteEntity.Lcid = prop.Lcid; siteEntity.SiteOwnerLogin = prop.Owner; siteEntity.StorageMaximumLevel = prop.StorageMaximumLevel; siteEntity.StorageWarningLevel = prop.StorageWarningLevel; siteEntity.Template = prop.Template; siteEntity.TimeZoneId = prop.TimeZoneId; siteEntity.Title = prop.Title; siteEntity.Url = prop.Url; siteEntity.UserCodeMaximumLevel = prop.UserCodeMaximumLevel; siteEntity.UserCodeWarningLevel = prop.UserCodeWarningLevel; siteEntity.CurrentResourceUsage = prop.CurrentResourceUsage; siteEntity.LastContentModifiedDate = prop.LastContentModifiedDate; siteEntity.StorageUsage = prop.StorageUsage; siteEntity.WebsCount = prop.WebsCount; SiteLockState lockState; if (Enum.TryParse(prop.LockState, out lockState)) { siteEntity.LockState = lockState; } sites.Add(siteEntity); } Console.WriteLine(props.NextStartIndexFromSharePoint); Console.WriteLine($"Added {props.Count} sites, total sites to scan is now {sites.Count}"); } return(sites); }
/// <summary> /// Get the site collections for ONE location in a Multi-Geo tenant /// </summary> /// <param name="tenant">Tenant instance</param> /// <param name="startIndex">Start from </param> /// <param name="endIndex">End at</param> /// <param name="includeDetail">Also retrieve details</param> /// <param name="includeOD4BSites">Also retrieve OD4B sites</param> /// <param name="geoLocation">Geo location for which we're retrieving site collections</param> /// <returns></returns> public IList <GeoSites> GetSiteCollectionsInGeo(Tenant tenant, int startIndex = 0, int endIndex = 500000, bool includeDetail = true, bool includeOD4BSites = false, string geoLocation = null) { var sites = new List <GeoSites>(); SPOSitePropertiesEnumerable props = null; while (props == null || props.NextStartIndexFromSharePoint != null) { // approach to be used as of Feb 2017 SPOSitePropertiesEnumerableFilter filter = new SPOSitePropertiesEnumerableFilter() { IncludePersonalSite = includeOD4BSites ? PersonalSiteFilter.Include : PersonalSiteFilter.UseServerDefault, StartIndex = props == null ? null : props.NextStartIndexFromSharePoint, IncludeDetail = includeDetail }; props = tenant.GetSitePropertiesFromSharePointByFilters(filter); tenant.Context.Load(props); tenant.Context.ExecuteQuery(); foreach (var prop in props) { var siteEntity = new GeoSites() { GeoLocation = geoLocation, Lcid = prop.Lcid, SiteOwnerLogin = prop.Owner, StorageMaximumLevel = prop.StorageMaximumLevel, StorageWarningLevel = prop.StorageWarningLevel, Template = prop.Template, TimeZoneId = prop.TimeZoneId, Title = prop.Title, Url = prop.Url, UserCodeMaximumLevel = prop.UserCodeMaximumLevel, UserCodeWarningLevel = prop.UserCodeWarningLevel, CurrentResourceUsage = prop.CurrentResourceUsage, LastContentModifiedDate = prop.LastContentModifiedDate, StorageUsage = prop.StorageUsage, WebsCount = prop.WebsCount }; SiteLockState lockState; if (Enum.TryParse(prop.LockState, out lockState)) { siteEntity.LockState = lockState; } sites.Add(siteEntity); } } return(sites); }
/// <summary> /// Returns all site collections in the current Tenant based on a startIndex. IncludeDetail adds additional properties to the SPSite object. /// </summary> /// <param name="tenant">Tenant object to operate against</param> /// <param name="startIndex">Not relevant anymore</param> /// <param name="endIndex">Not relevant anymore</param> /// <param name="includeDetail">Option to return a limited set of data</param> /// <returns>An IList of SiteEntity objects</returns> public static IList <SiteEntity> GetSiteCollections(this Tenant tenant, int startIndex = 0, int endIndex = 500000, bool includeDetail = true, bool includeOD4BSites = false) { var sites = new List <SiteEntity>(); SPOSitePropertiesEnumerable props = null; while (props == null || props.NextStartIndexFromSharePoint != null) //while (props == null || props.NextStartIndex > -1) { SPOSitePropertiesEnumerableFilter filter = new SPOSitePropertiesEnumerableFilter() { IncludePersonalSite = includeOD4BSites ? PersonalSiteFilter.Include : PersonalSiteFilter.UseServerDefault, StartIndex = props == null ? null : props.NextStartIndexFromSharePoint, IncludeDetail = includeDetail }; //props = tenant.GetSitePropertiesFromSharePointByFilters(filter); props = tenant.GetSitePropertiesFromSharePoint(props == null?null:props.NextStartIndexFromSharePoint, includeDetail); //props = tenant.GetSiteProperties(props == null ? 0 : props.NextStartIndex, includeDetail); tenant.Context.Load(props); tenant.Context.ExecuteQueryRetry(); foreach (var prop in props) { var siteEntity = new SiteEntity(); siteEntity.Lcid = prop.Lcid; siteEntity.SiteOwnerLogin = prop.Owner; siteEntity.StorageMaximumLevel = prop.StorageMaximumLevel; siteEntity.StorageWarningLevel = prop.StorageWarningLevel; siteEntity.Template = prop.Template; siteEntity.TimeZoneId = prop.TimeZoneId; siteEntity.Title = prop.Title; siteEntity.Url = prop.Url; siteEntity.UserCodeMaximumLevel = prop.UserCodeMaximumLevel; siteEntity.UserCodeWarningLevel = prop.UserCodeWarningLevel; siteEntity.CurrentResourceUsage = prop.CurrentResourceUsage; siteEntity.LastContentModifiedDate = prop.LastContentModifiedDate; siteEntity.StorageUsage = prop.StorageUsage; siteEntity.WebsCount = prop.WebsCount; var lockState = SiteLockState.Unlock; if (Enum.TryParse(prop.LockState, out lockState)) { siteEntity.LockState = lockState; } sites.Add(siteEntity); } } return(sites); }
}// End Method // Method - Refresh.onClick() - Call for showsite private void RefreshSites(object sender, RoutedEventArgs e) { SPOLogic sp = new SPOLogic(CredManager); // Task - SetTenantProps and show sites Task.Factory.StartNew(() => { this.TenantProp = sp.getTenantProp(CredManager); ShowSites(); }); //Clear Ui TBOut.Content = ""; SiteView.Items.Clear(); }// End Method
public bool SiteURLAlreadyInUse(ClientContext adminCtx, string fullSiteUrl) { var tenant = new Tenant(adminCtx); SPOSitePropertiesEnumerable spp = tenant.GetSiteProperties(0, true); adminCtx.Load(spp); adminCtx.ExecuteQuery(); foreach (SiteProperties sp in spp) { if (sp.Url.ToLowerInvariant() == fullSiteUrl.ToLowerInvariant()) { return(true); } } return(false); }
//gavdcodeend 02 //gavdcodebegin 03 static void SpCsCsomReadAllSiteCollections(ClientContext spAdminCtx) { Tenant myTenant = new Tenant(spAdminCtx); myTenant.GetSiteProperties(0, true); SPOSitePropertiesEnumerable myProps = myTenant.GetSiteProperties(0, true); spAdminCtx.Load(myProps); spAdminCtx.ExecuteQuery(); foreach (var oneSiteColl in myProps) { Console.WriteLine(oneSiteColl.Title + " - " + oneSiteColl.Url); } }
/// <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); } }
protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { using (var ctx = GetAdminContext()) { // get site collections. Tenant tenant = new Tenant(ctx); SPOSitePropertiesEnumerable sites = tenant.GetSiteProperties(0, true); ctx.Load(tenant); ctx.Load(sites); ctx.ExecuteQuery(); SharingCapabilities tenantSharing = tenant.SharingCapability; switch (tenantSharing) { case SharingCapabilities.Disabled: lblStatus.Text = "External sharing is disabled at tenant level."; break; case SharingCapabilities.ExternalUserSharingOnly: lblStatus.Text = "External sharing at tenant level is set only for authenticated users."; break; case SharingCapabilities.ExternalUserAndGuestSharing: lblStatus.Text = "External sharing at tenant level is for authenticated and guest users."; break; default: break; } if (tenantSharing != SharingCapabilities.Disabled) { // List site collections foreach (var item in sites) { sitecollections.Items.Add(new System.Web.UI.WebControls.ListItem(item.Url, item.Url)); } } } } }
// Method - Returns tenantSiteProps public SPOSitePropertiesEnumerable getTenantProp(string Url) { try { ClientContext ctx = GetSiteContext(Url); Tenant tenant = new Tenant(ctx); SPOSitePropertiesEnumerable prop = tenant.GetSitePropertiesFromSharePoint("0", true); ctx.Load(prop); ctx.ExecuteQuery(); return(prop); } catch (IdcrlException) { MessageBox.Show("Wrong UserName and Password combination"); }catch (System.Exception ex) { MessageBox.Show(ex.Message); } return(null); }
/// <summary> /// Return SPOSites tenant wide /// </summary> /// <returns></returns> public SPOSitePropertiesEnumerable getTenantProp() { using (ClientContext ctx = new ClientContext(Url)) { try { ctx.Credentials = Credentials; Tenant tenant = new Tenant(ctx); SPOSitePropertiesEnumerable prop = tenant.GetSitePropertiesFromSharePoint("0", true); ctx.Load(prop); ctx.ExecuteQuery(); return(prop); } catch (System.Exception ex) { MessageBox.Show(ex.Message); new SigningScreen().Show(); } return(null); } }
/// <summary> /// Popullate treeview with SPOSite /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Window_Loaded(object sender, RoutedEventArgs e) { // Call the SPOLogic object SPOLogic sp = new SPOLogic(credential, tenantUrl); // Ask for Sites and loop SPOSitePropertiesEnumerable Tenant = sp.getTenantProp(); foreach (var site in Tenant) { var item = new TreeViewItem { Header = site.Url, Tag = site.Url, }; // Adding dumy item.items for expand icon to show item.Items.Add(null); // Listen out for item being expanded item.Expanded += Folder_Expanded; SiteView.Items.Add(item); } }
/// <summary> /// Get All ( Classic & Modern ) Site Collections from SharePoint Online Tenant /// </summary> /// <param name="siteUrl"></param> /// <param name="userName"></param> /// <param name="password"></param> private static void getAllSiteCollections(string siteUrl, string userName, SecureString password) { var credentials = new SharePointOnlineCredentials(userName, password); ClientContext ctx = new ClientContext(siteUrl); ctx.Credentials = credentials; Tenant tenant = new Tenant(ctx); SPOSitePropertiesEnumerable siteProps = tenant.GetSitePropertiesFromSharePoint("0", true); ctx.Load(siteProps); ctx.ExecuteQuery(); var authCookie = credentials.GetAuthenticationCookie(new Uri(siteUrl)); Console.WriteLine("*************************************************"); Console.WriteLine("Total Site Collections: " + siteProps.Count.ToString()); foreach (var site in siteProps) { Console.WriteLine("{0} - {1}", site.Title, site.Template.ToString()); } }
public static void UpdateQuotaWarningLevelBasedOnURL(string url) { try { TenentAdminSiteUrl = new Uri(Constants._strTenentAdminUrl); string realm = TokenHelper.GetRealmFromTargetUrl(TenentAdminSiteUrl); string accessToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, TenentAdminSiteUrl.Authority, realm).AccessToken; SPOSitePropertiesEnumerable prop = null; using (ClientContext ctx = TokenHelper.GetClientContextWithAccessToken(TenentAdminSiteUrl.ToString(), accessToken)) { Tenant tenant = new Tenant(ctx); string _strsites = url; int count = 0; if (_strsites.Contains(";")) { string[] sites = _strsites.Split(';'); foreach (string site in sites) { count++; Update(site, ctx, tenant, true, count, _intItemCount); } } else { Update(_strsites, ctx, tenant, true, 1, _intItemCount); } string LogFile = _strLogPath + "\\" + _strFileName; //UploadFiles(LogFile, _strFileName); } } catch (Exception ex) { //Logger.WriteLog(ex.ToString()); } }
public static void UpdateQuotaWarningLevel() { try { TenentAdminSiteUrl = new Uri(Constants._strTenentAdminUrl); string realm = TokenHelper.GetRealmFromTargetUrl(TenentAdminSiteUrl); string accessToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, TenentAdminSiteUrl.Authority, realm).AccessToken; SPOSitePropertiesEnumerable prop = null; using (ClientContext ctx = TokenHelper.GetClientContextWithAccessToken(TenentAdminSiteUrl.ToString(), accessToken)) { Tenant tenant = new Tenant(ctx); int startIndex = 0; while (prop == null || prop.Count > 0) { prop = tenant.GetSiteProperties(startIndex, true); ctx.Load(prop); ctx.ExecuteQuery(); int count = 0; foreach (SiteProperties sp in prop) { _intItemCount++; count++; Update(sp.Url, ctx, tenant, true, count, _intItemCount); } startIndex += prop.Count; } // Logger.WriteLog("================================== END ===================================="); string LogFile = _strLogPath + "\\" + _strFileName; //UploadFiles(LogFile, _strFileName); } } catch (Exception ex) { //Logger.WriteLog(ex.ToString()); } }
public Boolean check_site() { using (ClientContext tenantContext = new ClientContext(tenantAdminUri)) { SecureString password = new SecureString(); foreach (char c in userPassword.ToCharArray()) { password.AppendChar(c); } tenantContext.Credentials = new SharePointOnlineCredentials(userName, password); var tenant = new Tenant(tenantContext); SPOSitePropertiesEnumerable sitePropEnumerable = tenant.GetSiteProperties(0, true); tenantContext.Load(sitePropEnumerable); tenantContext.ExecuteQuery(); foreach (SiteProperties property in sitePropEnumerable) { if (property.Url.Equals(webUrl)) { return(true); } } return(false); } }
protected override void ExecuteCmdlet() { ClientContext.ExecuteQueryRetry(); if (ParameterSpecified(nameof(Identity))) { var siteProperties = Tenant.GetSitePropertiesByUrl(Identity.Url, Detailed); ClientContext.Load(siteProperties); ClientContext.ExecuteQueryRetry(); Model.SPOSite site = null; if (ParameterSpecified(nameof(DisableSharingForNonOwnersStatus))) { var office365Tenant = new Office365Tenant(ClientContext); var clientResult = office365Tenant.IsSharingDisabledForNonOwnersOfSite(Identity.Url); ClientContext.ExecuteQuery(); site = new Model.SPOSite(siteProperties, clientResult.Value); } else { site = new Model.SPOSite(siteProperties, null); } WriteObject(site, true); } else { SPOSitePropertiesEnumerableFilter filter = new SPOSitePropertiesEnumerableFilter() { IncludePersonalSite = IncludeOneDriveSites.IsPresent ? PersonalSiteFilter.Include : PersonalSiteFilter.UseServerDefault, IncludeDetail = Detailed, #pragma warning disable CS0618 // Type or member is obsolete Template = Template, #pragma warning restore CS0618 // Type or member is obsolete Filter = Filter, }; if (ClientContext.ServerVersion >= new Version(16, 0, 7708, 1200)) { if (ParameterSpecified(nameof(GroupIdDefined))) { filter.GroupIdDefined = GroupIdDefined.Value == true ? 1 : 2; } } else if (ParameterSpecified(nameof(GroupIdDefined))) { throw new PSArgumentException("Filtering by Group Id is not yet available for this tenant."); } SPOSitePropertiesEnumerable sitesList = null; var sites = new List <SiteProperties>(); do { sitesList = Tenant.GetSitePropertiesFromSharePointByFilters(filter); Tenant.Context.Load(sitesList); Tenant.Context.ExecuteQueryRetry(); sites.AddRange(sitesList.ToList()); filter.StartIndex = sitesList.NextStartIndexFromSharePoint; } while (!string.IsNullOrWhiteSpace(sitesList.NextStartIndexFromSharePoint)); if (Template != null) { WriteObject(sites.Where(t => t.Template == Template).OrderBy(x => x.Url).Select(s => new Model.SPOSite(s, null)), true); } else { WriteObject(sites.OrderBy(x => x.Url).Select(s => new Model.SPOSite(s, null)), true); } } }