private static async Task <int> ApplyProvisioningTemplate(string url, X509Certificate2 cert, ProvisioningTemplate template, TraceWriter log)
        {
            OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();
            using (ClientContext targetCtx = authMgr.GetAzureADAppOnlyAuthenticatedContext(url, CLIENT_ID, TENANT, cert))
            {
                // Disable request timeout
                targetCtx.RequestTimeout = Timeout.Infinite;

                // Make sure our context is valid
                targetCtx.Load(targetCtx.Web, w => w.Url, w => w.Title);
                await targetCtx.ExecuteQueryRetryAsync();

                log.Info($"Connected to targetUrl: {targetCtx.Web.Url}");

                // Apply template, clear existing nav nodes
                ProvisioningTemplateApplyingInformation ptai = new ProvisioningTemplateApplyingInformation();
                ptai.ClearNavigation  = true;
                ptai.ProgressDelegate = delegate(String message, Int32 progress, Int32 total)
                {
                    log.Info(string.Format("APPLY: {0:00}/{1:00} - {2}", progress, total, message));
                };

                log.Info($"Beginning applying PnP template");
                targetCtx.Web.ApplyProvisioningTemplate(template, ptai);
                log.Info($"Finished applying PnP template");
            }
            return(await Task.FromResult(0));
        }
示例#2
0
        public static ClientContext GetContext(string siteUrl)
        {
            string thumbPrint = ConfigurationManager.AppSettings["thumbPrint"];


            string tenant        = ConfigurationManager.AppSettings["tenant"];
            string applicationID = ConfigurationManager.AppSettings["applicationID"];

            X509Certificate2 cert2 = null;
            X509Store        store = new X509Store(StoreName.My, StoreLocation.CurrentUser);

            try
            {
                store.Open(OpenFlags.ReadOnly);

                var col = store.Certificates.Find(X509FindType.FindByThumbprint, thumbPrint, false);

                if (col == null || col.Count == 0)
                {
                }
                cert2 = col[0];
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                store.Close();
            }

            OfficeDevPnP.Core.AuthenticationManager authmanager = new OfficeDevPnP.Core.AuthenticationManager();

            return(authmanager.GetAzureADAppOnlyAuthenticatedContext(siteUrl, applicationID, tenant, cert2));
        }
        private static async Task <ProvisioningTemplate> GetProvisioningTemplate(string url, X509Certificate2 cert, TraceWriter log)
        {
            ProvisioningTemplate template = null;

            OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();
            using (ClientContext sourceCtx = authMgr.GetAzureADAppOnlyAuthenticatedContext(url, CLIENT_ID, TENANT, cert))
            {
                // Disable request timeout
                sourceCtx.RequestTimeout = Timeout.Infinite;

                // Make sure our context is valid
                sourceCtx.Load(sourceCtx.Web, w => w.Url, w => w.Title);
                await sourceCtx.ExecuteQueryRetryAsync();

                log.Info($"Connected to sourceUrl: {sourceCtx.Web.Url}");

                // Extract template and hold in-memory
                ProvisioningTemplateCreationInformation ptci = new ProvisioningTemplateCreationInformation(sourceCtx.Web);
                ptci.ProgressDelegate = delegate(string message, Int32 progress, Int32 total)
                {
                    log.Info(string.Format("EXTRACT: {0:00}/{1:00} - {2}", progress, total, message));
                };

                log.Info($"Beginning PnP template extraction");
                template = sourceCtx.Web.GetProvisioningTemplate(ptci);
                log.Info($"Finished PnP template extraction");
            }
            return(await Task.FromResult(template));
        }
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            string thumbPrint    = "Your ThumbPrint";
            string siteUrl       = "Your Url";
            string tenant        = "Your Tenant";
            string applicationID = "Your App Id from Azure";

            X509Certificate2 cert2 = null;
            X509Store        store = new X509Store(StoreName.My, StoreLocation.CurrentUser);

            try
            {
                store.Open(OpenFlags.ReadOnly);

                var col = store.Certificates.Find(X509FindType.FindByThumbprint, thumbPrint, false);

                if (col == null || col.Count == 0)
                {
                    return(null);
                }
                cert2 = col[0];
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                store.Close();
            }

            OfficeDevPnP.Core.AuthenticationManager authmanager = new OfficeDevPnP.Core.AuthenticationManager();



            using (ClientContext ctx = authmanager.GetAzureADAppOnlyAuthenticatedContext(siteUrl, applicationID, tenant, cert2))
            {
                ctx.Load(ctx.Web);
                ctx.ExecuteQuery();
                log.Info("Your Site Name is: " + ctx.Web.Title);
                return(req.CreateResponse(HttpStatusCode.OK, $"Your Site Name is: " + ctx.Web.Title));
            }
        }
        public static async Task RunAsync([QueueTrigger("processchanges", Connection = "AzureWebJobsStorage")] WebhookNotification notificationModel, ILogger log)
        {
            log.LogInformation($"ProcesResourceChange queue trigger function process Site:{notificationModel.SiteUrl} Resource{notificationModel.Resource} ");

            string tenant  = System.Environment.GetEnvironmentVariable("Tenant", EnvironmentVariableTarget.Process);
            string siteUrl = $"https://{tenant}.sharepoint.com{notificationModel.SiteUrl}";

            log.LogInformation("Getting Azure SharePoint Token");
            LoginEntity loginDetails = await LoginUtil.CertificateLoginDetails();

            OfficeDevPnP.Core.AuthenticationManager authManager = new OfficeDevPnP.Core.AuthenticationManager();

            log.LogInformation("Connecting to SharePoint");
            using (ClientContext clientContext = authManager.GetAzureADAppOnlyAuthenticatedContext(siteUrl, loginDetails.ClientId, loginDetails.Tenant, loginDetails.Certificate))
            {
                log.LogInformation("Getting SharePoint List");
                Guid listId = new Guid(notificationModel.Resource);
                List list   = clientContext.Web.Lists.GetById(listId);

                // grab the changes to the provided list using the GetChanges method
                // on the list. Only request Item changes as that's what's supported via
                // the list web hooks
                ChangeQuery changeQuery = new ChangeQuery(false, false)
                {
                    Item         = true,
                    Add          = true,
                    DeleteObject = false,
                    Update       = true,
                    FetchLimit   = 1000
                };

                ChangeToken lastChangeToken = null;
                if (null == notificationModel.ClientState)
                {
                    throw new ApplicationException("Webhook doesn't contain a Client State");
                }

                Guid id = new Guid(notificationModel.ClientState);
                log.LogInformation("Checking Database for Change Token");
                AzureTableSPWebHook listWebHookRow = await AzureTable.GetListWebHookByID(id, listId);

                if (!string.IsNullOrEmpty(listWebHookRow.LastChangeToken))
                {
                    log.LogInformation("Change Token found");
                    lastChangeToken = new ChangeToken
                    {
                        StringValue = listWebHookRow.LastChangeToken
                    };
                }
                //Start pulling down the changes
                bool allChangesRead = false;

                do
                {
                    if (lastChangeToken == null)
                    {
                        log.LogInformation("Change Token not found grabbing the last 5 days of changes");
                        //If none found, grab only the last 5 day changes.
                        lastChangeToken = new ChangeToken
                        {
                            StringValue = string.Format("1;3;{0};{1};-1", notificationModel.Resource, DateTime.Now.AddDays(-5).ToUniversalTime().Ticks.ToString())
                        };
                    }

                    //Assing the change token to the query..this determins from what point in time we'll receive changes
                    changeQuery.ChangeTokenStart = lastChangeToken;

                    ChangeCollection changes = list.GetChanges(changeQuery);
                    clientContext.Load(list);
                    clientContext.Load(changes);
                    await clientContext.ExecuteQueryAsync();

                    if (changes.Count > 0)
                    {
                        log.LogInformation($"Found {changes.Count} changes");
                        foreach (Change change in changes)
                        {
                            lastChangeToken = change.ChangeToken;

                            if (change is ChangeItem item)
                            {
                                log.LogInformation($"Change {change.ChangeType} on Item:{item.ItemId} on List:{list.Title} Site:{notificationModel.SiteUrl}");
                            }
                        }

                        if (changes.Count < changeQuery.FetchLimit)
                        {
                            allChangesRead = true;
                        }
                    }
                    else
                    {
                        allChangesRead = true;
                    }
                } while (allChangesRead == false);

                if (!listWebHookRow.LastChangeToken.Equals(lastChangeToken.StringValue, StringComparison.InvariantCultureIgnoreCase))
                {
                    listWebHookRow.LastChangeToken = lastChangeToken.StringValue;
                    log.LogInformation("Updating change token");
                    await AzureTable.InsertOrReplaceListWebHook(listWebHookRow);
                }

                if (notificationModel.ExpirationDateTime.AddDays(-30) < DateTime.Now)
                {
                    bool updateResult = list.UpdateWebhookSubscription(new Guid(notificationModel.SubscriptionId), DateTime.Now.AddMonths(2));

                    if (!updateResult)
                    {
                        log.LogError($"The expiration date of web hook {notificationModel.SubscriptionId} with endpoint 'https://{Environment.GetEnvironmentVariable("WEBSITE_HOSTNAME")}/SharePointWebHook' could not be updated");
                    }
                    else
                    {
                        log.LogInformation($"The expiration date of web hook {notificationModel.SubscriptionId} with endpoint 'https://{Environment.GetEnvironmentVariable("WEBSITE_HOSTNAME")}/SharePointWebHook' successfully updated until {DateTime.Now.AddMonths(2).ToLongDateString()} ");
                    }
                }
            }
        }