public static void Run([TimerTrigger("0 0 23 * * *")] TimerInfo myTimer, TraceWriter log) { string userName = System.Environment.GetEnvironmentVariable("SPUser", EnvironmentVariableTarget.Process); string password = System.Environment.GetEnvironmentVariable("SPPwd", EnvironmentVariableTarget.Process); string SPRootURL = System.Environment.GetEnvironmentVariable("SPRootURL", EnvironmentVariableTarget.Process); string sendReportTo = System.Environment.GetEnvironmentVariable("SendReportTo", EnvironmentVariableTarget.Process); var authenticationManager = new PnPAuthenticationManager(); var clientContext = authenticationManager.GetSharePointOnlineAuthenticatedContextTenant(SPRootURL, userName, password); try { log.Info($"SPAudit Timer trigger function executed at: {DateTime.Now}"); var tenant = new Tenant(clientContext); var siteProperties = tenant.GetSiteProperties(0, true); clientContext.Load(siteProperties); clientContext.ExecuteQuery(); var sbOutput = new StringBuilder(); sbOutput.AppendLine("Audit Report Results<br/>"); sbOutput.AppendLine("---------------------<br/>"); foreach (SiteProperties sp in siteProperties) { //since we're iterating through the site collections we need a new context object for each site collection var siteClientContext = authenticationManager.GetSharePointOnlineAuthenticatedContextTenant(sp.Url, userName, password); Web web = siteClientContext.Web; GroupCollection groupCollection = web.SiteGroups; siteClientContext.Load(groupCollection, gc => gc.Include(group => group.AllowMembersEditMembership, Group => Group.Title)); siteClientContext.ExecuteQuery(); foreach (Group group in groupCollection) { if (group.AllowMembersEditMembership) { sbOutput.AppendLine($"Site Collection = {sp.Url} . Group with Edit Membership found = {group.Title}<br/>"); } } } sbOutput.AppendLine("---------------------<br/>"); sbOutput.AppendLine($"Audit Report Complete at {DateTime.Now}"); OfficeDevPnP.Core.Utilities.MailUtility.SendEmail(clientContext, new string[] { sendReportTo }, null, "SharePoint Audit Report Results", sbOutput.ToString()); log.Info($"SPAudit completed normally at: {DateTime.Now}"); } catch (Exception ex) { log.Info($"SPAudit Timer Exception at: {DateTime.Now}"); log.Info($"Message: {ex.Message}"); log.Info($"Stack Trace: {ex.StackTrace}"); OfficeDevPnP.Core.Utilities.MailUtility.SendEmail(clientContext, new string[] { sendReportTo }, null, "SharePoint Audit Report Has Errored", ex.Message + ex.StackTrace); } }
public static void ActivateSiteFeature() { OfficeDevPnP.Core.AuthenticationManager authenticationManager = new OfficeDevPnP.Core.AuthenticationManager(); using (templateSiteClientContext = authenticationManager.GetSharePointOnlineAuthenticatedContextTenant(templateSiteUrl, userName, passWord)) { var features = templateSiteClientContext.Web.Features; templateSiteClientContext.Load(features); templateSiteClientContext.ExecuteQuery(); //Feature sitePageFeature = features.Where(f => f.DisplayName == "Site Pages").FirstOrDefault(); //foreach (Feature getfeatureName in features) //{ // //# Set the property name to retrieve the value // getfeatureName.Retrieve("DisplayName"); // templateSiteClientContext.Load(getfeatureName); // templateSiteClientContext.ExecuteQuery(); // //Console.ForegroundColor = ConsoleColor.Green; // Console.WriteLine("Feature Definition ID:{0}", getfeatureName.DefinitionId, getfeatureName.DisplayName); //} //Console.WriteLine(features); //DefinitionId = { 15a572c6e5454d32897abab6f5846e18} //ff48f7e6 - 2fa1 - 428d - 9a15 - ab154762043d Guid guidOfFeature = new Guid("3f59333f4ce1406d8a979ecb0ff0337f"); //Feature feature = features.Where(f => f.DefinitionId == guidOfFeature).FirstOrDefault(); //var featureId = feature.DefinitionId; features.Add(guidOfFeature, true, FeatureDefinitionScope.Site); templateSiteClientContext.ExecuteQuery(); //label1.Text = " Operation Completed"; } }
public static void AddSectionAndAddWebpart() { OfficeDevPnP.Core.AuthenticationManager authenticationManager = new OfficeDevPnP.Core.AuthenticationManager(); using (binderSiteClientContext = authenticationManager.GetSharePointOnlineAuthenticatedContextTenant(binderSiteUrl, userName, passWord)) { //Create a page or get the existing page string pageName = "POCSiteProvisioning.aspx"; ClientSidePage page = ClientSidePage.Load(binderSiteClientContext, pageName); //var page = binderSiteClientContext.Web.AddClientSidePage("POCAppProvisioning.aspx", true); // Add Section page.AddSection(CanvasSectionTemplate.ThreeColumn, 5); // get the available web parts - this collection will include OOTB and custom SPFx web parts.. page.Save(); // Get all the available webparts var components = page.AvailableClientSideComponents(); // add the named web part.. var webPartToAdd = components.Where(wp => wp.ComponentType == 1 && wp.Name == "HeroControl").FirstOrDefault(); if (webPartToAdd != null) { ClientSideWebPart clientWp = new ClientSideWebPart(webPartToAdd) { Order = 1 }; //Add the WebPart to the page with appropriate section page.AddControl(clientWp, page.Sections[1].Columns[1]); } // the save method creates the page if one doesn't exist with that name in this site.. page.Save(); } }
public string UploadDocuments(string filePath) { try { string url = tbSharePointURL.Text; string username = "******"; string password = "******"; string docLib = tbDocLib.Text; // CreateDocumentLibrary(docLib); //CreateFolderinDocumentLibrary(docLib, processID); //string serverRelativeURL = string.Format("{0}/{1}", docLib, processID); OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager(); string fileName = Path.GetFileName(filePath); using (var ctx = authMgr.GetSharePointOnlineAuthenticatedContextTenant(url, username, password)) { Folder folder = ctx.Web.GetFolderByServerRelativeUrl(docLib); folder.UploadFile(fileName, filePath, true); } return(string.Format("{0}/{1}/{2}", url, docLib, fileName)); } catch (Exception ex) { return(ex.ToString()); } }
public static void AddTaxonomyEntry() { try { OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager(); string siteUrl = "https://sppalsmvp.sharepoint.com/sites/DeveloperSite"; string userName = "******"; string password = "******"; using (var ctx = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password)) { Web web = ctx.Web; ctx.Load(web); ctx.Load(web.Lists); ctx.ExecuteQueryRetry(); List list = web.Lists.GetByTitle("List1"); ctx.Load(list); ctx.ExecuteQueryRetry(); var tags = new string[] { "Term1", "Term2" }; var tagsString = EnsureTerms(tags, siteUrl, list.Id, "MyTaxonomyField", ctx); } } catch (Exception ex) { } }
/// <summary> /// Get the credentials from Windows Secure Store... Good, i use that often /// </summary> public static ClientContext authenticateByWindowsSecureStore() { OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager(); NetworkCredential cred = OfficeDevPnP.Core.Utilities.CredentialManager.GetCredential(securestoreid); return(authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteURL, cred.UserName, cred.SecurePassword)); }
public static ClientContext GetClientContext(ContentLogRequest request) { string locationUrl = $"{request.SiteUrl}"; Uri locationUri = new Uri(locationUrl); ClientContext clientContext = new ClientContext(locationUri.Scheme + Uri.SchemeDelimiter + locationUri.Host); OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager(); clientContext = authMgr.GetSharePointOnlineAuthenticatedContextTenant(locationUrl, request.UserId, request.Password); clientContext.ExecuteQuery(); return(clientContext); }
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."); // Credentials for getting authenticated context using auth manager of OfficeDevPnP Dll // Since its a POC, I have used direct creds. // You could use other authentication modes for getting the context for PRODUCTION ENV usage. string siteUrl = "https://nakkeerann.sharepoint.com/sites/teamsite"; string userName = "******"; string password = "******"; OfficeDevPnP.Core.AuthenticationManager authManager = new OfficeDevPnP.Core.AuthenticationManager(); // parse query parameter string filePath = req.GetQueryNameValuePairs() .FirstOrDefault(q => string.Compare(q.Key, "filePath", true) == 0) .Value; try { // context using auth manager using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password)) { Web web = clientContext.Site.RootWeb; Microsoft.SharePoint.Client.File file = web.GetFileByUrl(filePath); var data = file.OpenBinaryStream(); string content = null; using (MemoryStream memoryStream = new MemoryStream()) { clientContext.Load(file); clientContext.ExecuteQuery(); if (data != null && data.Value != null) { data.Value.CopyTo(memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); // Function extracts the document content content = ExtractContentFromWordDocument(memoryStream); // Function responds back with extracted document content return(req.CreateResponse(HttpStatusCode.OK, content)); } } // Function responds back return(req.CreateResponse(HttpStatusCode.BadRequest, "Unable to process file or no content present")); } } catch (Exception ex) { log.Info("Error Message: " + ex.Message); return(req.CreateResponse(HttpStatusCode.BadRequest, ex.Message)); } }
//gavdcodeend 12 //---------------------------------------------------------------------------------------- static ClientContext LoginPnPCore() { OfficeDevPnP.Core.AuthenticationManager pnpAuthMang = new OfficeDevPnP.Core.AuthenticationManager(); ClientContext rtnContext = pnpAuthMang.GetSharePointOnlineAuthenticatedContextTenant (ConfigurationManager.AppSettings["spUrl"], ConfigurationManager.AppSettings["spUserName"], ConfigurationManager.AppSettings["spUserPw"]); return(rtnContext); }
public static ClientContext GetWebContext(string webUrl, ContentLogRequest request, ClientContext ctx) { string locationUrl = $"{webUrl}"; if (siteContextUrl != locationUrl) { siteContextUrl = locationUrl; ClientContext clientContext = new ClientContext(locationUrl.ToString()); OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager(); clientContext = authMgr.GetSharePointOnlineAuthenticatedContextTenant(locationUrl.ToString(), request.UserId, request.Password); clientContext.ExecuteQuery(); return(clientContext); } return(ctx); }
//gavdcodeend 06 //gavdcodebegin 03 static void LoginPnPCoreDirectly() { OfficeDevPnP.Core.AuthenticationManager pnpAuthMang = new OfficeDevPnP.Core.AuthenticationManager(); using (ClientContext spCtx = pnpAuthMang.GetSharePointOnlineAuthenticatedContextTenant (ConfigurationManager.AppSettings["spUrl"], ConfigurationManager.AppSettings["spUserName"], ConfigurationManager.AppSettings["spUserPw"])) { Web rootWeb = spCtx.Web; spCtx.Load(rootWeb); spCtx.ExecuteQuery(); Console.WriteLine(rootWeb.Created.ToShortDateString()); } }
protected void CaptureScreenShot() { this.testContextInstance.WriteLine("Capture Screenshot"); string fileName = "TestAutomation_" + DateTime.Now.ToString("yyyy-MM-dd_hh-mm") + ".jpeg"; string file = TestContext.TestDir; ((ITakesScreenshot)driver).GetScreenshot().SaveAsFile(file + fileName); //SharePoint Online - Credentials string siteUrl = (string)TestContext.Properties["SiteUrl"]; string userName = (string)TestContext.Properties["Username"]; string password = (string)TestContext.Properties["Password"]; OfficeDevPnP.Core.AuthenticationManager authManager = new OfficeDevPnP.Core.AuthenticationManager(); ClientContext context = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password); // get the root folder var library = context.Web.Lists.GetByTitle("Documents"); context.Load(library, l => l.RootFolder); context.ExecuteQuery(); // upload the file library.RootFolder.UploadFileAsync(fileName, file + fileName, false); }
private void CreateDocumentLibrary(string doclibName) { string url = tbSharePointURL.Text; string username = "******"; string password = "******"; OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager(); var docLib = new ListCreationInformation() { Title = doclibName, Description = "system created document Library for storing DKSH documents", TemplateType = 101 //document library }; using (var ctx = authMgr.GetSharePointOnlineAuthenticatedContextTenant(url, username, password)) { if (!ctx.Site.RootWeb.ListExists(doclibName)) { ctx.Web.Lists.Add(docLib); ctx.ExecuteQuery(); } } }
public static void PageSectionDivision() { OfficeDevPnP.Core.AuthenticationManager authenticationManager = new OfficeDevPnP.Core.AuthenticationManager(); using(ClientContext currentSiteContext = authenticationManager.GetSharePointOnlineAuthenticatedContextTenant(binderSiteUrl, userName, passWord)) { string pageName = "POCSiteProvisioning.aspx"; ClientSidePage page = ClientSidePage.Load(currentSiteContext, pageName); var appManager = new AppManager(currentSiteContext); var apps = appManager.GetAvailable(); ClientSideComponent clientSideComponent = null; var chartsApp = apps.Where(a => a.Title == "hero-control-client-side-solution-ProductionEnv").FirstOrDefault(); bool controlPresent = false; bool done = false; int count = 0; do { try { ClientSideComponent[] clientSideComponents = (ClientSideComponent[])page.AvailableClientSideComponents(); clientSideComponent = clientSideComponents.Where(c => c.Id.ToLower() == chartsApp.Id.ToString().ToLower()).FirstOrDefault(); foreach (ClientSideComponent csc in clientSideComponents) { if (csc.Id.ToString().ToLower().Contains(chartsApp.Id.ToString().ToLower())) { clientSideComponent = csc; continue; } } //ClientSideWebPart webPart = page.Controls.Where(wP => wP != null) foreach (var control in page.Controls) { ClientSideWebPart cpWP = control as ClientSideWebPart; if (cpWP != null && cpWP.SpControlData.WebPartId.ToString() == chartsApp.Id.ToString()) { controlPresent = true; done = true; } } if (!controlPresent) { ClientSideWebPart WebPart = new ClientSideWebPart(clientSideComponent); JToken activeValueToken = true; // Find the web part configuration string from the web part file or code debugging //string propertyJSONString = String.Format("[{{<WP Configuration string>}}]", < parameters >); //JToken propertyTermToken = JToken.Parse(propertyJSONString); WebPart.Properties.Add("showOnlyActive", activeValueToken); CanvasSection section = new CanvasSection(page, CanvasSectionTemplate.ThreeColumnVerticalSection, page.Sections.Count + 1); page.Sections.Add(section); page.Save(); page.AddControl(WebPart, section.Columns[0]); page.Save(); page.Publish(); done = true; controlPresent = true; } } catch (Exception ex) { //Log.Info("Catched exception while adding Capex web part.. Trying again" + ex.Message); Console.WriteLine(ex); Console.ReadLine(); count++; } } while (!done && count <= 5); } }
/// <summary> /// Authenticate using a given UserName and Password... Not the best Idea to store password in clear text /// </summary> public static ClientContext authenticateWithUserNamePassword() { OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager(); return(authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteURL, username, password)); }
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."); // parse query parameter string name = req.GetQueryNameValuePairs() .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0) .Value; if (name == null) { // Get request body dynamic data = await req.Content.ReadAsAsync <object>(); name = data?.name; } string siteUrl = string.Empty; string createdTeamSiteUrl = string.Empty; string adminUserEmail = Environment.GetEnvironmentVariable("createTeamsAdminUserEmail"); if (string.IsNullOrWhiteSpace(adminUserEmail)) { adminUserEmail = "*****@*****.**"; } log.Info("Admin UserEmail : " + adminUserEmail); string adminPassword = Environment.GetEnvironmentVariable("createTeamsAdminUserPassword"); if (string.IsNullOrWhiteSpace(adminPassword)) { adminPassword = "******"; } log.Info("Admin Password : "******"createTeamsTenantURL"); if (string.IsNullOrWhiteSpace(tenantSiteURL)) { tenantSiteURL = "https://cyclotrondev.sharepoint.com/"; } log.Info("Tenant URL : " + tenantSiteURL); string sharepointSiteURL = Environment.GetEnvironmentVariable("createTeamsSharepointSiteURL"); if (string.IsNullOrWhiteSpace(sharepointSiteURL)) { sharepointSiteURL = "https://cyclotrondev.sharepoint.com/sites/ClarkPacific/"; } log.Info("SharePoint Site URL : " + sharepointSiteURL); string sharepointListName = Environment.GetEnvironmentVariable("createTeamsSharepointListName"); if (string.IsNullOrWhiteSpace(sharepointListName)) { sharepointListName = "Projects"; } log.Info("SharePoint List Name : " + sharepointListName); System.Security.SecureString secureString = new System.Security.SecureString(); foreach (char ch in adminPassword) { secureString.AppendChar(ch); } Dictionary <string, string> siteInfo = new Dictionary <string, string>(); OfficeDevPnP.Core.AuthenticationManager authManager = new OfficeDevPnP.Core.AuthenticationManager(); string camlQuery = "<View>" + "<Query>" + "<Where>" + "<Eq>" + "<FieldRef Name='HasSiteCreated' />" + "<Value Type='Boolean'>No</Value>" + "</Eq>" + "</Where>" + "</Query>" + "</View>"; CamlQuery query = new CamlQuery(); query.ViewXml = camlQuery; log.Info("CAML Query : " + camlQuery); using (var context = authManager.GetSharePointOnlineAuthenticatedContextTenant(sharepointSiteURL, adminUserEmail, secureString)) { List list = context.Web.Lists.GetByTitle(sharepointListName); if (list != null) { log.Info("List : " + sharepointListName + " Found."); ListItemCollection licollection = list.GetItems(query); context.Load(licollection); context.ExecuteQuery(); foreach (ListItem item in licollection) { siteInfo.Add("Id", item["ID"].ToString()); siteInfo.Add("Title", item["Title"] == null ? "" : item["Title"].ToString()); siteInfo.Add("JobId", item["JOBID"] == null ? "" : item["JOBID"].ToString()); siteInfo.Add("ProductType", item["ProductType"] == null ? "" : item["ProductType"].ToString()); siteInfo.Add("BuildingType", item["BuildingType"] == null ? "" : item["BuildingType"].ToString()); siteInfo.Add("ContractValue", item["ContractValue"] == null ? "" : item["ContractValue"].ToString()); siteInfo.Add("ProjectType", item["ProjectType"] == null ? "" : item["ProjectType"].ToString()); siteInfo.Add("ProjectSiteLink", item["ProjectSiteLink"] == null ? "" : item["ProjectSiteLink"].ToString()); // Store SPM,PM,Jurisdiction, APM,PE user emails as owner emails string ownerUsersEmailStr = ""; if (item["SPM"] != null) { FieldUserValue userValue = item["SPM"] as FieldUserValue; if (userValue != null) { siteInfo.Add("SPM", userValue.Email); ownerUsersEmailStr += userValue.Email + ";"; } } if (item["PM"] != null) { FieldUserValue userValue = item["PM"] as FieldUserValue; if (userValue != null) { siteInfo.Add("PM", userValue.Email); ownerUsersEmailStr += userValue.Email + ";"; } } if (item["Jurisdiction"] != null) { FieldUserValue userValue = item["Jurisdiction"] as FieldUserValue; if (userValue != null) { siteInfo.Add("Jurisdiction", userValue.Email); ownerUsersEmailStr += userValue.Email + ";"; } } if (item["APM"] != null) { FieldUserValue userValue = item["APM"] as FieldUserValue; if (userValue != null) { siteInfo.Add("APM", userValue.Email); ownerUsersEmailStr += userValue.Email + ";"; } } if (item["PE"] != null) { FieldUserValue userValue = item["PE"] as FieldUserValue; if (userValue != null) { siteInfo.Add("PE", userValue.Email); ownerUsersEmailStr += userValue.Email + ";"; } } if (!string.IsNullOrWhiteSpace(ownerUsersEmailStr)) { siteInfo.Add("OwnerUsers", ownerUsersEmailStr); } string memberUsersEmailStr = ""; if (item["Members"] != null) { foreach (FieldUserValue userValue in item["Members"] as FieldUserValue[]) { if (userValue != null) { memberUsersEmailStr += userValue.Email + ";"; } } } if (!string.IsNullOrWhiteSpace(memberUsersEmailStr)) { siteInfo.Add("MemberUsers", memberUsersEmailStr); } siteInfo.Add("Client", item["Client"] == null ? "" : item["Client"].ToString()); // Added hardcode value for type for site creation siteInfo.Add("type", "teams"); log.Info("Processing Site : " + item["Title"].ToString()); var siteType = siteInfo["type"]; string existingGroupID = ""; 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 = tenantSiteURL + "/sites/" + siteInfo["alias"].ToString(), }).GetAwaiter().GetResult(); log.Info("Communication Site URL : " + tenantSiteURL + "/sites/" + siteInfo["alias"].ToString()); // 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(); siteUrl = tenantSiteURL + "/sites/" + siteInfo["alias"].ToString(); break; case "teamsite": var ctxTeamsite = context.CreateSiteAsync(new TeamSiteCollectionCreationInformation { DisplayName = siteInfo["Title"].ToString(), Description = siteInfo["Description"].ToString(), Alias = siteInfo["alias"].ToString().Replace("\r\n", "").Replace(" ", ""), IsPublic = false, }).GetAwaiter().GetResult(); log.Info("Team Site URL : " + ctxTeamsite.Url); 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); log.Info("Access Token: " + token); string userId = string.Empty; string groupId = string.Empty; // Get all owner user ID's from email string ownerUsersIDString = Graph.FormatUserIdFromUserEmail(token, ownerUsersEmailStr, log); // Get all Member user ID's from email string memberUsersIDString = Graph.FormatUserIdFromUserEmail(token, memberUsersEmailStr, log); string teamTemplateGroupId = Environment.GetEnvironmentVariable("createTeamsTemplateGroupId"); if (string.IsNullOrWhiteSpace(teamTemplateGroupId)) { teamTemplateGroupId = "a714962d-3e90-44c5-842d-df9c25bb2b9a"; } log.Info("Template Team ID : " + teamTemplateGroupId); existingGroupID = Graph.getTeamsIdByMailNickNameName(token, siteInfo["Title"].ToString(), "", log); if (string.IsNullOrWhiteSpace(existingGroupID)) { // Decide to clone team using existing teams template or create completely new teams if (teamTemplateGroupId != null) { // Clone teams using existing teams group id var body = "{ 'displayName': '" + siteInfo["Title"].ToString() + "', 'description': '" + siteInfo["Title"].ToString() + "', 'mailNickname': '" + siteInfo["Title"].ToString() + "', 'partsToClone': 'apps,tabs,settings,channels,members'}"; log.Info("Cloning Data : " + body); string teamResponse = Graph.cloneMicrosoftTeams(token, body, teamTemplateGroupId, log, out createdTeamSiteUrl); log.Info("Cloning Response : " + teamResponse); while (existingGroupID == "") { existingGroupID = Graph.getTeamsIdByMailNickNameName(token, siteInfo["Title"].ToString(), "", log); } if (!string.IsNullOrWhiteSpace(existingGroupID)) { createdTeamSiteUrl = "https://graph.microsoft.com/v1.0/groups/" + existingGroupID; // Add default owner users to newly created teams site var hasTeamOwnersAdded = Graph.addDefaultTeamsUserToNewTeams(token, teamTemplateGroupId, existingGroupID, log, "owners"); // Add default Members users to newly created teams site var hasTeamMembersAdded = Graph.addDefaultTeamsUserToNewTeams(token, teamTemplateGroupId, existingGroupID, log, "members"); // Add Form Owner users to newly created group var hasOwnersAdded = Graph.addFormUsersToTeams(token, existingGroupID, ownerUsersEmailStr, log, "owners"); // Add Form Member users to newly created group var hasMembersAdded = Graph.addFormUsersToTeams(token, existingGroupID, memberUsersEmailStr, log, "members"); // Get Source SharePoint Url using existing teams id string sourceSPUrl = Graph.getSharePointSiteUrlForTeams(token, teamTemplateGroupId, log); // Get Destination SharePoint Url using newly created teams id string destinationSPUrl = ""; while (destinationSPUrl == "") { destinationSPUrl = Graph.getSharePointSiteUrlForTeams(token, existingGroupID, log); } if (sourceSPUrl != null && sourceSPUrl != "" && destinationSPUrl != null && destinationSPUrl != "") { // Copy content from source SharePoint site to destination SharePoint site. CloneTeamsLibrary ctlib = new CloneTeamsLibrary(); ctlib.CloneLibraryItems(sourceSPUrl, destinationSPUrl, adminUserEmail, secureString, log); } } } else if (!string.IsNullOrWhiteSpace(ownerUsersIDString) || !string.IsNullOrWhiteSpace(memberUsersIDString)) { // Create new teams string dataPost = "{ 'displayName': '" + siteInfo["Title"].ToString() + "', 'groupTypes': ['Unified'], 'mailEnabled': true, 'mailNickname': '" + siteInfo["Title"].ToString().Replace("\r\n", "").Replace(" ", "") + "', 'securityEnabled': false, '*****@*****.**': [" + ownerUsersIDString + "], 'visibility': 'Private','*****@*****.**':[" + memberUsersIDString + "] }"; groupId = Graph.createUnifiedGroup(token, dataPost, log); log.Info("groupId: " + groupId); string dataPut = "{'memberSettings': {'allowCreateUpdateChannels': true},'messagingSettings': {'allowUserEditMessages': true,'allowUserDeleteMessages': true},'funSettings': {'allowGiphy': true,'giphyContentRating':'strict'}}"; log.Info("Team JSON Data" + dataPut); string teamResponse = Graph.createMicrosoftTeams(token, dataPut, groupId, log, out createdTeamSiteUrl); //Graph.addOwnerToUnifiedGroup(token, groupId, userId); //removeOwnerToUnifiedGroup(token, groupId, userId); } //siteUrl = siteInfo["ProjectSiteLink"].ToString(); log.Info("Teams URL : " + createdTeamSiteUrl); } else { log.Info("Team : " + siteInfo["Title"].ToString() + " is already exists. Please try with different name."); } break; } // When the site or Teams has been created the status of the list item will change in ready if (!string.IsNullOrWhiteSpace(createdTeamSiteUrl) || !string.IsNullOrWhiteSpace(existingGroupID)) { item["HasSiteCreated"] = true; item.Update(); context.ExecuteQuery(); } } } } return(name == null ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body") : req.CreateResponse(HttpStatusCode.OK, "Hello " + adminUserEmail)); }
private void bkWorkerProcess_DoWorkAsync(object sender, DoWorkEventArgs e) { try { // string siteUrl = txtSite.Text; string userName = txtUser.Text; string password = txtPassword.Text; string whiteList = txtWhiteList.Text; (sender as BackgroundWorker).ReportProgress(5, "The configuration process was started"); //if (siteUrl.Substring(siteUrl.Length - 1) == "/") //{ // siteUrl = siteUrl.Substring(0, siteUrl.Length - 1); //} OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager(); using (var clientContext = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteAdminUrl, userName, password)) { (sender as BackgroundWorker).ReportProgress(10, "Getting access to admin site"); Tenant adminSite = new Tenant(clientContext); var siteName = txtSite.Text; Regex pattern = new Regex("[&_,.;:/\"!@$%^+=\\|<>{}#~*? ]"); siteName = pattern.Replace(siteName, string.Empty); Microsoft.SharePoint.Client.Site site = null; if (adminSite.CheckIfSiteExists("https://jreckner.sharepoint.com/sites/" + siteName, "Active")) { throw new Exception("The site: " + txtSite.Text + ", already exists. Please choose another name."); } var siteCreationProperties = new SiteCreationProperties(); var sitedesign = new OfficeDevPnP.Core.Entities.SiteEntity(); string[] owners = { txtUser.Text }; (sender as BackgroundWorker).ReportProgress(15, "Creating site collection"); //CommunicationSiteCollectionCreationInformation modernteamSiteInfo = new CommunicationSiteCollectionCreationInformation //{ // Description = "", // Owner = txtUser.Text, // SiteDesignId = new Guid("6a3f7a23-031b-4072-bf24-4193c14af65f"), // Title = txtSite.Text, // Lcid = 1033, // AllowFileSharingForGuestUsers = false, // Url = "https://jreckner.sharepoint.com/sites/" + siteName //}; TeamSiteCollectionCreationInformation modernteamSiteInfo = new TeamSiteCollectionCreationInformation() { DisplayName = txtSite.Text, //Owners = owners, //Alias = "https://jreckner.sharepoint.com/sites/" + siteName, Alias = siteName, Lcid = 1033, IsPublic = true, Description = "" }; var result = Task.Run(async() => { return(await clientContext.CreateSiteAsync(modernteamSiteInfo)); }).Result; siteUrl = result.Url; var properties = adminSite.GetSitePropertiesByUrl(siteUrl, true); clientContext.Load(properties); site = adminSite.GetSiteByUrl(siteUrl); Web web = site.RootWeb; clientContext.Load(web); ListCreationInformation doclist = new ListCreationInformation() { Title = "Document Library", TemplateType = 101, }; web.Lists.Add(doclist); (sender as BackgroundWorker).ReportProgress(20, "Creating Document Library"); clientContext.ExecuteQuery(); (sender as BackgroundWorker).ReportProgress(30, "Configuring WhiteList"); properties.SharingDomainRestrictionMode = SharingDomainRestrictionModes.AllowList; properties.SharingAllowedDomainList = whiteList; properties.SharingCapability = SharingCapabilities.ExternalUserSharingOnly; properties.Update(); clientContext.ExecuteQuery(); } using (var ctx = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password)) { (sender as BackgroundWorker).ReportProgress(40, "Copy disclaimer file"); callResponseFlow(siteUrl, userName, userName); (sender as BackgroundWorker).ReportProgress(50, "Getting access to site collection"); Web web = ctx.Web; ctx.Load(web); ctx.ExecuteQueryRetry(); var page2 = ctx.Web.AddClientSidePage("HomePageDisclaimer.aspx", true); page2.AddSection(CanvasSectionTemplate.OneColumn, 5); CanvasSection section = new CanvasSection(page2, CanvasSectionTemplate.OneColumn, page2.Sections.Count + 1); page2.Sections.Add(section); page2.PageTitle = "Disclaimer"; page2.LayoutType = ClientSidePageLayoutType.Home; page2.DisableComments(); page2.PromoteAsHomePage(); page2.PageHeader.LayoutType = ClientSidePageHeaderLayoutType.NoImage; page2.Save(); (sender as BackgroundWorker).ReportProgress(60, "Generating disclaimer Page"); // Check if file exists //Microsoft.SharePoint.Client.Folder folder = ctx.Web.GetFolderByServerRelativeUrl(ctx.Web.ServerRelativeUrl + "/" + library); var documentFile = ctx.Web.GetFileByServerRelativeUrl(ctx.Web.ServerRelativeUrl + "/" + library + "/" + fileName); web.Context.Load(documentFile, f => f.Exists); // Only load the Exists property web.Context.ExecuteQuery(); if (documentFile.Exists) { Console.WriteLine("File exists!!!!"); //} ctx.Load(documentFile); ctx.Load(documentFile, w => w.SiteId); ctx.Load(documentFile, w => w.WebId); ctx.Load(documentFile, w => w.ListId); ctx.Load(documentFile, w => w.UniqueId); ctx.ExecuteQuery(); //if (documentFile != null) //{ //si el documento existe var pdfWebPart = page2.InstantiateDefaultWebPart(DefaultClientSideWebParts.DocumentEmbed); var url = new Uri(ctx.Web.Url + "/" + library + "/" + fileName); pdfWebPart.Properties["siteId"] = documentFile.SiteId; pdfWebPart.Properties["webId"] = documentFile.WebId; pdfWebPart.Properties["listId"] = documentFile.ListId; pdfWebPart.Properties["uniqueId"] = documentFile.UniqueId; pdfWebPart.Properties["file"] = url.AbsoluteUri; pdfWebPart.Properties["serverRelativeUrl"] = documentFile.ServerRelativeUrl; pdfWebPart.Properties["wopiurl"] = String.Format("{0}/_layouts/15/{1}?sourcedoc=%7b{2}%7d&action=interactivepreview", web.Url, "WopiFrame.aspx", documentFile.UniqueId.ToString("D")); pdfWebPart.Properties["startPage"] = 1; page2.AddControl(pdfWebPart, section.Columns[0]); (sender as BackgroundWorker).ReportProgress(80, "Configuring webpart"); page2.Save(); page2.Publish(); } else { throw (new Exception("We can't not find the disclaimer file, please upload it to the site at Document library as 'Disclaimer.pdf' and apply the configuration again.")); } } (sender as BackgroundWorker).ReportProgress(100, "All configuration was applied correctly!!!"); //MessageBox.Show("All configuration was applied correctly!!!"); } catch (Exception ex) { string errormessage = ""; errormessage = ex.Message; if (ex.InnerException != null) { errormessage = ex.InnerException.Message; } (sender as BackgroundWorker).ReportProgress(0, "Error: " + ex.Message); } finally { finishprocess = true; } }
public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log) { log.Info("New modifications was detected."); // Get request body string httpPostData = string.Empty; var content = await req.Content.ReadAsStringAsync(); var reader = new StreamReader(content); if (reader != null) { httpPostData = reader.ReadToEnd(); } XmlDocument xmlDoc = new XmlDocument(); if (!string.IsNullOrWhiteSpace(httpPostData)) { xmlDoc.LoadXml(httpPostData); //print Xml to Azure Function log using (var stringWriter = new StringWriter()) using (var xmlTextWriter = XmlWriter.Create(stringWriter)) { xmlDoc.WriteTo(xmlTextWriter); xmlTextWriter.Flush(); log.Info(stringWriter.GetStringBuilder().ToString()); } string webUrl = xmlDoc.GetElementsByTagName("WebUrl")[0].InnerText; string listTitle = xmlDoc.GetElementsByTagName("ListTitle")[0].InnerText; string itemId = xmlDoc.GetElementsByTagName("ListItemId")[0].InnerText; string listTitleLog = "Log"; // Input Parameters string userName = "******"; string password = "******"; string columnTitle = "Title"; string objectif = "New element"; // PnP component to set context OfficeDevPnP.Core.AuthenticationManager authManager = new OfficeDevPnP.Core.AuthenticationManager(); try { using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(webUrl, userName, password)) { // Retrieve list item clientContext.Load(clientContext.Web); clientContext.ExecuteQuery(); List list = clientContext.Web.GetListByTitle(listTitleLog); clientContext.Load(list); clientContext.ExecuteQuery(); ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); ListItem oListItem; oListItem = list.AddItem(itemCreateInfo); oListItem[columnTitle] = objectif; oListItem.Update(); clientContext.Load(list); clientContext.ExecuteQuery(); } } catch (Exception ex) { return(req.CreateResponse(HttpStatusCode.BadRequest, "Error Message: " + ex.Message)); } } return(req.CreateResponse(HttpStatusCode.OK, "L'azure function est terminé")); }