public GetSharePointOnlineAuthenticatedContextTenant ( string siteUrl, string tenantUser, |
||
siteUrl | string | Site for which the ClientContext object will be instantiated |
tenantUser | string | User to be used to instantiate the ClientContext object |
tenantUserPassword | Password (SecureString) of the user used to instantiate the ClientContext object | |
Résultat | ClientContext |
static void Main(string[] args) { AuthenticationManager am = new AuthenticationManager(); ClientContext cc = am.GetSharePointOnlineAuthenticatedContextTenant("https://bertonline.sharepoint.com/sites/dev", "*****@*****.**", GetPassWord()); cc.Load(cc.Web.EventReceivers); cc.ExecuteQuery(); List<EventReceiverDefinition> rerToDelete = new List<EventReceiverDefinition>(); foreach (EventReceiverDefinition rer in cc.Web.EventReceivers) { Console.WriteLine(string.Format("Type:{0}, Url:{1}, Assembly:{2}, Class:{3}", rer.EventType, rer.ReceiverUrl, rer.ReceiverAssembly, rer.ReceiverClass)); if (rer.EventType == EventReceiverType.ListAdded && !String.IsNullOrEmpty(rer.ReceiverUrl)) { rerToDelete.Add(rer); } } Console.WriteLine("Cleanup old ListAdded event receivers"); foreach(EventReceiverDefinition rer in rerToDelete) { // this might fail for side loaded apps rer.DeleteObject(); } cc.ExecuteQuery(); }
public ClientContext GetContext(string url) { var authenticationManager = new AuthenticationManager(); var username = ConfigurationManager.AppSettings["SiteCollectionRequests_UserName"]; var password = ConfigurationManager.AppSettings["SiteCollectionRequests_Password"]; return authenticationManager.GetSharePointOnlineAuthenticatedContextTenant(url, username, password); }
public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Admin, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log) { dynamic data = await req.Content.ReadAsAsync <object>(); string SPParentSiteUrl = data["SPParentSiteUrl"]; string SPWebTemplate = data["SPWebTemplate"]; string SPSiteTitle = data["SPSiteTitle"]; string SPSiteDescription = data["SPSiteDescription"]; string SPSiteURL = data["SPSiteURL"]; int SPSiteLanguage = data["SPSiteLanguage"]; log.Info($"SPParentSiteUrl = '{SPParentSiteUrl}'"); log.Info($"SPWebTemplate = '{SPWebTemplate}'"); log.Info($"SPSiteTitle = '{SPSiteTitle}'"); log.Info($"SPSiteDescription = '{SPSiteDescription}'"); log.Info($"SPSiteURL = '{SPSiteURL}'"); log.Info($"SPSiteLanguage = '{SPSiteLanguage}'"); string userName = System.Environment.GetEnvironmentVariable("SPUser", EnvironmentVariableTarget.Process); string password = System.Environment.GetEnvironmentVariable("SPPwd", EnvironmentVariableTarget.Process); var authenticationManager = new PnPAuthenticationManager(); var clientContext = authenticationManager.GetSharePointOnlineAuthenticatedContextTenant(SPParentSiteUrl, userName, password); var pnpClientContext = PnPClientContext.ConvertFrom(clientContext); var webCreationInfo = new Microsoft.SharePoint.Client.WebCreationInformation(); webCreationInfo.WebTemplate = SPWebTemplate; webCreationInfo.Title = SPSiteTitle; webCreationInfo.Description = SPSiteDescription; webCreationInfo.Url = SPSiteURL; webCreationInfo.Language = SPSiteLanguage; pnpClientContext.Web.Webs.Add(webCreationInfo); pnpClientContext.ExecuteQuery(); return(req.CreateResponse(HttpStatusCode.OK, "request done")); }
public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log) { log.Info("C# HTTP trigger function processed a request."); if (adminPassword == null) { // This is the part where I grab the secret. var azureServiceTokenProvider = new AzureServiceTokenProvider(); log.Info("Getting the secret."); var kvClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback)); log.Info("KeyVaultSecret: " + Environment.GetEnvironmentVariable("KeyVaultSecret")); adminPassword = (await kvClient.GetSecretAsync(Environment.GetEnvironmentVariable("KeyVaultSecret"))).Value; } // parse query parameter string name = req.GetQueryNameValuePairs() .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0) .Value; // Get request body dynamic data = await req.Content.ReadAsAsync <object>(); // Set name to query string or body data name = name ?? data?.name; string title = data?.title; string siteUrl = string.Empty; string adminUser = Environment.GetEnvironmentVariable("spAdminUser"); log.Info("adminUser: "******"spSite"); log.Info("spSite: " + adminUser); System.Security.SecureString secureString = new System.Security.SecureString(); foreach (char ch in adminPassword) { secureString.AppendChar(ch); } string sitesRequest = Environment.GetEnvironmentVariable("listName"); log.Info("listName: " + sitesRequest); Dictionary <string, string> siteInfo = new Dictionary <string, string>(); OfficeDevPnP.Core.AuthenticationManager authManager = new OfficeDevPnP.Core.AuthenticationManager(); string camlQuery = "<View>" + "<Query>" + "<Where>" + "<Eq>" + "<FieldRef Name='Status' />" + "<Value Type='Choice'>Approved</Value>" + "</Eq>" + "</Where>" + "</Query>" + "<RowLimit>1</RowLimit>" + "</View>"; CamlQuery cq = new CamlQuery(); cq.ViewXml = camlQuery; using (var context = authManager.GetSharePointOnlineAuthenticatedContextTenant(spSite, adminUser, secureString)) { List list = context.Web.Lists.GetByTitle(sitesRequest); ListItemCollection lic = list.GetItems(cq); context.Load(lic); context.ExecuteQuery(); foreach (ListItem item in lic) { siteInfo.Add("Id", item["ID"].ToString()); siteInfo.Add("title", item["Title"].ToString()); siteInfo.Add("owner", item["Owner"].ToString()); siteInfo.Add("description", item["Description"] == null ? "" : item["Description"].ToString()); siteInfo.Add("type", item["SiteType"].ToString()); siteInfo.Add("alias", item["Alias"].ToString()); log.Info("Processing: " + item["Title"].ToString()); var siteType = siteInfo["type"]; switch (siteType.ToLower()) { case "communicationsite": var ctx = context.CreateSiteAsync(new CommunicationSiteCollectionCreationInformation { Title = siteInfo["title"].ToString(), Owner = siteInfo["owner"].ToString(), Lcid = 1033, Description = siteInfo["description"].ToString(), Url = spSite + "/sites/" + siteInfo["alias"].ToString(), }).GetAwaiter().GetResult(); // Add OWner User user = ctx.Web.EnsureUser(siteInfo["owner"].ToString()); ctx.Web.Context.Load(user); ctx.Web.Context.ExecuteQueryRetry(); ctx.Web.AssociatedOwnerGroup.Users.AddUser(user); ctx.Web.AssociatedOwnerGroup.Update(); ctx.Web.Context.ExecuteQueryRetry(); break; case "teamsite": var ctxTeamsite = context.CreateSiteAsync(new TeamSiteCollectionCreationInformation { DisplayName = siteInfo["title"].ToString(), Description = siteInfo["description"].ToString(), Alias = siteInfo["alias"].ToString(), IsPublic = false, }).GetAwaiter().GetResult(); siteUrl = ctxTeamsite.Url; // Add OWner User userTeamSite = ctxTeamsite.Web.EnsureUser(siteInfo["owner"].ToString()); ctxTeamsite.Web.Context.Load(userTeamSite); ctxTeamsite.Web.Context.ExecuteQueryRetry(); ctxTeamsite.Web.AssociatedOwnerGroup.Users.AddUser(userTeamSite); ctxTeamsite.Web.AssociatedOwnerGroup.Update(); ctxTeamsite.Web.Context.ExecuteQueryRetry(); break; case "teams": string token = Graph.getToken(); log.Info("Access Token: " + token); string userId = string.Empty; string groupId = string.Empty; if (string.IsNullOrEmpty(token) == false) { userId = Graph.getUser(token, siteInfo["owner"].ToString()); log.Info("userId: " + userId); } if (string.IsNullOrEmpty(userId) == false) { string dataPost = "{ 'displayName': '" + siteInfo["title"].ToString() + "', 'groupTypes': ['Unified'], 'mailEnabled': true, 'mailNickname': '" + siteInfo["alias"].ToString().Replace("\r\n", "").Replace(" ", "") + "', 'securityEnabled': false, '*****@*****.**': ['https://graph.microsoft.com/v1.0/users/" + userId + "'], 'visibility': 'Private' }"; groupId = Graph.createUnifiedGroup(token, dataPost); log.Info("groupId: " + groupId); log.Info("Creating team......"); string teamData = "{ \"memberSettings\": { \"allowCreateUpdateChannels\": true }, \"messagingSettings\": { \"allowUserEditMessages\": true, \"allowUserDeleteMessages\": true }, \"funSettings\": { \"allowGiphy\": true, \"giphyContentRating\": \"strict\" } }"; string team = Graph.createTeamFromUnifiedGroup(token, teamData, groupId); log.Info("team: " + team); //Graph.addOwnerToUnifiedGroup(token, groupId, userId); //removeOwnerToUnifiedGroup(token, groupId, userId); } siteUrl = siteInfo["title"].ToString(); log.Info("Teams ready: " + siteUrl); break; } // When the site or Teams has been created the status of the list item will change in ready if (siteUrl != string.Empty) { item["Status"] = "Ready"; item.Update(); context.ExecuteQuery(); } } } return(siteUrl == null ? req.CreateResponse(HttpStatusCode.InternalServerError, "Something went wrong!") : req.CreateResponse(HttpStatusCode.OK, siteUrl)); }
public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log) { string message = ""; List <string> keyPhrases = new List <string>(); string description = ""; // Get request body dynamic data = await req.Content.ReadAsAsync <object>(); string id = data.ID; log.Info("Document id: " + id); message += "Document id: " + id; OfficeDevPnP.Core.AuthenticationManager authManager = new OfficeDevPnP.Core.AuthenticationManager(); try { // Connects to SharePoint online site using (var ctx = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password)) { // List Name input // Retrieves list object using title List list = ctx.Site.RootWeb.GetListByTitle(listName); if (list != null) { // Returns required result ListItem li = list.GetItemById(id); ctx.Load(li); ctx.Load(li.File); ctx.ExecuteQuery(); ctx.ExecuteQuery(); // We CAN extract text out of most documents with the library, but for this demo I'm limiting our options to these 2 that I know to be working :) if (li.File.Name.IndexOf(".pdf") >= 0 || li.File.Name.IndexOf(".doc") >= 0) { li.File.OpenBinaryStream(); ctx.Load(li.File); ctx.ExecuteQuery(); log.Info("It was a valid file! Continuing into handling..."); try { log.Info("Got a file! Name: " + li.File.Name); var fileRef = li.File.ServerRelativeUrl; var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(ctx, fileRef); fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(ctx, fileRef); using (var ms = new MemoryStream()) { log.Info("Extracting text.."); fileInfo.Stream.CopyTo(ms); byte[] fileContents = ms.ToArray(); var extractor = new TikaOnDotNet.TextExtraction.TextExtractor(); var extractionResult = extractor.Extract(fileContents); string text = extractionResult.Text; List <MultiLanguageInput> analyzable = FormatAnalyzableText(ref text); log.Info("Formed altogether " + analyzable.Count + " sentences to analyze!"); int snippetEnd = 500 < text.Length ? 500 : text.Length; log.Info("Extracted text! First few rows here.. \r\n " + text.Substring(0, snippetEnd)); RunTextAnalysis(ref keyPhrases, analyzable, log); } log.Info("Found " + keyPhrases.Count + " key phrases! First 20 are here: "); foreach (var kp in keyPhrases.Take(20)) { log.Info(kp); } try { log.Info("Saving to SharePoint.."); TextInfo ti = new CultureInfo("en-US", false).TextInfo; li["Title"] = ti.ToTitleCase(li.File.Name); // then write the most important keyphrases back foreach (var s in keyPhrases.Take(keywordCount)) { description += s + "\r\n"; } li.Update(); try { ctx.Load(list.Fields); ctx.ExecuteQuery(); log.Info("Updating Managed Metadata..."); var fieldnames = new string[] { "Keywords" }; var field = list.GetFields(fieldnames).First(); // setting managed metadata log.Info("Updating keywords to taxonomy! Taking: " + keywordCount); UpdateManagedMetadata(keyPhrases.Take(keywordCount).ToArray(), log, ctx, li, field, wantedGuid); ctx.ExecuteQuery(); } catch (Exception ex) { log.Error(ex.Message); } } catch (Exception ex) { log.Error(ex.Message); } } catch (Exception ex) { log.Error(ex.Message); return(req.CreateResponse(HttpStatusCode.InternalServerError, ex.Message)); } } else { return(req.CreateResponse(HttpStatusCode.OK, "File was not pdf or doc")); } return(req.CreateResponse(HttpStatusCode.OK, list.Id)); } else { log.Info("List is not available on the site"); return(req.CreateResponse(HttpStatusCode.NotFound, "List is not available on the site")); } } } catch (Exception ex) { log.Info("Error Message: " + ex.Message); message += "Error Message: " + ex.Message; } log.Info(""); var returnable = JsonConvert.SerializeObject(keyPhrases); return(keyPhrases.Count <= 0 ? req.CreateResponse(HttpStatusCode.BadRequest, "Couldn't analyze file. Please verify the POST payload!") : req.CreateResponse(HttpStatusCode.OK, returnable)); }
static void Main(string[] args) { // Office 365 Multi-tenant sample // For a console application you need to create a context: this can be done by creating a context based on a user and password. // Using this approach you can add administrators to site collections for which the user used to create the context is already an // admin. Console.Write("Tenant name (e.g. ams if your SharePoint url is https://"); ConsoleWriteColor("ams", ConsoleColor.Green); Console.WriteLine(".sharepoint.com) :"); string tenantName = Console.ReadLine(); Console.Write("Name of site collection to target permissions (siteName)\r\n(https://" + tenantName + ".sharepoint.com/sites/"); ConsoleWriteColor("<siteName>", ConsoleColor.Green); Console.WriteLine(") :"); string siteName = Console.ReadLine(); Console.Write("Tenant admin name ("); ConsoleWriteColor("<tenantAdminName>", ConsoleColor.Green); Console.WriteLine("@" + tenantName + ".onmicrosoft.com) :"); string tenantAdminUserName = Console.ReadLine(); Console.WriteLine("Create SharePoint ClientContext object for the web"); string tenantAdminPassword = GetPassword(); AuthenticationManager authManager = new AuthenticationManager(); string targetSiteUrl = String.Format("https://{0}.sharepoint.com/sites/{1}", tenantName, siteName); string tenantAdmin = String.Format("{0}@{1}.onmicrosoft.com", tenantAdminUserName, tenantName); ClientContext cc = authManager.GetSharePointOnlineAuthenticatedContextTenant(targetSiteUrl, tenantAdmin, tenantAdminPassword); // Alternative approach is via an AppOnly app that has been registered via AppRegNew/AppInv. Good thing with this approach is // that you registered app can have tenant level permissions which makes that you can use below code to for example set the // additional site collection administrators to site collections where you today are not listed as site collection admin. A // typical example would be adding additional admins to OneDrive site collections to enable eDiscovery //ClientContext cc = authManager.GetAppOnlyAuthenticatedContext("https://tenantname-my.sharepoint.com/personal/user2", "<your tenant realm>", "<appID>", "<appsecret>"); // Tenant admin site context Console.WriteLine("Create SharePoint ClientContext object for the tenant administration web"); string tenantAdminUrl = String.Format("https://{0}-admin.sharepoint.com/", tenantName); ClientContext ccTenant = authManager.GetSharePointOnlineAuthenticatedContextTenant(tenantAdminUrl, tenantAdmin, tenantAdminPassword); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("----------------------------------------------------------------------"); Console.WriteLine("Admins for site collection {0}:", targetSiteUrl); // Get a list of current admins List<UserEntity> admins = cc.Web.GetAdministrators(); foreach (var admin in admins) { Console.WriteLine("{0} ({1})", admin.Title, admin.LoginName); } Console.WriteLine("----------------------------------------------------------------------"); Console.WriteLine("Add administrators to the current site collection:"); // Prepare a list of admins to add: below sample shows how to do this for Office 365 Multi-Tenant // NOTE: This is a sample of the code that must be implemented and WILL NOT EXECUTE since the user List<UserEntity> adminsToAdd = new List<UserEntity>(); adminsToAdd.Add(new UserEntity() { LoginName = SAMPLE_USER_ACCOUNTNAME }); cc.Web.AddAdministrators(adminsToAdd); foreach (var admin in adminsToAdd) { Console.WriteLine("Add: {0}", admin.LoginName); } Console.WriteLine("----------------------------------------------------------------------"); Console.WriteLine("Remove administrators from the current site collection:"); UserEntity adminToRemove = new UserEntity() { LoginName = SAMPLE_USER_ACCOUNTNAME }; cc.Web.RemoveAdministrator(adminToRemove); Console.WriteLine("Removed: {0}", adminToRemove.LoginName); Console.WriteLine("----------------------------------------------------------------------"); Console.WriteLine("External sharing settings for current site collection:"); Console.WriteLine(ccTenant.Web.GetSharingCapabilitiesTenant(new Uri(targetSiteUrl))); Console.WriteLine("----------------------------------------------------------------------"); Console.WriteLine("External users for current site collection:"); List<ExternalUserEntity> externalUsers = ccTenant.Web.GetExternalUsersForSiteTenant(new Uri(targetSiteUrl)); //List<ExternalUserEntity> externalUsers = ccTenant.Web.GetExternalUsersTenant();" foreach (var externalUser in externalUsers) { Console.WriteLine("{0} ({1})", externalUser.DisplayName, externalUser.AcceptedAs); } Console.WriteLine("Press enter to continue..."); Console.ReadLine(); }