public static async Task Run()
        {
            /////////////////////////////
            //
            // Programmer configuration
            //
            /////////////////////////////

            var sharepointDomain   = "demo.sharepoint.com";
            var siteCollectionPath = "/sites/GraphCommunityDemo";

            /////////////////
            //
            // Configuration
            //
            /////////////////

            AzureAdOptions azureAdOptions = new AzureAdOptions();

            var settingsFilename = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "appsettings.json");
            var builder          = new ConfigurationBuilder()
                                   .AddJsonFile(settingsFilename, optional: false)
                                   .AddUserSecrets <Program>();
            var config = builder.Build();

            config.Bind("AzureAd", azureAdOptions);

            ////////////////////////////
            //
            // Graph Client with Logger
            //
            ////////////////////////////

            var logger = new StringBuilderHttpMessageLogger();

            /*
             *  Could also use the Console if preferred...
             *
             *  var logger = new ConsoleHttpMessageLogger();
             */


            // Use the system browser to login
            //  https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/System-Browser-on-.Net-Core#how-to-use-the-system-browser-ie-the-default-browser-of-the-os

            var options = new PublicClientApplicationOptions()
            {
                AadAuthorityAudience = AadAuthorityAudience.AzureAdMyOrg,
                AzureCloudInstance   = AzureCloudInstance.AzurePublic,
                ClientId             = azureAdOptions.ClientId,
                TenantId             = azureAdOptions.TenantId,
                RedirectUri          = "http://localhost"
            };

            // Create the public client application (desktop app), with a default redirect URI
            var pca = PublicClientApplicationBuilder
                      .CreateWithApplicationOptions(options)
                      .Build();

            // Enable a simple token cache serialiation so that the user does not need to
            // re-sign-in each time the application is run
            TokenCacheHelper.EnableSerialization(pca.UserTokenCache);

            var scopes = new string[] { $"https://graph.microsoft.com/Sites.Read.All" };
            IAuthenticationProvider ap = new InteractiveAuthenticationProvider(pca, scopes);

            using (LoggingMessageHandler loggingHandler = new LoggingMessageHandler(logger))
                using (HttpProvider hp = new HttpProvider(loggingHandler, false, new Serializer()))
                {
                    GraphServiceClient graphServiceClient = new GraphServiceClient(ap, hp);

                    ////////////////////////////
                    //
                    // Setup is complete, run the sample
                    //
                    ////////////////////////////

                    var WebUrl = $"https://{sharepointDomain}{siteCollectionPath}";

                    try
                    {
                        var results = await graphServiceClient
                                      .Sites["root"]
                                      .Request()
                                      .Select(s => s.DisplayName)
                                      .GetAsync();

                        Console.WriteLine($"title: {results.DisplayName}");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }



                    Console.WriteLine("Press enter to show log");
                    Console.ReadLine();
                    Console.WriteLine();
                    var log = logger.GetLog();
                    Console.WriteLine(log);
                }
        }
        public static async Task Run()
        {
            /////////////////////////////
            //
            // Programmer configuration
            //
            /////////////////////////////

            var sharepointDomain   = "demo.sharepoint.com";
            var siteCollectionPath = "/sites/GraphCommunityDemo";

            ////////////////////////////////
            //
            // Azure AD Configuration
            //
            ////////////////////////////////

            AzureAdOptions azureAdOptions = new AzureAdOptions();

            var settingsFilename = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "appsettings.json");
            var builder          = new ConfigurationBuilder()
                                   .AddJsonFile(settingsFilename, optional: false)
                                   .AddUserSecrets <Program>();
            var config = builder.Build();

            config.Bind("AzureAd", azureAdOptions);

            /////////////////////////////////////
            //
            // Client Application Configuration
            //
            /////////////////////////////////////

            var options = new PublicClientApplicationOptions()
            {
                AadAuthorityAudience = AadAuthorityAudience.AzureAdMyOrg,
                AzureCloudInstance   = AzureCloudInstance.AzurePublic,
                ClientId             = azureAdOptions.ClientId,
                TenantId             = azureAdOptions.TenantId,
                RedirectUri          = "http://localhost"
            };

            // Create the public client application (desktop app), with a default redirect URI
            var pca = PublicClientApplicationBuilder
                      .CreateWithApplicationOptions(options)
                      .Build();

            // Enable a simple token cache serialiation so that the user does not need to
            // re-sign-in each time the application is run
            TokenCacheHelper.EnableSerialization(pca.UserTokenCache);

            ///////////////////////////////////////////////
            //
            //  Auth Provider - Device Code in this sample
            //
            ///////////////////////////////////////////////

            // Create an authentication provider to attach the token to requests
            var scopes = new string[] { $"https://{sharepointDomain}/AllSites.FullControl" };
            IAuthenticationProvider ap = new DeviceCodeProvider(pca, scopes);

            ////////////////////////////////////////////////////////////
            //
            // Graph Client with Logger and SharePoint service handler
            //
            ////////////////////////////////////////////////////////////

            var logger = new StringBuilderHttpMessageLogger();

            /*
             *  Could also use the Console if preferred...
             *
             *  var logger = new ConsoleHttpMessageLogger();
             */

            // Configure our client
            CommunityGraphClientOptions clientOptions = new CommunityGraphClientOptions()
            {
                UserAgent = "ChangeLogSample"
            };
            var graphServiceClient = CommunityGraphClientFactory.Create(clientOptions, logger, ap);

            ///////////////////////////////////////
            //
            // Setup is complete, run the sample
            //
            ///////////////////////////////////////

            var WebUrl = $"https://{sharepointDomain}{siteCollectionPath}";

            var web = await graphServiceClient
                      .SharePointAPI(WebUrl)
                      .Web
                      .Request()
                      .GetAsync();

            var changeToken = web.CurrentChangeToken;

            Console.WriteLine($"current change token: {changeToken.StringValue}");

            Console.WriteLine($"Make an update to the site {WebUrl}");
            Console.WriteLine("Press enter to continue");
            Console.ReadLine();

            var qry = new ChangeQuery(true, true);

            qry.ChangeTokenStart = changeToken;

            var changes = await graphServiceClient
                          .SharePointAPI(WebUrl)
                          .Web
                          .Request()
                          .GetChangesAsync(qry);

            Console.WriteLine(changes.Count);

            foreach (var item in changes)
            {
                Console.WriteLine($"{item.ChangeType}");
            }

            Console.WriteLine("Press enter to show log");
            Console.ReadLine();
            Console.WriteLine();
            var log = logger.GetLog();

            Console.WriteLine(log);
        }
        public static async Task Run()
        {
            /////////////////////////////
            //
            // Programmer configuration
            //
            /////////////////////////////

            var sharepointDomain   = "demo.sharepoint.com";
            var siteCollectionPath = "/sites/GraphCommunityDemo";

            ////////////////////////////////
            //
            // Azure AD Configuration
            //
            ////////////////////////////////

            AzureAdOptions azureAdOptions = new AzureAdOptions();

            var settingsFilename = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "appsettings.json");
            var builder          = new ConfigurationBuilder()
                                   .AddJsonFile(settingsFilename, optional: false);
            var config = builder.Build();

            config.Bind("AzureAd", azureAdOptions);

            /////////////////////////////////////
            //
            // Client Application Configuration
            //
            /////////////////////////////////////

            var options = new PublicClientApplicationOptions()
            {
                AadAuthorityAudience = AadAuthorityAudience.AzureAdMyOrg,
                AzureCloudInstance   = AzureCloudInstance.AzurePublic,
                ClientId             = azureAdOptions.ClientId,
                TenantId             = azureAdOptions.TenantId,
                RedirectUri          = "http://localhost"
            };

            // Create the public client application (desktop app), with a default redirect URI
            var pca = PublicClientApplicationBuilder
                      .CreateWithApplicationOptions(options)
                      .Build();

            // Enable a simple token cache serialiation so that the user does not need to
            // re-sign-in each time the application is run
            TokenCacheHelper.EnableSerialization(pca.UserTokenCache);

            ///////////////////////////////////////////////
            //
            //  Auth Provider - Interactive in this sample
            //
            ///////////////////////////////////////////////

            // Use the system browser to login
            //  https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/System-Browser-on-.Net-Core#how-to-use-the-system-browser-ie-the-default-browser-of-the-os

            var scopes = new string[] { $"https://{sharepointDomain}/AllSites.FullControl" };
            IAuthenticationProvider ap = new InteractiveAuthenticationProvider(pca, scopes);

            ////////////////////////////////////////////////////////////
            //
            // Graph Client with Logger and SharePoint service handler
            //
            ////////////////////////////////////////////////////////////

            var logger = new StringBuilderHttpMessageLogger();

            /*
             *  Could also use the Console if preferred...
             *
             *  var logger = new ConsoleHttpMessageLogger();
             */

            // Configure our client
            CommunityGraphClientOptions clientOptions = new CommunityGraphClientOptions()
            {
                UserAgent = "SharePointSearchSample"
            };

            var graphServiceClient = CommunityGraphClientFactory.Create(clientOptions, logger, ap);

            ///////////////////////////////////////
            //
            // Setup is complete, run the sample
            //
            ///////////////////////////////////////

            var WebUrl = $"https://{sharepointDomain}{siteCollectionPath}";

            var queryText     = $"adaptive";
            var propsToSelect = new List <string>()
            {
                "Title", "Path", "DocId]"
            };
            var sortList = new List <SearchQuery.Sort>()
            {
                new SearchQuery.Sort("DocId", SearchQuery.SortDirection.Ascending)
            };

            var query = new SearchQuery(
                queryText: queryText,
                selectProperties: propsToSelect,
                sortList: sortList);

            try
            {
                var results = await graphServiceClient
                              .SharePointAPI(WebUrl)
                              .Search
                              .Request()
                              .PostQueryAsync(query);

                var rowCount  = results.PrimaryQueryResult.RelevantResults.RowCount;
                var totalRows = results.PrimaryQueryResult.RelevantResults.TotalRows;

                Console.WriteLine($"rowCount: {rowCount}");

                string lastDocId = null;
                foreach (var item in results.PrimaryQueryResult.RelevantResults.Table.Rows)
                {
                    Console.WriteLine(item.Cells.FirstOrDefault(c => c.Key == "Path").Value);

                    var docId = item.Cells.FirstOrDefault(c => c.Key == "DocId")?.Value;
                    if (docId != null)
                    {
                        lastDocId = docId;
                    }
                }

                if (totalRows > rowCount && !string.IsNullOrEmpty(lastDocId))
                {
                    var nextPageQuery = new SearchQuery(
                        queryText: $"{queryText} indexdocid>{lastDocId}",
                        selectProperties: propsToSelect,
                        sortList: sortList);

                    var page2results = await graphServiceClient
                                       .SharePointAPI(WebUrl)
                                       .Search
                                       .Request()
                                       .PostQueryAsync(nextPageQuery);

                    foreach (var item in page2results.PrimaryQueryResult.RelevantResults.Table.Rows)
                    {
                        Console.WriteLine(item.Cells.FirstOrDefault(c => c.Key == "Path").Value);
                    }
                }
                Console.WriteLine($"totalRows: {totalRows}");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }



            Console.WriteLine("Press enter to show log");
            Console.ReadLine();
            Console.WriteLine();
            var log = logger.GetLog();

            Console.WriteLine(log);
        }
Exemple #4
0
        public static async Task Run()
        {
            /////////////////////////////
            //
            // Programmer configuration
            //
            /////////////////////////////

            var sharepointDomain   = "demo.sharepoint.com";
            var siteCollectionPath = "/sites/SiteGroupsTest";

            ////////////////////////////////
            //
            // Azure AD Configuration
            //
            ////////////////////////////////

            AzureAdOptions azureAdOptions = new AzureAdOptions();

            var settingsFilename = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "appsettings.json");
            var builder          = new ConfigurationBuilder()
                                   .AddJsonFile(settingsFilename, optional: false);
            var config = builder.Build();

            config.Bind("AzureAd", azureAdOptions);

            ////////////////////////////////////////
            //
            // Capture all diagnostic information
            //
            ///////////////////////////////////////

            // Start with an IHttpMessageLogger that will write to a StringBuilder
            var logger = new StringBuilderHttpMessageLogger();

            /*
             *  Could also use the Console if preferred...
             *
             *  var logger = new ConsoleHttpMessageLogger();
             */


            // MSAL provides logging via a callback on the client application.
            //  Write those entries to the same logger, prefixed with MSAL
            async void MSALLogging(LogLevel level, string message, bool containsPii)
            {
                await logger.WriteLine($"MSAL {level} {containsPii} {message}");
            }

            // GraphCommunity uses an EventSource to publish diagnostics in the handler.
            //    This follows the pattern used by the Azure SDK.
            var listener = new Community.Diagnostics.GraphCommunityEventSourceListener(async(args, message) =>
            {
                if (args.EventSource.Name.StartsWith("Graph-Community"))
                {
                    // create a dictionary of the properties of the args object
                    var properties = args.PayloadNames
                                     .Zip(args.Payload, (string k, object v) => new { Key = k, Value = v })
                                     .ToDictionary(x => x.Key, x => x.Value.ToString());

                    // log the message and payload, prefixed with COMM
                    var traceMessage = string.Format(args.Message, args.Payload.ToArray());
                    await logger.WriteLine($"COMM {traceMessage}");
                }
            }, System.Diagnostics.Tracing.EventLevel.LogAlways);

            /////////////////////////////////////
            //
            // Client Application Configuration
            //
            /////////////////////////////////////

            // Use the system browser to login
            //  https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/System-Browser-on-.Net-Core#how-to-use-the-system-browser-ie-the-default-browser-of-the-os

            var options = new PublicClientApplicationOptions()
            {
                AadAuthorityAudience = AadAuthorityAudience.AzureAdMyOrg,
                AzureCloudInstance   = AzureCloudInstance.AzurePublic,
                ClientId             = azureAdOptions.ClientId,
                TenantId             = azureAdOptions.TenantId,
                RedirectUri          = "http://localhost"
            };

            // Create the public client application (desktop app), with a default redirect URI
            var pca = PublicClientApplicationBuilder.CreateWithApplicationOptions(options)
                      .WithLogging(MSALLogging, LogLevel.Verbose, true, true)
                      .Build();

            // Enable a simple token cache serialiation so that the user does not need to
            // re-sign-in each time the application is run
            TokenCacheHelper.EnableSerialization(pca.UserTokenCache);

            ///////////////////////////////////////////////
            //
            //  Auth Provider - Interactive in this sample
            //
            ///////////////////////////////////////////////

            // Create an authentication provider to attach the token to requests
            var scopes = new string[] { $"https://{sharepointDomain}/AllSites.FullControl" };
            IAuthenticationProvider ap = new InteractiveAuthenticationProvider(pca, scopes);


            ////////////////////////////////////////////////////////////
            //
            // Graph Client with Logger and SharePoint service handler
            //
            ////////////////////////////////////////////////////////////

            // Configure our client
            CommunityGraphClientOptions clientOptions = new CommunityGraphClientOptions()
            {
                UserAgent = "DiagnosticsSample"
            };

            var graphServiceClient = CommunityGraphClientFactory.Create(clientOptions, logger, ap);


            ///////////////////////////////////////
            //
            // Setup is complete, run the sample
            //
            ///////////////////////////////////////

            try
            {
                var WebUrl = $"https://{sharepointDomain}{siteCollectionPath}";

                var appTiles = await graphServiceClient
                               .SharePointAPI(WebUrl)
                               .Web
                               .AppTiles
                               .Request()
                               .GetAsync();

                Console.WriteLine($"Tile count: {appTiles.Count}");

                var me = await graphServiceClient
                         .Me
                         .Request()
                         .WithScopes(new string[] { "https://graph.microsoft.com/User.Read" })
                         .GetAsync();

                Console.WriteLine($"Me.DisplayName: {me.DisplayName}");
            }
            catch (Exception ex)
            {
                await logger.WriteLine("");

                await logger.WriteLine("================== Exception caught ==================");

                await logger.WriteLine(ex.ToString());
            }


            Console.WriteLine("Press enter to show log");
            Console.ReadLine();
            Console.WriteLine();
            var log = logger.GetLog();

            Console.WriteLine(log);
        }
        public static async Task Run()
        {
            /////////////////////////////
            //
            // Programmer configuration
            //
            /////////////////////////////

            var sharepointDomain   = "demo.sharepoint.com";
            var siteCollectionPath = "/sites/SiteDesignTest";

            ////////////////////////////////
            //
            // Azure AD Configuration
            //
            ////////////////////////////////

            AzureAdOptions azureAdOptions = new AzureAdOptions();

            var settingsFilename = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "appsettings.json");
            var builder          = new ConfigurationBuilder()
                                   .AddJsonFile(settingsFilename, optional: false)
                                   .AddUserSecrets <Program>();
            var config = builder.Build();

            config.Bind("AzureAd", azureAdOptions);

            /////////////////////////////////////
            //
            // Client Application Configuration
            //
            /////////////////////////////////////

            var options = new PublicClientApplicationOptions()
            {
                AadAuthorityAudience = AadAuthorityAudience.AzureAdMyOrg,
                AzureCloudInstance   = AzureCloudInstance.AzurePublic,
                ClientId             = azureAdOptions.ClientId,
                TenantId             = azureAdOptions.TenantId,
                RedirectUri          = "http://localhost"
            };

            // Create the public client application (desktop app), with a default redirect URI
            var pca = PublicClientApplicationBuilder
                      .CreateWithApplicationOptions(options)
                      .Build();

            // Enable a simple token cache serialiation so that the user does not need to
            // re-sign-in each time the application is run
            TokenCacheHelper.EnableSerialization(pca.UserTokenCache);

            ///////////////////////////////////////////////
            //
            //  Auth Provider - Device Code in this sample
            //
            ///////////////////////////////////////////////

            // Create an authentication provider to attach the token to requests
            var scopes = new string[] { $"https://{sharepointDomain}/AllSites.FullControl" };
            IAuthenticationProvider ap = new DeviceCodeProvider(pca, scopes);

            ////////////////////////////////////////////////////////////
            //
            // Graph Client with Logger and SharePoint service handler
            //
            ////////////////////////////////////////////////////////////

            var logger = new StringBuilderHttpMessageLogger();

            /*
             *  Could also use the Console if preferred...
             *
             *  var logger = new ConsoleHttpMessageLogger();
             */

            // Configure our client
            CommunityGraphClientOptions clientOptions = new CommunityGraphClientOptions()
            {
                UserAgent = "SiteDesignSample"
            };
            var graphServiceClient = CommunityGraphClientFactory.Create(clientOptions, logger, ap);

            ///////////////////////////////////////
            //
            // Setup is complete, run the sample
            //
            ///////////////////////////////////////

            var WebUrl = $"https://{sharepointDomain}{siteCollectionPath}";

            var siteScript = new SiteScriptMetadata()
            {
                Title       = "Green Theme",
                Description = "Apply the Green Theme",
                Content     = "{\"$schema\": \"schema.json\",\"actions\": [{\"verb\": \"applyTheme\",\"themeName\": \"Green\"}],\"bindata\": { },\"version\": 1}",
            };

            var createdScript = await graphServiceClient
                                .SharePointAPI(WebUrl)
                                .SiteScripts
                                .Request()
                                .CreateAsync(siteScript);

            var siteDesign = new SiteDesignMetadata()
            {
                Title         = "Green Theme",
                Description   = "Apply the Green theme",
                SiteScriptIds = new System.Collections.Generic.List <Guid>()
                {
                    new Guid(createdScript.Id)
                },
                WebTemplate = "64"                 // 64 = Team Site, 68 = Communication Site, 1 = Groupless Team Site
            };

            var createdDesign = await graphServiceClient
                                .SharePointAPI(WebUrl)
                                .SiteDesigns
                                .Request()
                                .CreateAsync(siteDesign);

            var applySiteDesignRequest = new ApplySiteDesignRequest
            {
                SiteDesignId = createdDesign.Id,
                WebUrl       = WebUrl
            };

            var applySiteDesignResponse = await graphServiceClient
                                          .SharePointAPI(WebUrl)
                                          .SiteDesigns.Request()
                                          .ApplyAsync(applySiteDesignRequest);

            foreach (var outcome in applySiteDesignResponse.ActionOutcomes)
            {
                Console.WriteLine(outcome.OutcomeText);
            }


            Console.WriteLine("Press enter to show log");
            Console.ReadLine();
            Console.WriteLine();
            var log = logger.GetLog();

            Console.WriteLine(log);
        }
        public static async Task Run()
        {
            /////////////////
            //
            // Configuration
            //
            /////////////////

            AzureAdOptions azureAdOptions = new AzureAdOptions();

            var settingsFilename = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "appsettings.json");
            var builder          = new ConfigurationBuilder()
                                   .AddJsonFile(settingsFilename, optional: false);
            var config = builder.Build();

            config.Bind("AzureAd", azureAdOptions);

            // Log Http Request/Response
            var logger = new StringBuilderHttpMessageLogger();

            // Use the system browser to login
            //  https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/System-Browser-on-.Net-Core#how-to-use-the-system-browser-ie-the-default-browser-of-the-os

            var options = new PublicClientApplicationOptions()
            {
                AadAuthorityAudience = AadAuthorityAudience.AzureAdMyOrg,
                AzureCloudInstance   = AzureCloudInstance.AzurePublic,
                ClientId             = azureAdOptions.ClientId,
                TenantId             = azureAdOptions.TenantId,
                RedirectUri          = "http://localhost"
            };

            // Create the public client application (desktop app), with a default redirect URI
            var pca = PublicClientApplicationBuilder.CreateWithApplicationOptions(options)
                      .Build();

            // Enable a simple token cache serialiation so that the user does not need to
            // re-sign-in each time the application is run
            TokenCacheHelper.EnableSerialization(pca.UserTokenCache);

            // Create an authentication provider to attach the token to requests
            var scopes = new string[] { "https://graph.microsoft.com/User.ReadBasic.All" };
            IAuthenticationProvider ap = new InteractiveAuthenticationProvider(pca, scopes);


            ////////////////////////////////////////////////////////////////
            //
            //  Create a GraphClient with the Logging handler
            //
            ////////////////////////////////////////////////////////////////

            // Configure our client
            CommunityGraphClientOptions clientOptions = new CommunityGraphClientOptions()
            {
                UserAgent = "NOVA365-UG-Demo"
            };

            var graphServiceClient = CommunityGraphClientFactory.Create(clientOptions, logger, ap);


            ////////////////////////////
            //
            // Setup is complete, run the sample
            //
            ////////////////////////////

            try
            {
                var searchFor    = "al";
                var filterString = $"startswith(givenName,'{searchFor}') or startswith(surname,'{searchFor}') or startswith(displayName,'{searchFor}')";

                var users = await graphServiceClient
                            .Users
                            .Request()
                            .Filter(filterString)
                            .GetAsync();


                var u = await graphServiceClient.Users["*****@*****.**"].Request().GetAsync();

                var g = new Microsoft.Graph.Group
                {
                    DisplayName     = "NOVA 365 UG",
                    MailEnabled     = false,
                    MailNickname    = "novaug",
                    SecurityEnabled = true
                };

                g.AddMember(u.Id);
                g = await graphServiceClient.Groups.Request().AddAsync(g);

                Console.WriteLine($"Group: {g.DisplayName} ({g.Id})");
            }
            catch (Exception ex)
            {
                await logger.WriteLine("");

                await logger.WriteLine("================== Exception caught ==================");

                await logger.WriteLine(ex.ToString());
            }


            Console.WriteLine("Press enter to show log");
            Console.ReadLine();
            Console.WriteLine();
            var log = logger.GetLog();

            Console.WriteLine(log);
        }
        public static async Task Run()
        {
            /////////////////////////////
            //
            // Programmer configuration
            //
            /////////////////////////////

            var sharepointDomain   = "demo.sharepoint.com";
            var siteCollectionPath = "/sites/SiteDesignTest";

            /////////////////
            //
            // Configuration
            //
            /////////////////

            AzureAdOptions azureAdOptions = new AzureAdOptions();

            var settingsFilename = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "appsettings.json");
            var builder          = new ConfigurationBuilder()
                                   .AddJsonFile(settingsFilename, optional: false)
                                   .AddUserSecrets <Program>();
            var config = builder.Build();

            config.Bind("AzureAd", azureAdOptions);

            ////////////////////////////
            //
            // Graph Client with Logger
            //
            ////////////////////////////

            var logger = new StringBuilderHttpMessageLogger();

            /*
             *  Could also use the Console if preferred...
             *
             *  var logger = new ConsoleHttpMessageLogger();
             */

            var pca = PublicClientApplicationBuilder
                      .Create(azureAdOptions.ClientId)
                      .WithTenantId(azureAdOptions.TenantId)
                      .Build();

            var scopes = new string[] { $"https://{sharepointDomain}/AllSites.FullControl" };
            IAuthenticationProvider ap = new DeviceCodeProvider(pca, scopes);

            using (LoggingMessageHandler loggingHandler = new LoggingMessageHandler(logger))
                using (HttpProvider hp = new HttpProvider(loggingHandler, false, new Serializer()))
                {
                    GraphServiceClient graphServiceClient = new GraphServiceClient(ap, hp);

                    ////////////////////////////
                    //
                    // Setup is complete, run the sample
                    //
                    ////////////////////////////

                    var WebUrl = $"https://{sharepointDomain}{siteCollectionPath}";

                    var siteScript = new SiteScriptMetadata()
                    {
                        Title       = "Green Theme",
                        Description = "Apply the Green Theme",
                        Content     = "{\"$schema\": \"schema.json\",\"actions\": [{\"verb\": \"applyTheme\",\"themeName\": \"Green\"}],\"bindata\": { },\"version\": 1}",
                    };

                    var createdScript = await graphServiceClient
                                        .SharePointAPI(WebUrl)
                                        .SiteScripts
                                        .Request()
                                        .CreateAsync(siteScript);

                    var siteDesign = new SiteDesignMetadata()
                    {
                        Title         = "Green Theme",
                        Description   = "Apply the Green theme",
                        SiteScriptIds = new System.Collections.Generic.List <Guid>()
                        {
                            new Guid(createdScript.Id)
                        },
                        WebTemplate = "64"                 // 64 = Team Site, 68 = Communication Site, 1 = Groupless Team Site
                    };

                    var createdDesign = await graphServiceClient
                                        .SharePointAPI(WebUrl)
                                        .SiteDesigns
                                        .Request()
                                        .CreateAsync(siteDesign);

                    var applySiteDesignRequest = new ApplySiteDesignRequest
                    {
                        SiteDesignId = createdDesign.Id,
                        WebUrl       = WebUrl
                    };

                    var applySiteDesignResponse = await graphServiceClient
                                                  .SharePointAPI(WebUrl)
                                                  .SiteDesigns.Request()
                                                  .ApplyAsync(applySiteDesignRequest);

                    foreach (var outcome in applySiteDesignResponse.ActionOutcomes)
                    {
                        Console.WriteLine(outcome.OutcomeText);
                    }


                    Console.WriteLine("Press enter to show log");
                    Console.ReadLine();
                    Console.WriteLine();
                    var log = logger.GetLog();
                    Console.WriteLine(log);
                }
        }
        public static async Task Run()
        {
            /////////////////////////////
            //
            // Programmer configuration
            //
            /////////////////////////////

            var sharepointDomain   = "demo.sharepoint.com";
            var siteCollectionPath = "/sites/SiteGroupsTest";

            /////////////////
            //
            // Configuration
            //
            /////////////////

            AzureAdOptions azureAdOptions = new AzureAdOptions();

            var settingsFilename = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "appsettings.json");
            var builder          = new ConfigurationBuilder()
                                   .AddJsonFile(settingsFilename, optional: false)
                                   .AddUserSecrets <Program>();
            var config = builder.Build();

            config.Bind("AzureAd", azureAdOptions);

            ////////////////////////////
            //
            // Graph Client with Logger
            //
            ////////////////////////////

            var logger = new StringBuilderHttpMessageLogger();

            /*
             *  Could also use the Console if preferred...
             *
             *  var logger = new ConsoleHttpMessageLogger();
             */

            var pca = PublicClientApplicationBuilder
                      .Create(azureAdOptions.ClientId)
                      .WithTenantId(azureAdOptions.TenantId)
                      .Build();

            var scopes = new string[] { $"https://{sharepointDomain}/AllSites.FullControl" };
            IAuthenticationProvider ap = new DeviceCodeProvider(pca, scopes);

            using (LoggingMessageHandler loggingHandler = new LoggingMessageHandler(logger))
                using (HttpProvider hp = new HttpProvider(loggingHandler, false, new Serializer()))
                {
                    GraphServiceClient graphServiceClient = new GraphServiceClient(ap, hp);

                    ////////////////////////////
                    //
                    // Setup is complete, run the sample
                    //
                    ////////////////////////////

                    var WebUrl = $"https://{sharepointDomain}{siteCollectionPath}";

                    var groups = await graphServiceClient
                                 .SharePointAPI(WebUrl)
                                 .Web
                                 .SiteGroups
                                 .Request()
                                 .Expand(g => g.Users)
                                 .Expand("Owner")
                                 .GetAsync();


                    foreach (var group in groups)
                    {
                        Console.WriteLine(group.Title);
                        foreach (var user in group.Users)
                        {
                            Console.WriteLine($"  {user.LoginName}");
                        }
                    }

                    Console.WriteLine("Press enter to show log");
                    Console.ReadLine();
                    Console.WriteLine();
                    var log = logger.GetLog();
                    Console.WriteLine(log);
                }
        }
Exemple #9
0
        public static async Task Run()
        {
            ////////////////////////////////
            //
            // Azure AD Configuration
            //
            ////////////////////////////////

            AzureAdOptions azureAdOptions = new AzureAdOptions();

            var settingsFilename = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "appsettings.json");
            var builder          = new ConfigurationBuilder()
                                   .AddJsonFile(settingsFilename, optional: false)
                                   .AddUserSecrets <Program>();
            var config = builder.Build();

            config.Bind("AzureAd", azureAdOptions);

            /////////////////////////////////////
            //
            // Client Application Configuration
            //
            /////////////////////////////////////

            var options = new PublicClientApplicationOptions()
            {
                AadAuthorityAudience = AadAuthorityAudience.AzureAdMyOrg,
                AzureCloudInstance   = AzureCloudInstance.AzurePublic,
                ClientId             = azureAdOptions.ClientId,
                TenantId             = azureAdOptions.TenantId,
                RedirectUri          = "http://localhost"
            };

            // Create the public client application (desktop app), with a default redirect URI
            var pca = PublicClientApplicationBuilder
                      .CreateWithApplicationOptions(options)
                      .Build();

            // Enable a simple token cache serialiation so that the user does not need to
            // re-sign-in each time the application is run
            TokenCacheHelper.EnableSerialization(pca.UserTokenCache);

            ///////////////////////////////////////////////
            //
            //  Auth Provider - Device Code in this sample
            //
            ///////////////////////////////////////////////

            // Create an authentication provider to attach the token to requests
            var scopes = new string[] { "https://graph.microsoft.com/Mail.Read" };
            IAuthenticationProvider ap = new DeviceCodeProvider(pca, scopes);

            ////////////////////////////////////////////////////////////////
            //
            //  Create a GraphClient with the Logging handler
            //
            ////////////////////////////////////////////////////////////////

            var logger = new StringBuilderHttpMessageLogger();

            /*
             *  Could also use the Console if preferred...
             *
             *  var logger = new ConsoleHttpMessageLogger();
             */

            // Configure our client
            CommunityGraphClientOptions clientOptions = new CommunityGraphClientOptions()
            {
                UserAgent = "ImmutableIdsSample"
            };

            var graphServiceClient = CommunityGraphClientFactory.Create(clientOptions, logger, ap);

            ///////////////////////////////////////
            //
            // Setup is complete, run the sample
            //
            ///////////////////////////////////////

            var messages =
                await graphServiceClient
                .Me
                .Messages
                .Request()
                .Top(1)
                .GetAsync();

            Console.WriteLine($"ID: {messages.CurrentPage[0].Id}");

            Console.WriteLine();

            var messagesI =
                await graphServiceClient
                .Me
                .Messages
                .Request()
                .WithImmutableId()
                .Top(1)
                .GetAsync();

            Console.WriteLine($"ImmutableId: {messagesI.CurrentPage[0].Id}");
            Console.WriteLine();

            Console.WriteLine("Press enter to show log");
            Console.ReadLine();
            Console.WriteLine();
            Console.WriteLine(logger.GetLog());
        }
Exemple #10
0
        public static async Task Run()
        {
            ////////////////////////////////
            //
            // Azure AD Configuration
            //
            ////////////////////////////////

            AzureAdOptions azureAdOptions = new AzureAdOptions();

            var settingsFilename = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "appsettings.json");
            var builder          = new ConfigurationBuilder()
                                   .AddJsonFile(settingsFilename, optional: false)
                                   .AddUserSecrets <Program>();
            var config = builder.Build();

            config.Bind("AzureAd", azureAdOptions);

            /////////////////////////////////////
            //
            // Client Application Configuration
            //
            /////////////////////////////////////

            var options = new PublicClientApplicationOptions()
            {
                AadAuthorityAudience = AadAuthorityAudience.AzureAdMyOrg,
                AzureCloudInstance   = AzureCloudInstance.AzurePublic,
                ClientId             = azureAdOptions.ClientId,
                TenantId             = azureAdOptions.TenantId,
                RedirectUri          = "http://localhost"
            };

            // Create the public client application (desktop app), with a default redirect URI
            var pca = PublicClientApplicationBuilder
                      .CreateWithApplicationOptions(options)
                      .Build();

            // Enable a simple token cache serialiation so that the user does not need to
            // re-sign-in each time the application is run
            TokenCacheHelper.EnableSerialization(pca.UserTokenCache);

            ///////////////////////////////////////////////
            //
            //  Auth Provider - Interactive in this sample
            //
            ///////////////////////////////////////////////

            // Use the system browser to login
            //  https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/System-Browser-on-.Net-Core#how-to-use-the-system-browser-ie-the-default-browser-of-the-os

            // Create an authentication provider to attach the token to requests
            var scopes = new string[] { "https://graph.microsoft.com/Directory.AccessAsUser.All" };
            IAuthenticationProvider ap = new InteractiveAuthenticationProvider(pca, scopes);

            ////////////////////////////////////////////////////////////////
            //
            //  Create a GraphClient
            //
            ////////////////////////////////////////////////////////////////

            // Configure our client
            CommunityGraphClientOptions clientOptions = new CommunityGraphClientOptions()
            {
                UserAgent = "ExpiringClientSecretsSample"
            };

            var graphServiceClient = CommunityGraphClientFactory.Create(clientOptions, ap);

            ///////////////////////////////////////
            //
            // Setup is complete, run the sample
            //
            ///////////////////////////////////////


            bool iteratorItemCallback(Application a)                // equivalent to Func<Application, bool> iteratorItemCallback = (a) => {}
            {
                // process the current item
                if (a.PasswordCredentials.Any(c => c.EndDateTime < DateTime.UtcNow.AddDays(30)))
                {
                    Console.WriteLine($"{a.DisplayName} ({a.AppId})");
                }


                // return true to indicate iteration should continue
                return(true);
            }

            var results = await graphServiceClient
                          .Applications
                          .Request()
                          .Top(999)
                          .GetAsync();

            var appIterator = PageIterator <Application> .CreatePageIterator(graphServiceClient, results, iteratorItemCallback);

            await appIterator.IterateAsync();
        }
        public static async Task Run()
        {
            /////////////////
            //
            // Configuration
            //
            /////////////////

            AzureAdOptions azureAdOptions = new AzureAdOptions();

            var settingsFilename = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "appsettings.json");
            var builder          = new ConfigurationBuilder()
                                   .AddJsonFile(settingsFilename, optional: false)
                                   .AddUserSecrets <Program>();
            var config = builder.Build();

            config.Bind("AzureAd", azureAdOptions);

            ////////////////////////////
            //
            // Graph Client with Logger
            //
            ////////////////////////////

            var logger = new StringBuilderHttpMessageLogger();

            /*
             *  Could also use the Console if preferred...
             *
             *  var logger = new ConsoleHttpMessageLogger();
             */

            var pca = PublicClientApplicationBuilder
                      .Create(azureAdOptions.ClientId)
                      .WithTenantId(azureAdOptions.TenantId)
                      .Build();

            var scopes = new string[] { "https://graph.microsoft.com/Mail.Read" };
            IAuthenticationProvider ap = new DeviceCodeProvider(pca, scopes);

            using (LoggingMessageHandler loggingHandler = new LoggingMessageHandler(logger))
                using (HttpProvider hp = new HttpProvider(loggingHandler, false, new Serializer()))
                {
                    GraphServiceClient graphServiceClient = new GraphServiceClient(ap, hp);


                    ////////////////////////////
                    //
                    // Setup is complete, run the sample
                    //
                    ////////////////////////////

                    var messages =
                        await graphServiceClient
                        .Me
                        .Messages
                        .Request()
                        .Top(1)
                        .GetAsync();

                    Console.WriteLine($"ID: {messages.CurrentPage[0].Id}");

                    Console.WriteLine();

                    var messagesI =
                        await graphServiceClient
                        .Me
                        .Messages
                        .Request()
                        .WithImmutableId()
                        .Top(1)
                        .GetAsync();

                    Console.WriteLine($"ImmutableId: {messagesI.CurrentPage[0].Id}");
                    Console.WriteLine();

                    Console.WriteLine("Press enter to show log");
                    Console.ReadLine();
                    Console.WriteLine();
                    Console.WriteLine(logger.GetLog());
                }
        }
Exemple #12
0
        public static async Task Run()
        {
            /////////////////////////////
            //
            // Programmer configuration
            //
            /////////////////////////////

            var sharepointDomain   = "demo.sharepoint.com";
            var siteCollectionPath = "/sites/GraphCommunityDemo";

            /////////////////
            //
            // Configuration
            //
            /////////////////

            AzureAdOptions azureAdOptions = new AzureAdOptions();

            var settingsFilename = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "appsettings.json");
            var builder          = new ConfigurationBuilder()
                                   .AddJsonFile(settingsFilename, optional: false)
                                   .AddUserSecrets <Program>();
            var config = builder.Build();

            config.Bind("AzureAd", azureAdOptions);

            ////////////////////////////
            //
            // Graph Client with Logger
            //
            ////////////////////////////

            var logger = new StringBuilderHttpMessageLogger();

            /*
             *  Could also use the Console if preferred...
             *
             *  var logger = new ConsoleHttpMessageLogger();
             */

            var pca = PublicClientApplicationBuilder
                      .Create(azureAdOptions.ClientId)
                      .WithTenantId(azureAdOptions.TenantId)
                      .Build();

            var scopes = new string[] { $"https://{sharepointDomain}/AllSites.FullControl" };
            IAuthenticationProvider ap = new DeviceCodeProvider(pca, scopes);

            using (LoggingMessageHandler loggingHandler = new LoggingMessageHandler(logger))
                using (HttpProvider hp = new HttpProvider(loggingHandler, false, new Serializer()))
                {
                    GraphServiceClient graphServiceClient = new GraphServiceClient(ap, hp);


                    ////////////////////////////
                    //
                    // Setup is complete, run the sample
                    //
                    ////////////////////////////

                    var WebUrl = $"https://{sharepointDomain}{siteCollectionPath}";

                    var web = await graphServiceClient
                              .SharePointAPI(WebUrl)
                              .Web
                              .Request()
                              .GetAsync();

                    var changeToken = web.CurrentChangeToken;
                    Console.WriteLine($"current change token: {changeToken.StringValue}");

                    Console.WriteLine($"Make an update to the site {WebUrl}");
                    Console.WriteLine("Press enter to continue");
                    Console.ReadLine();

                    var qry = new ChangeQuery(true, true);
                    qry.ChangeTokenStart = changeToken;

                    var changes = await graphServiceClient
                                  .SharePointAPI(WebUrl)
                                  .Web
                                  .Request()
                                  .GetChangesAsync(qry);

                    Console.WriteLine(changes.Count);

                    foreach (var item in changes)
                    {
                        Console.WriteLine($"{item.ChangeType}");
                    }

                    Console.WriteLine("Press enter to show log");
                    Console.ReadLine();
                    Console.WriteLine();
                    var log = logger.GetLog();
                    Console.WriteLine(log);
                }
        }