Пример #1
0
        // Create a modern page.
        // string pageName = "PnPTestPage.aspx";
        // var newPage = await context.Web.NewPageAsync(PageLayoutType.Article);
        // await newPage.SaveAsync(pageName);
        // Console.WriteLine($"{pageName} was created");

        // Create a modern page.
        // string pageName = "PnPSectionPage.aspx";
        // var newPage = await context.Web.NewPageAsync(PageLayoutType.Article);
        // // adding sections to the page
        // newPage.AddSection(CanvasSectionTemplate.OneColumnFullWidth, 1);
        // newPage.AddSection(CanvasSectionTemplate.OneColumn, 2);
        // newPage.AddSection(CanvasSectionTemplate.TwoColumn, 3);
        // newPage.AddSection(CanvasSectionTemplate.TwoColumnLeft, 4);
        // newPage.AddSection(CanvasSectionTemplate.TwoColumnRight, 5);
        // newPage.AddSection(CanvasSectionTemplate.ThreeColumn, 6);
        // await newPage.SaveAsync(pageName);
        // Console.WriteLine($"{pageName} was created");

        // Add Text web part
        // string pageName = "PnPTextPage.aspx";
        // var newPage = await context.Web.NewPageAsync();
        // // adding sections to the page
        // newPage.AddSection(CanvasSectionTemplate.OneColumn, 1);
        // // Adding text control to the first section, first column
        // newPage.AddControl(newPage.NewTextPart("welcome to programmatic page"), newPage.Sections[0].Columns[0]);
        // // Save the page
        // await newPage.SaveAsync(pageName);
        // Console.WriteLine($"{pageName} was created");

        // Add Image web part
        // string pageName = "PnPImagePage.aspx";
        // var newPage = await context.Web.NewPageAsync();
        // // adding sections to the page
        // newPage.AddSection(CanvasSectionTemplate.OneColumn, 1);
        // // get the web part 'blueprint'
        // var imageWebPartToAdd = await newPage.InstantiateDefaultWebPartAsync(DefaultWebPart.Image);
        // imageWebPartToAdd.PropertiesJson = "{\"position\":{\"zoneIndex\":1,\"sectionIndex\":1,\"controlIndex\":1,\"layoutIndex\":1},\"webPartData\":{\"id\":\"d1d91016-032f-456d-98a4-721247c305e8\",\"instanceId\":\"f348a061-7740-4233-ae01-dd91e5e14c39\",\"title\":\"Image\",\"description\":\"Add an image, picture or photo to your page including text overlays and ability to crop and resize images.\",\"audiences\":[],\"serverProcessedContent\":{\"htmlStrings\":{},\"searchablePlainTexts\":{},\"imageSources\":{\"imageSource\":\"https://m365x725618.sharepoint.com/sites/ContosoAssets/OrgAssets/boat-500x300.jpg\"},\"links\":{},\"customMetadata\":{\"imageSource\":{\"siteId\":\"7b403ade-bf19-4e43-8cc4-e35708af56ec\",\"webId\":\"4befe663-3d09-4374-b5a6-e8b4556e9f27\",\"listId\":\"{7D75CC74-6E70-4F10-9697-61C70C92A311}\",\"uniqueId\":\"{f7e27b70-ce04-474c-b118-00521d4aa63f}\",\"width\":500,\"height\":300}}},\"dataVersion\":\"1.9\",\"properties\":{\"imageSourceType\":2,\"captionText\":\"\",\"altText\":\"\",\"linkUrl\":\"\",\"overlayText\":\"\",\"fileName\":\"\",\"siteId\":\"7b403ade-bf19-4e43-8cc4-e35708af56ec\",\"webId\":\"4befe663-3d09-4374-b5a6-e8b4556e9f27\",\"listId\":\"{7D75CC74-6E70-4F10-9697-61C70C92A311}\",\"uniqueId\":\"{f7e27b70-ce04-474c-b118-00521d4aa63f}\",\"imgWidth\":500,\"imgHeight\":300,\"alignment\":\"Center\",\"fixAspectRatio\":false}},\"controlType\":3,\"id\":\"f348a061-7740-4233-ae01-dd91e5e14c39\",\"webPartId\":\"d1d91016-032f-456d-98a4-721247c305e8\",\"emphasis\":{},\"reservedHeight\":26,\"reservedWidth\":744,\"addedFromPersistedData\":true}";
        // // add the web part to the first column of the first section
        // newPage.AddControl(imageWebPartToAdd, newPage.Sections[0].Columns[0]);
        // // Save the page
        // await newPage.SaveAsync(pageName);
        // Console.WriteLine($"{pageName} was created");
        public async Task CreateModernPage()
        {
            using (var context = await _pnpContextFactory.CreateAsync("FrankCommunication1"))
            {
                // Add Text web part
                string pageName = "PnPTextPage.aspx";
                var    newPage  = await context.Web.NewPageAsync();

                // adding sections to the page
                newPage.AddSection(CanvasSectionTemplate.OneColumn, 1);
                // Adding text control to the first section, first column
                newPage.AddControl(newPage.NewTextPart("<div><h1>welcome</h1> to programmatic page</div>"), newPage.Sections[0].Columns[0]);
                // Save the page
                await newPage.SaveAsync(pageName);

                Console.WriteLine($"{pageName} was created");

                // // Add Image web part
                // string pageName = "PnPImagePage.aspx";
                // var newPage = await context.Web.NewPageAsync();
                // // adding sections to the page
                // newPage.AddSection(CanvasSectionTemplate.OneColumn, 1);
                // // get the web part 'blueprint'
                // var imageWebPartToAdd = await newPage.InstantiateDefaultWebPartAsync(DefaultWebPart.Image);
                // imageWebPartToAdd.PropertiesJson = "{\"position\":{\"zoneIndex\":1,\"sectionIndex\":1,\"controlIndex\":1,\"layoutIndex\":1},\"webPartData\":{\"id\":\"d1d91016-032f-456d-98a4-721247c305e8\",\"instanceId\":\"f348a061-7740-4233-ae01-dd91e5e14c39\",\"title\":\"Image\",\"description\":\"Add&nbsp;an&nbsp;image,&nbsp;picture&nbsp;or&nbsp;photo&nbsp;to&nbsp;your&nbsp;page&nbsp;including&nbsp;text&nbsp;overlays&nbsp;and&nbsp;ability&nbsp;to&nbsp;crop&nbsp;and&nbsp;resize&nbsp;images.\",\"audiences\":[],\"serverProcessedContent\":{\"htmlStrings\":{},\"searchablePlainTexts\":{},\"imageSources\":{\"imageSource\":\"https://m365x725618.sharepoint.com/sites/ContosoAssets/OrgAssets/boat-500x300.jpg\"},\"links\":{},\"customMetadata\":{\"imageSource\":{\"siteId\":\"7b403ade-bf19-4e43-8cc4-e35708af56ec\",\"webId\":\"4befe663-3d09-4374-b5a6-e8b4556e9f27\",\"listId\":\"{7D75CC74-6E70-4F10-9697-61C70C92A311}\",\"uniqueId\":\"{f7e27b70-ce04-474c-b118-00521d4aa63f}\",\"width\":500,\"height\":300}}},\"dataVersion\":\"1.9\",\"properties\":{\"imageSourceType\":2,\"captionText\":\"\",\"altText\":\"\",\"linkUrl\":\"\",\"overlayText\":\"\",\"fileName\":\"\",\"siteId\":\"7b403ade-bf19-4e43-8cc4-e35708af56ec\",\"webId\":\"4befe663-3d09-4374-b5a6-e8b4556e9f27\",\"listId\":\"{7D75CC74-6E70-4F10-9697-61C70C92A311}\",\"uniqueId\":\"{f7e27b70-ce04-474c-b118-00521d4aa63f}\",\"imgWidth\":500,\"imgHeight\":300,\"alignment\":\"Center\",\"fixAspectRatio\":false}},\"controlType\":3,\"id\":\"f348a061-7740-4233-ae01-dd91e5e14c39\",\"webPartId\":\"d1d91016-032f-456d-98a4-721247c305e8\",\"emphasis\":{},\"reservedHeight\":26,\"reservedWidth\":744,\"addedFromPersistedData\":true}";
                // // add the web part to the first column of the first section
                // newPage.AddControl(imageWebPartToAdd, newPage.Sections[0].Columns[0]);
                // // Save the page
                // await newPage.SaveAsync(pageName);
                // Console.WriteLine($"{pageName} was created");
            }
        }
Пример #2
0
        internal async Task SiteInfoAsync()
        {
            using (var context = await pnpContextFactory.CreateAsync("DemoSite"))
            {
                // Retrieving web with lists and masterpageurl loaded ==> SharePoint REST query
                var web = await context.Web.GetAsync(w => w.Title, w => w.Description, w => w.MasterUrl);

                this.txtResults.Text = $"Title: {web.Title} Description: {web.Description} MasterPageUrl: {web.MasterUrl}";
            }
        }
Пример #3
0
        public async Task Run([QueueTrigger("%TasksQueueName%", Connection = "AzureWebJobsStorage")] TaskQueueItem item,
                              ILogger log,
                              CancellationToken token)
        {
            log.LogInformation($"Processing: {item.TaskId}");

            // Restore process info
            var process = await executor.LoadTransformationProcessAsync(item.ProcessId, token);

            if (!(process is LongRunningTransformationProcessBase p))
            {
                throw new NotSupportedException();
            }

            string target = "TargetSite";

            // Create SharePoint target context
            PnPContext targetContext = await pnpContextFactory.CreateAsync(target);

            // Configure the source item id and the data source provider
            var sourceItemId   = new SharePointSourceItemId(item.SourcePageUri);
            var sourceProvider = new SharePointSourceProvider(sourceContext);

            // Execute the actual transformatio task
            var task = new PageTransformationTask(item.TaskId, sourceProvider, sourceItemId, targetContext);
            await p.ProcessTaskAsync(task, token);
        }
Пример #4
0
        private async Task <PnPContext> createSiteContext()
        {
            var siteUrl = new Uri(_pnpCoreOptions.Sites["DemoSite"].SiteUrl);

            return(await _pnpContextFactory.CreateAsync(siteUrl,
                                                        new ExternalAuthenticationProvider((resourceUri, scopes) =>
            {
                return _tokenAcquisition.GetAccessTokenForUserAsync(scopes).GetAwaiter().GetResult();
            }
                                                                                           )));
        }
Пример #5
0
        internal async Task SiteInfoAsync()
        {
            using (var context = await pnpContextFactory.CreateAsync("DemoSite"))
            {
                var accessToken = await context.AuthenticationProvider.GetAccessTokenAsync(context.Uri);

                //Console.WriteLine($"Token: {accessToken}");
                var CSOMContext = GetContext(context.Uri, accessToken);
                using (CSOMContext) {
                    Web CSOMWeb = CSOMContext.Web;
                    CSOMContext.Load(CSOMWeb, w => w.Title, w => w.Description);
                    CSOMContext.ExecuteQuery();
                    Console.WriteLine(CSOMWeb.Title);
                }
            }
        }
Пример #6
0
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("PiaSys Yo Teams Backend function triggered!");

            var targetSiteUrl = new Uri(Environment.GetEnvironmentVariable("TargetSiteUrl"));
            var clientId      = Environment.GetEnvironmentVariable("ClientId");
            var tenantId      = Environment.GetEnvironmentVariable("TenantId");
            var clientSecret  = this.ToSecureString(Environment.GetEnvironmentVariable("ClientSecret"));

            // Let's try to get the access token from the Authorization request header
            if (req.Headers.ContainsKey(AUTHORIZATION_HEADER) &&
                req.Headers[AUTHORIZATION_HEADER].Count == 1)
            {
                string accessToken = req.Headers[AUTHORIZATION_HEADER][0].Split(' ', StringSplitOptions.RemoveEmptyEntries)[1];

                var oboProvider = new OnBehalfOfAuthenticationProvider(clientId, tenantId, clientSecret,
                                                                       () => accessToken);

                using (var context = await _pnpContextFactory.CreateAsync(targetSiteUrl, oboProvider))
                {
                    var web = await context.Web.GetAsync(w => w.Id, w => w.Title, w => w.CurrentUser);

                    var user = await context.Web.CurrentUser.GetAsync(
                        u => u.Title,
                        u => u.UserPrincipalName);

                    var result = new {
                        web = new {
                            web.Id,
                            web.Title,
                        },
                        user = new
                        {
                            user.UserPrincipalName,
                            user.Title,
                        }
                    };

                    return(new JsonResult(result));
                }
            }

            return(new UnauthorizedObjectResult(null));
        }
Пример #7
0
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = "term/{name}")] HttpRequest req, string name)
        {
            using (var pnpContext = await _pnpContextFactory.CreateAsync("Default"))
            {
                _logger.LogInformation("Creating Term '{DefaultLabel}'", name);
                try
                {
                    ITermGroup termGroup = pnpContext.TermStore.Groups.First();
                    ITermSet   termSet   = termGroup.Sets.First();

                    var newTerm = await termSet.Terms.AddAsync(name);

                    return(new OkObjectResult(new { id = newTerm.Id }));
                }
                catch (MicrosoftGraphServiceException ex)
                {
                    _logger.LogError((Exception)ex, ex.Error.ToString());
                    return(new BadRequestObjectResult(ex.Error));
                }
            }
        }
        /// <summary>
        /// Creates a new transformation process for SharePoint
        /// </summary>
        /// <param name="transformationProcess">The process to use</param>
        /// <param name="pnpContextFactory">The context factory to use</param>
        /// <param name="sourceContext">The source context</param>
        /// <param name="targetName">The target site name</param>
        /// <param name="token">The cancellation token, if any</param>
        /// <returns></returns>
        public static async Task StartProcessAsync(
            this ITransformationProcess transformationProcess,
            IPnPContextFactory pnpContextFactory,
            ClientContext sourceContext,
            string targetName,
            CancellationToken token = default)
        {
            if (transformationProcess == null)
            {
                throw new ArgumentNullException(nameof(transformationProcess));
            }
            if (pnpContextFactory == null)
            {
                throw new ArgumentNullException(nameof(pnpContextFactory));
            }

            // Create context
            var targetContext = await pnpContextFactory.CreateAsync(targetName).ConfigureAwait(false);

            token.ThrowIfCancellationRequested();

            await transformationProcess.StartSharePointProcessAsync(sourceContext, targetContext, token).ConfigureAwait(false);
        }
Пример #9
0
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("GetSiteDocuments()");
            using (var pnpContext = await pnpContextFactory.CreateAsync("Default"))
            {
                log.LogInformation("Getting all the shared documents on site.");

                IList sharedDocuments = await pnpContext.Web.Lists.GetByTitleAsync("Documents", l => l.RootFolder);

                var sharedDocumentsFolder = await sharedDocuments.RootFolder.GetAsync(f => f.Files);

                var documents = (from d in sharedDocumentsFolder.Files.AsEnumerable()
                                 select new
                {
                    d.Name,
                    d.TimeLastModified,
                    d.UniqueId
                }).ToList();

                return(new OkObjectResult(new { documents }));
            }
        }
Пример #10
0
        public async Task <HttpResponseData> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req)
        {
            logger.LogInformation("CreateSite function starting...");

            // Parse the url parameters
            NameValueCollection parameters = HttpUtility.ParseQueryString(req.Url.Query);
            var siteName = parameters["siteName"];
            var owner    = parameters["owner"];

            HttpResponseData response = null;

            try
            {
                using (var pnpContext = await contextFactory.CreateAsync("Default"))
                {
                    response = req.CreateResponse(HttpStatusCode.OK);
                    response.Headers.Add("Content-Type", "application/json");

                    var communicationSiteToCreate = new CommunicationSiteOptions(new Uri($"https://{pnpContext.Uri.DnsSafeHost}/sites/{siteName}"), "Demo site")
                    {
                        Description = "PnP Core SDK demo site",
                        Language    = Language.English,
                        Owner       = $"i:0#.f|membership|{owner}"
                    };

                    logger.LogInformation($"Creating site: {communicationSiteToCreate.Url}");

                    // Create the new site collection
                    using (var newSiteContext = await pnpContext.GetSiteCollectionManager().CreateSiteCollectionAsync(communicationSiteToCreate))
                    {
                        logger.LogInformation($"Site created: {communicationSiteToCreate.Url}");

                        // Step 1: Upload image to site assets library
                        var siteAssetsLibrary = await newSiteContext.Web.Lists.EnsureSiteAssetsLibraryAsync(p => p.RootFolder);

                        var uploadFolder = await siteAssetsLibrary.RootFolder.EnsureFolderAsync("SitePages/PnP");

                        var addedFile = await uploadFolder.Files.AddAsync("parker.png", File.OpenRead($".{Path.DirectorySeparatorChar}parker.png"), true);

                        // Step 2: Create the page
                        var page = await newSiteContext.Web.NewPageAsync();

                        page.AddSection(CanvasSectionTemplate.OneColumn, 1);

                        // Add text with inline image
                        var text   = page.NewTextPart();
                        var parker = await page.GetInlineImageAsync(text, addedFile.ServerRelativeUrl, new PageImageOptions { Alignment = PageImageAlignment.Left });

                        text.Text = $"<H2>Hello everyone!</H2>{parker}<P>Community rocks, sharing is caring!</P>";
                        page.AddControl(text, page.Sections[0].Columns[0]);

                        // Save the page
                        await page.SaveAsync("PnP.aspx");

                        // Return the URL of the created site
                        await response.WriteStringAsync(JsonSerializer.Serialize(new { siteUrl = newSiteContext.Uri.AbsoluteUri }));
                    }

                    return(response);
                }
            }
            catch (Exception ex)
            {
                response = req.CreateResponse(HttpStatusCode.OK);
                response.Headers.Add("Content-Type", "application/json");
                await response.WriteStringAsync(JsonSerializer.Serialize(new { error = ex.Message }));

                return(response);
            }
        }
Пример #11
0
        public async Task <PnPContext> GetContextAsync()
        {
            string siteUrl = _configuration.GetValue <string>("SharePoint:SiteUrl");

            return(await _contextFactory.CreateAsync(new Uri(siteUrl), _msalAuthProvider));
        }