Esempio n. 1
0
        public static async Task RemoveThirdPartAPIPermissions(ActiveDirectoryClient client, string thirdPartyClientId)
        {
            var spoCeServicePrinicipal = await client.ServicePrincipals
                                         .Where(sp => sp.AppId == GlobalConstants.SpoCeApplicationId).ExecuteSingleAsync();

            var thirdPartyServicePrincipal = await client.ServicePrincipals
                                             .Where(sp => sp.AppId == thirdPartyClientId).ExecuteSingleAsync();

            var grants = await client.Oauth2PermissionGrants.ExecuteAsync();

            OAuth2PermissionGrant existingGrant = null;

            foreach (IOAuth2PermissionGrant grant in grants.CurrentPage)
            {
                if (grant.ClientId == spoCeServicePrinicipal.ObjectId &&
                    grant.ResourceId == thirdPartyServicePrincipal.ObjectId)
                {
                    existingGrant = (OAuth2PermissionGrant)grant;
                }
            }

            if (existingGrant != null)
            {
                await existingGrant.DeleteAsync();
            }
        }
        /// <summary>
        /// Admin consent to API permissions
        /// </summary>
        /// <param name="graphServiceClient"></param>
        /// <param name="scopesPerResource"></param>
        /// <returns></returns>
        private static async Task AddAdminConsentToApiPermissions(
            GraphServiceClient graphServiceClient,
            ServicePrincipal servicePrincipal,
            IEnumerable <IGrouping <string, ResourceAndScope> >?scopesPerResource)
        {
            // Consent to the scopes
            if (scopesPerResource != null)
            {
                foreach (var g in scopesPerResource)
                {
                    IEnumerable <ResourceAndScope> resourceAndScopes = g;

                    var oAuth2PermissionGrant = new OAuth2PermissionGrant
                    {
                        ClientId    = servicePrincipal.Id,
                        ConsentType = "AllPrincipals",
                        PrincipalId = null,
                        ResourceId  = resourceAndScopes.FirstOrDefault()?.ResourceServicePrincipalId,
                        Scope       = string.Join(" ", resourceAndScopes.Select(r => r.Scope))
                    };

                    // TODO: See https://github.com/jmprieur/app-provisonning-tool/issues/9.
                    // We need to process the case where the developer is not a tenant admin
                    await graphServiceClient.Oauth2PermissionGrants
                    .Request()
                    .AddAsync(oAuth2PermissionGrant);
                }
            }
        }
Esempio n. 3
0
 public virtual Response <OAuth2PermissionGrant> Create(OAuth2PermissionGrant body = null, CancellationToken cancellationToken = default)
 {
     using var scope = _clientDiagnostics.CreateScope("OAuth2PermissionGrantClient.Create");
     scope.Start();
     try
     {
         return(RestClient.Create(body, cancellationToken));
     }
     catch (Exception e)
     {
         scope.Failed(e);
         throw;
     }
 }
Esempio n. 4
0
 public virtual async Task <Response <OAuth2PermissionGrant> > CreateAsync(OAuth2PermissionGrant body = null, CancellationToken cancellationToken = default)
 {
     using var scope = _clientDiagnostics.CreateScope("OAuth2PermissionGrantClient.Create");
     scope.Start();
     try
     {
         return(await RestClient.CreateAsync(body, cancellationToken).ConfigureAwait(false));
     }
     catch (Exception e)
     {
         scope.Failed(e);
         throw;
     }
 }
        public async Task GrantAdminConsentToClientApplicationAsync(
            ServicePrincipal serviceApplicationSP,
            ServicePrincipal clientApplicationSP,
            CancellationToken cancellationToken = default
            )
        {
            // Grant admin consent for service application "user_impersonation" API permissions of client application
            var clientApplicationOAuth2PermissionGrantUserImpersonationDefinition = new OAuth2PermissionGrant {
                ConsentType = "AllPrincipals",
                ClientId    = clientApplicationSP.Id,
                ResourceId  = serviceApplicationSP.Id,
                Scope       = "user_impersonation",
                StartTime   = DateTimeOffset.UtcNow,
                ExpiryTime  = DateTimeOffset.UtcNow.AddYears(2)
            };

            await _graphServiceClient
            .Oauth2PermissionGrants
            .Request()
            .AddAsync(
                clientApplicationOAuth2PermissionGrantUserImpersonationDefinition,
                cancellationToken
                );

            // Grant admin consent for Microsoft Graph "User.Read" API permissions of client application
            var microsoftGraphApplicationSP = await GetServicePrincipalByAppIdAsync(
                AzureAppsConstants.MicrosoftGraph.AppId,
                cancellationToken
                );

            var clientApplicationOAuth2PermissionGrantUserReadDefinition = new OAuth2PermissionGrant {
                ConsentType = "AllPrincipals",
                ClientId    = clientApplicationSP.Id,
                ResourceId  = microsoftGraphApplicationSP.Id,
                Scope       = "User.Read",
                StartTime   = DateTimeOffset.UtcNow,
                ExpiryTime  = DateTimeOffset.UtcNow.AddYears(2)
            };

            await _graphServiceClient
            .Oauth2PermissionGrants
            .Request()
            .AddAsync(
                clientApplicationOAuth2PermissionGrantUserReadDefinition,
                cancellationToken
                );
        }
        private async Task AddApiPermissionFromBlazorwasmHostedSpaToServerApi(
            GraphServiceClient graphServiceClient,
            Application createdApplication,
            ServicePrincipal createdServicePrincipal,
            bool isB2C)
        {
            var requiredResourceAccess   = new List <RequiredResourceAccess>();
            var resourcesAccessAndScopes = new List <ResourceAndScope>
            {
                new ResourceAndScope($"api://{createdApplication.AppId}", "access_as_user")
                {
                    ResourceServicePrincipalId = createdServicePrincipal.Id
                }
            };

            await AddPermission(
                graphServiceClient,
                requiredResourceAccess,
                resourcesAccessAndScopes.GroupBy(r => r.Resource).First()).ConfigureAwait(false);

            Application applicationToUpdate = new Application
            {
                RequiredResourceAccess = requiredResourceAccess
            };

            await graphServiceClient.Applications[createdApplication.Id]
            .Request()
            .UpdateAsync(applicationToUpdate).ConfigureAwait(false);

            if (isB2C)
            {
                var oAuth2PermissionGrant = new OAuth2PermissionGrant
                {
                    ClientId    = createdServicePrincipal.Id,
                    ConsentType = "AllPrincipals",
                    PrincipalId = null,
                    ResourceId  = createdServicePrincipal.Id,
                    Scope       = "access_as_user"
                };

                await graphServiceClient.Oauth2PermissionGrants
                .Request()
                .AddAsync(oAuth2PermissionGrant).ConfigureAwait(false);
            }
        }
        /// <summary>
        /// Add new entity to oauth2PermissionGrants
        /// <param name="body"></param>
        /// <param name="requestConfiguration">Configuration for the request such as headers, query parameters, and middleware options.</param>
        /// </summary>
        public RequestInformation CreatePostRequestInformation(OAuth2PermissionGrant body, Action <Oauth2PermissionGrantsRequestBuilderPostRequestConfiguration> requestConfiguration = default)
        {
            _ = body ?? throw new ArgumentNullException(nameof(body));
            var requestInfo = new RequestInformation {
                HttpMethod     = Method.POST,
                UrlTemplate    = UrlTemplate,
                PathParameters = PathParameters,
            };

            requestInfo.SetContentFromParsable(RequestAdapter, "application/json", body);
            if (requestConfiguration != null)
            {
                var requestConfig = new Oauth2PermissionGrantsRequestBuilderPostRequestConfiguration();
                requestConfiguration.Invoke(requestConfig);
                requestInfo.AddRequestOptions(requestConfig.Options);
                requestInfo.AddHeaders(requestConfig.Headers);
            }
            return(requestInfo);
        }
Esempio n. 8
0
        public static async Task AddWindowsAdPermissions(ActiveDirectoryClient client, string scope)
        {
            var spoCeServicePrinicipal = await client.ServicePrincipals
                                         .Where(sp => sp.AppId == GlobalConstants.SpoCeApplicationId).ExecuteSingleAsync();

            var windowsAdServicePrincipal = await client.ServicePrincipals
                                            .Where(sp => sp.AppId == GlobalConstants.WindowsAzureActiveDirectoryAppId).ExecuteSingleAsync();

            var grants = await client.Oauth2PermissionGrants.ExecuteAsync();

            OAuth2PermissionGrant existingGrant = null;

            foreach (IOAuth2PermissionGrant grant in grants.CurrentPage)
            {
                if (grant.ClientId == spoCeServicePrinicipal.ObjectId &&
                    grant.ResourceId == windowsAdServicePrincipal.ObjectId)
                {
                    existingGrant = (OAuth2PermissionGrant)grant;
                }
            }

            if (existingGrant != null)
            {
                existingGrant.Scope = scope;
                await existingGrant.UpdateAsync();
            }
            else
            {
                var auth2PermissionGrant = new OAuth2PermissionGrant
                {
                    ClientId    = spoCeServicePrinicipal.ObjectId,
                    ConsentType = "AllPrincipals",
                    PrincipalId = null,
                    ExpiryTime  = DateTime.Now.AddYears(10),
                    ResourceId  = windowsAdServicePrincipal.ObjectId,
                    Scope       = scope
                };

                await client.Oauth2PermissionGrants.AddOAuth2PermissionGrantAsync(auth2PermissionGrant);
            }
        }
        /// <summary>
        /// Register Application to Azure AD
        /// </summary>
        /// <returns>registered application's clientid</returns>
        public string RegisterApp()
        {
            authContext = new AuthenticationContext(props.Authority);

            // Application Name
            string appName = "CRM for LINQPad";

            ActiveDirectoryClient activeDirectoryClient;

            int i = 0;

            while (true)
            {
                // Instantiate ActiveDirectoryClient
                activeDirectoryClient = GetActiveDirectoryClientAsApplication(useCurrentUser);

                if (CheckAzureAdPrivilege(activeDirectoryClient))
                {
                    break;
                }
                else
                {
                    MessageBox.Show("Current login user does not have privilege to register an applicaiton to the Azure AD. You need to login as Company Admin so that it can reigster an applicaiton, or cancel the wizard, then enter ClientId/RedirectUri manually.");
                    // Clear the ADAL cache.
                    authContext.TokenCache.Clear();
                    useCurrentUser = false;
                    if (i == 1)
                    {
                        return(null);
                    }
                    else
                    {
                        i++;
                    }
                }
            }

            // Check if same name application already exists.
            var existingApp = activeDirectoryClient.Applications
                              .Where(x => x.DisplayName == appName)
                              .ExecuteAsync().Result.CurrentPage.FirstOrDefault();

            // If it is already registered, then return existing clientid.
            if (existingApp != null && existingApp.RequiredResourceAccess.Count() == 2)
            {
                return(existingApp.AppId);
            }
            else
            {
                existingApp.DeleteAsync().Wait();
            }

            // Instantiate Application to Azure AD.
            IApplication myapp = new Microsoft.Azure.ActiveDirectory.GraphClient.Application();

            myapp.DisplayName = appName;
            var redirectUri = "http://localhost/linqpad";

            myapp.ReplyUrls.Add(redirectUri);
            props.RedirectUri  = redirectUri;
            myapp.PublicClient = true;
            // Mark this only to this tenant
            myapp.AvailableToOtherTenants = false;

            // Create the Application to Azure AD.
            activeDirectoryClient.Applications.AddApplicationAsync(myapp).Wait();

            // Obtain the created Application.
            var createdApp = activeDirectoryClient.Applications
                             .Where(x => x.DisplayName == appName)
                             .ExecuteAsync().Result.CurrentPage.FirstOrDefault();

            // Instantiate Service regarding to the application.
            IServicePrincipal myservice = new ServicePrincipal();

            myservice.AppId = createdApp.AppId;
            myservice.Tags.Add("WindowsAzureActiveDirectoryIntegratedApp");

            // Create the Service.
            activeDirectoryClient.ServicePrincipals.AddServicePrincipalAsync(myservice).Wait();

            // Obtain the created Service.
            var createdService = activeDirectoryClient.ServicePrincipals
                                 .Where(x => x.DisplayName == appName)
                                 .ExecuteAsync().Result.CurrentPage.FirstOrDefault();

            // Set permissions.
            // Get Microsoft.Azure.ActiveDirectory Service.
            var service1 = activeDirectoryClient.ServicePrincipals
                           .Where(x => x.AppId == "00000002-0000-0000-c000-000000000000")
                           .ExecuteAsync().Result.CurrentPage.FirstOrDefault();

            // Instantiate UserProfile.Read OAuth2PermissionGrant for the Service
            OAuth2PermissionGrant grant0 = new OAuth2PermissionGrant();

            grant0.ClientId    = createdService.ObjectId;
            grant0.ResourceId  = service1.ObjectId;
            grant0.ConsentType = "AllPrincipals";
            grant0.Scope       = "User.Read";
            grant0.ExpiryTime  = DateTime.Now.AddYears(1);

            // Create the OAuth2PermissionGrant
            activeDirectoryClient.Oauth2PermissionGrants.AddOAuth2PermissionGrantAsync(grant0).Wait();

            // Get Microsoft.CRM Service.
            var service2 = activeDirectoryClient.ServicePrincipals
                           .Where(x => x.AppId == "00000007-0000-0000-c000-000000000000")
                           .ExecuteAsync().Result.CurrentPage.FirstOrDefault();

            // Instantiate user_impersonation OAuth2PermissionGrant for the Service
            OAuth2PermissionGrant grant = new OAuth2PermissionGrant();

            grant.ClientId    = createdService.ObjectId;
            grant.ResourceId  = service2.ObjectId;
            grant.ConsentType = "AllPrincipals";
            grant.Scope       = "user_impersonation";
            grant.ExpiryTime  = DateTime.Now.AddYears(1);

            // Create the OAuth2PermissionGrant
            activeDirectoryClient.Oauth2PermissionGrants.AddOAuth2PermissionGrantAsync(grant).Wait();

            // Create RequiredResourceAccess
            // Instantiate ResourceAccess for Microsoft.Azure.ActiveDirectory/UserProfile.Read permission.
            ResourceAccess resourceAccess1 = new ResourceAccess();

            resourceAccess1.Id   = service1.Oauth2Permissions.Where(x => x.Value == "User.Read").First().Id;
            resourceAccess1.Type = "Scope";
            // Instantiate RequiredResourceAccess and assign the ResourceAccess
            RequiredResourceAccess requiredresourceAccess1 = new RequiredResourceAccess();

            requiredresourceAccess1.ResourceAppId = service1.AppId;
            requiredresourceAccess1.ResourceAccess.Add(resourceAccess1);

            // Instantiate ResourceAccess for Microsoft.CRM/user_impersonation.Read permission.
            ResourceAccess resourceAccess2 = new ResourceAccess();

            resourceAccess2.Id   = service2.Oauth2Permissions.Where(x => x.Value == "user_impersonation").First().Id;
            resourceAccess2.Type = "Scope";
            // Instantiate RequiredResourceAccess and assign the ResourceAccess
            RequiredResourceAccess requiredResourceAccess2 = new RequiredResourceAccess();

            requiredResourceAccess2.ResourceAppId = service2.AppId;
            requiredResourceAccess2.ResourceAccess.Add(resourceAccess2);

            // Add RequiredResourceAccess information to the Application
            createdApp.RequiredResourceAccess.Add(requiredresourceAccess1);
            createdApp.RequiredResourceAccess.Add(requiredResourceAccess2);

            // Update the Application
            createdApp.UpdateAsync().Wait();

            // Once all Azure AD work done, clear ADAL cache again in case user logged in as different user.
            authContext.TokenCache.Clear();

            // Return AppId (ClientId)
            return(createdApp.AppId);
        }
Esempio n. 10
0
        private static void Main()
        {
            // record start DateTime of execution
            string currentDateTime = DateTime.Now.ToUniversalTime().ToString();

            #region Setup Active Directory Client

            //*********************************************************************
            // setup Active Directory Client
            //*********************************************************************
            ActiveDirectoryClient activeDirectoryClient;
            try
            {
                activeDirectoryClient = AuthenticationHelper.GetActiveDirectoryClientAsApplication();
            }
            catch (AuthenticationException ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Acquiring a token failed with the following error: {0}", ex.Message);
                if (ex.InnerException != null)
                {
                    //You should implement retry and back-off logic per the guidance given here:http://msdn.microsoft.com/en-us/library/dn168916.aspx
                    //InnerException Message will contain the HTTP error status codes mentioned in the link above
                    Console.WriteLine("Error detail: {0}", ex.InnerException.Message);
                }
                Console.ResetColor();
                Console.ReadKey();
                return;
            }

            #endregion

            #region TenantDetails

            //*********************************************************************
            // Get Tenant Details
            // Note: update the string TenantId with your TenantId.
            // This can be retrieved from the login Federation Metadata end point:             
            // https://login.windows.net/GraphDir1.onmicrosoft.com/FederationMetadata/2007-06/FederationMetadata.xml
            //  Replace "GraphDir1.onMicrosoft.com" with any domain owned by your organization
            // The returned value from the first xml node "EntityDescriptor", will have a STS URL
            // containing your TenantId e.g. "https://sts.windows.net/4fd2b2f2-ea27-4fe5-a8f3-7b1a7c975f34/" is returned for GraphDir1.onMicrosoft.com
            //*********************************************************************
            VerifiedDomain initialDomain = new VerifiedDomain();
            VerifiedDomain defaultDomain = new VerifiedDomain();
            ITenantDetail tenant = null;
            Console.WriteLine("\n Retrieving Tenant Details");
            try
            {
                List<ITenantDetail> tenantsList = activeDirectoryClient.TenantDetails
                    .Where(tenantDetail => tenantDetail.ObjectId.Equals(Constants.TenantId))
                    .ExecuteAsync().Result.CurrentPage.ToList();
                if (tenantsList.Count > 0)
                {
                    tenant = tenantsList.First();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError getting TenantDetails {0} {1}", e.Message,
                    e.InnerException != null ? e.InnerException.Message : "");
            }

            if (tenant == null)
            {
                Console.WriteLine("Tenant not found");
            }
            else
            {
                TenantDetail tenantDetail = (TenantDetail)tenant;
                Console.WriteLine("Tenant Display Name: " + tenantDetail.DisplayName);

                // Get the Tenant's Verified Domains 
                initialDomain = tenantDetail.VerifiedDomains.First(x => x.Initial.HasValue && x.Initial.Value);
                Console.WriteLine("Initial Domain Name: " + initialDomain.Name);
                defaultDomain = tenantDetail.VerifiedDomains.First(x => [email protected] && [email protected]);
                Console.WriteLine("Default Domain Name: " + defaultDomain.Name);

                // Get Tenant's Tech Contacts
                foreach (string techContact in tenantDetail.TechnicalNotificationMails)
                {
                    Console.WriteLine("Tenant Tech Contact: " + techContact);
                }
            }

            #endregion

            #region Create a new User

            IUser newUser = new User();
            if (defaultDomain.Name != null)
            {
                newUser.DisplayName = "Sample App Demo User (Manager)";
                newUser.UserPrincipalName = Helper.GetRandomString(10) + "@" + defaultDomain.Name;
                newUser.AccountEnabled = true;
                newUser.MailNickname = "SampleAppDemoUserManager";
                newUser.PasswordProfile = new PasswordProfile
                {
                    Password = "******",
                    ForceChangePasswordNextLogin = true
                };
                newUser.UsageLocation = "US";
                try
                {
                    activeDirectoryClient.Users.AddUserAsync(newUser).Wait();
                    Console.WriteLine("\nNew User {0} was created", newUser.DisplayName);
                }
                catch (Exception e)
                {
                    Console.WriteLine("\nError creating new user {0} {1}", e.Message,
                        e.InnerException != null ? e.InnerException.Message : "");
                }
            }

            #endregion

            #region List of max 4 Users by UPN

            //*********************************************************************
            // Demonstrate Getting a list of Users with paging (get 4 users), sorted by displayName
            //*********************************************************************
            int maxUsers = 4;
            try
            {
                Console.WriteLine("\n Retrieving Users");
                List<IUser> users = activeDirectoryClient.Users.OrderBy(user =>
                    user.UserPrincipalName).Take(maxUsers).ExecuteAsync().Result.CurrentPage.ToList();
                foreach (IUser user in users)
                {
                    Console.WriteLine("UserObjectId: {0}  UPN: {1}", user.ObjectId, user.UserPrincipalName);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError getting Users. {0} {1}", e.Message,
                    e.InnerException != null ? e.InnerException.Message : "");
            }

            #endregion

            #region Create a User with a temp Password

            //*********************************************************************************************
            // Create a new User with a temp Password
            //*********************************************************************************************
            IUser userToBeAdded = new User();
            userToBeAdded.DisplayName = "Sample App Demo User";
            userToBeAdded.UserPrincipalName = Helper.GetRandomString(10) + "@" + defaultDomain.Name;
            userToBeAdded.AccountEnabled = true;
            userToBeAdded.MailNickname = "SampleAppDemoUser";
            userToBeAdded.PasswordProfile = new PasswordProfile
            {
                Password = "******",
                ForceChangePasswordNextLogin = true
            };
            userToBeAdded.UsageLocation = "US";
            try
            {
                activeDirectoryClient.Users.AddUserAsync(userToBeAdded).Wait();
                Console.WriteLine("\nNew User {0} was created", userToBeAdded.DisplayName);
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError creating new user. {0} {1}", e.Message,
                    e.InnerException != null ? e.InnerException.Message : "");
            }

            #endregion

            #region Update newly created User

            //*******************************************************************************************
            // update the newly created user's Password, PasswordPolicies and City
            //*********************************************************************************************
            if (userToBeAdded.ObjectId != null)
            {
                // update User's city and reset their User's Password
                userToBeAdded.City = "Seattle";
                userToBeAdded.Country = "UK";
                PasswordProfile PasswordProfile = new PasswordProfile
                {
                    Password = "******",
                    ForceChangePasswordNextLogin = false
                };
                userToBeAdded.PasswordProfile = PasswordProfile;
                userToBeAdded.PasswordPolicies = "DisablePasswordExpiration, DisableStrongPassword";
                try
                {
                    userToBeAdded.UpdateAsync().Wait();
                    Console.WriteLine("\nUser {0} was updated", userToBeAdded.DisplayName);
                }
                catch (Exception e)
                {
                    Console.WriteLine("\nError Updating the user {0} {1}", e.Message,
                        e.InnerException != null ? e.InnerException.Message : "");
                }
            }

            #endregion

            #region Search User by UPN

            // search for a single user by UPN
            string searchString = "admin@" + initialDomain.Name;
            Console.WriteLine("\n Retrieving user with UPN {0}", searchString);
            User retrievedUser = new User();
            List<IUser> retrievedUsers = null;
            try
            {
                retrievedUsers = activeDirectoryClient.Users
                    .Where(user => user.UserPrincipalName.Equals(searchString))
                    .ExecuteAsync().Result.CurrentPage.ToList();
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError getting new user {0} {1}", e.Message,
                    e.InnerException != null ? e.InnerException.Message : "");
            }
            // should only find one user with the specified UPN
            if (retrievedUsers != null && retrievedUsers.Count == 1)
            {
                retrievedUser = (User)retrievedUsers.First();
            }
            else
            {
                Console.WriteLine("User not found {0}", searchString);
            }

            #endregion

            #region User Operations

            if (retrievedUser.UserPrincipalName != null)
            {
                Console.WriteLine("\n Found User: "******"  UPN: " +
                                  retrievedUser.UserPrincipalName);

                #region Assign User a Manager

                //Assigning User a new manager.
                if (newUser.ObjectId != null)
                {
                    Console.WriteLine("\n Assign User {0}, {1} as Manager.", retrievedUser.DisplayName,
                        newUser.DisplayName);
                    retrievedUser.Manager = newUser as DirectoryObject;
                    try
                    {
                        newUser.UpdateAsync().Wait();
                        Console.Write("User {0} is successfully assigned {1} as Manager.", retrievedUser.DisplayName,
                            newUser.DisplayName);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("\nError assigning manager to user. {0} {1}", e.Message,
                            e.InnerException != null ? e.InnerException.Message : "");
                    }
                }

                #endregion

                #region Get User's Manager

                //Get the retrieved user's manager.
                Console.WriteLine("\n Retrieving User {0}'s Manager.", retrievedUser.DisplayName);
                DirectoryObject usersManager = retrievedUser.Manager;
                if (usersManager != null)
                {
                    User manager = usersManager as User;
                    if (manager != null)
                    {
                        Console.WriteLine("User {0} Manager details: \nManager: {1}  UPN: {2}",
                            retrievedUser.DisplayName, manager.DisplayName, manager.UserPrincipalName);
                    }
                }
                else
                {
                    Console.WriteLine("Manager not found.");
                }

                #endregion

                #region Get User's Direct Reports

                //*********************************************************************
                // get the user's Direct Reports
                //*********************************************************************
                if (newUser.ObjectId != null)
                {
                    Console.WriteLine("\n Getting User{0}'s Direct Reports.", newUser.DisplayName);
                    IUserFetcher newUserFetcher = (IUserFetcher)newUser;
                    try
                    {
                        IPagedCollection<IDirectoryObject> directReports =
                            newUserFetcher.DirectReports.ExecuteAsync().Result;
                        do
                        {
                            List<IDirectoryObject> directoryObjects = directReports.CurrentPage.ToList();
                            foreach (IDirectoryObject directoryObject in directoryObjects)
                            {
                                if (directoryObject is User)
                                {
                                    User directReport = directoryObject as User;
                                    Console.WriteLine("User {0} Direct Report is {1}", newUser.UserPrincipalName,
                                        directReport.UserPrincipalName);
                                }
                            }
                            directReports = directReports.GetNextPageAsync().Result;
                        } while (directReports != null);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("\nError getting direct reports of user. {0} {1}", e.Message,
                            e.InnerException != null ? e.InnerException.Message : "");
                    }
                }

                #endregion

                #region Get list of Group IDS, user is member of

                //*********************************************************************
                // get a list of Group IDs that the user is a member of
                //*********************************************************************
                //const bool securityEnabledOnly = false;
                //IEnumerable<string> memberGroups = retrievedUser.GetMemberGroupsAsync(securityEnabledOnly).Result;
                //Console.WriteLine("\n {0} is a member of the following Groups (IDs)", retrievedUser.DisplayName);
                //foreach (String memberGroup in memberGroups)
                //{
                //    Console.WriteLine("Member of Group ID: " + memberGroup);
                //}

                #endregion

                #region Get User's Group And Role Membership, Getting the complete set of objects

                //*********************************************************************
                // get the User's Group and Role membership, getting the complete set of objects
                //*********************************************************************
                Console.WriteLine("\n {0} is a member of the following Group and Roles (IDs)", retrievedUser.DisplayName);
                IUserFetcher retrievedUserFetcher = retrievedUser;
                try
                {
                    IPagedCollection<IDirectoryObject> pagedCollection = retrievedUserFetcher.MemberOf.ExecuteAsync().Result;
                    do
                    {
                        List<IDirectoryObject> directoryObjects = pagedCollection.CurrentPage.ToList();
                        foreach (IDirectoryObject directoryObject in directoryObjects)
                        {
                            if (directoryObject is Group)
                            {
                                Group group = directoryObject as Group;
                                Console.WriteLine(" Group: {0}  Description: {1}", group.DisplayName, group.Description);
                            }
                            if (directoryObject is DirectoryRole)
                            {
                                DirectoryRole role = directoryObject as DirectoryRole;
                                Console.WriteLine(" Role: {0}  Description: {1}", role.DisplayName, role.Description);
                            }
                        }
                        pagedCollection = pagedCollection.GetNextPageAsync().Result;
                    } while (pagedCollection != null);
                }
                catch (Exception e)
                {
                    Console.WriteLine("\nError getting user's groups and roles memberships. {0} {1}", e.Message,
                        e.InnerException != null ? e.InnerException.Message : "");
                }

                #endregion
            }

            #endregion

            #region Search for User (People Picker)

            //*********************************************************************
            // People picker
            // Search for a user using text string "Us" match against userPrincipalName, displayName, giveName, surname   
            //*********************************************************************
            searchString = "Us";
            Console.WriteLine("\nSearching for any user with string {0} in UPN,DisplayName,First or Last Name",
                searchString);
            List<IUser> usersList = null;
            IPagedCollection<IUser> searchResults = null;
            try
            {
                IUserCollection userCollection = activeDirectoryClient.Users;
                searchResults = userCollection.Where(user =>
                    user.UserPrincipalName.StartsWith(searchString) ||
                    user.DisplayName.StartsWith(searchString) ||
                    user.GivenName.StartsWith(searchString) ||
                    user.Surname.StartsWith(searchString)).ExecuteAsync().Result;
                usersList = searchResults.CurrentPage.ToList();
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError getting User {0} {1}", e.Message,
                    e.InnerException != null ? e.InnerException.Message : "");
            }

            if (usersList != null && usersList.Count > 0)
            {
                do
                {
                    usersList = searchResults.CurrentPage.ToList();
                    foreach (IUser user in usersList)
                    {
                        Console.WriteLine("User DisplayName: {0}  UPN: {1}",
                            user.DisplayName, user.UserPrincipalName);
                    }
                    searchResults = searchResults.GetNextPageAsync().Result;
                } while (searchResults != null);
            }
            else
            {
                Console.WriteLine("User not found");
            }

            #endregion

            #region Search for Group using StartWith filter

            //*********************************************************************
            // Search for a group using a startsWith filter (displayName property)
            //*********************************************************************
            Group retrievedGroup = new Group();
            searchString = "My";
            List<IGroup> foundGroups = null;
            try
            {
                foundGroups = activeDirectoryClient.Groups
                    .Where(group => group.DisplayName.StartsWith(searchString))
                    .ExecuteAsync().Result.CurrentPage.ToList();
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError getting Group {0} {1}",
                    e.Message, e.InnerException != null ? e.InnerException.Message : "");
            }
            if (foundGroups != null && foundGroups.Count > 0)
            {
                retrievedGroup = foundGroups.First() as Group;
            }
            else
            {
                Console.WriteLine("Group Not Found");
            }

            #endregion

            #region Assign Member to Group

            if (retrievedGroup.ObjectId != null)
            {
                try
                {
                    retrievedGroup.Members.Add(newUser as DirectoryObject);
                    retrievedGroup.UpdateAsync().Wait();
                }
                catch (Exception e)
                {
                    Console.WriteLine("\nError assigning member to group. {0} {1}",
                        e.Message, e.InnerException != null ? e.InnerException.Message : "");
                }

            }

            #endregion

            #region Get Group members

            if (retrievedGroup.ObjectId != null)
            {
                Console.WriteLine("\n Found Group: " + retrievedGroup.DisplayName + "  " + retrievedGroup.Description);

                //*********************************************************************
                // get the groups' membership - 
                // Note this method retrieves ALL links in one request - please use this method with care - this
                // may return a very large number of objects
                //*********************************************************************
                IGroupFetcher retrievedGroupFetcher = retrievedGroup;
                try
                {
                    IPagedCollection<IDirectoryObject> members = retrievedGroupFetcher.Members.ExecuteAsync().Result;
                    Console.WriteLine(" Members:");
                    do
                    {
                        List<IDirectoryObject> directoryObjects = members.CurrentPage.ToList();
                        foreach (IDirectoryObject member in directoryObjects)
                        {
                            if (member is User)
                            {
                                User user = member as User;
                                Console.WriteLine("User DisplayName: {0}  UPN: {1}",
                                    user.DisplayName,
                                    user.UserPrincipalName);
                            }
                            if (member is Group)
                            {
                                Group group = member as Group;
                                Console.WriteLine("Group DisplayName: {0}", group.DisplayName);
                            }
                            if (member is Contact)
                            {
                                Contact contact = member as Contact;
                                Console.WriteLine("Contact DisplayName: {0}", contact.DisplayName);
                            }
                        }
                        members = members.GetNextPageAsync().Result;
                    } while (members != null);
                }
                catch (Exception e)
                {
                    Console.WriteLine("\nError getting groups' membership. {0} {1}",
                        e.Message, e.InnerException != null ? e.InnerException.Message : "");
                }
            }

            #endregion

            #region Add User to Group

            //*********************************************************************************************
            // Add User to the "WA" Group 
            //*********************************************************************************************
            if (retrievedGroup.ObjectId != null)
            {
                try
                {
                    retrievedGroup.Members.Add(userToBeAdded as DirectoryObject);
                    retrievedGroup.UpdateAsync().Wait();
                }
                catch (Exception e)
                {
                    Console.WriteLine("\nAdding user to group failed {0} {1}", e.Message,
                        e.InnerException != null ? e.InnerException.Message : "");
                }
            }

            #endregion

            #region Create a new Group

            //*********************************************************************************************
            // Create a new Group
            //*********************************************************************************************
            Group californiaEmployees = new Group
            {
                DisplayName = "California Employees" + Helper.GetRandomString(8),
                Description = "Employees in the state of California",
                MailNickname = "CalEmployees",
                MailEnabled = false,
                SecurityEnabled = true
            };
            try
            {
                activeDirectoryClient.Groups.AddGroupAsync(californiaEmployees).Wait();
                Console.WriteLine("\nNew Group {0} was created", californiaEmployees.DisplayName);
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError creating new Group {0} {1}", e.Message,
                    e.InnerException != null ? e.InnerException.Message : "");
            }

            #endregion

            #region Delete User

            //*********************************************************************************************
            // Delete the user that we just created
            //*********************************************************************************************
            if (userToBeAdded.ObjectId != null)
            {
                try
                {
                    userToBeAdded.DeleteAsync().Wait();
                    Console.WriteLine("\nUser {0} was deleted", userToBeAdded.DisplayName);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Deleting User failed {0} {1}", e.Message,
                        e.InnerException != null ? e.InnerException.Message : "");
                }
            }
            if (newUser.ObjectId != null)
            {
                try
                {
                    newUser.DeleteAsync().Wait();
                    Console.WriteLine("\nUser {0} was deleted", newUser.DisplayName);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Deleting User failed {0} {1}", e.Message,
                        e.InnerException != null ? e.InnerException.Message : "");
                }
            }

            #endregion

            #region Delete Group

            //*********************************************************************************************
            // Delete the Group that we just created
            //*********************************************************************************************
            if (californiaEmployees.ObjectId != null)
            {
                try
                {
                    californiaEmployees.DeleteAsync().Wait();
                    Console.WriteLine("\nGroup {0} was deleted", californiaEmployees.DisplayName);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Deleting Group failed {0} {1}", e.Message,
                        e.InnerException != null ? e.InnerException.Message : "");
                }
            }

            #endregion

            #region Get All Roles

            //*********************************************************************
            // Get All Roles
            //*********************************************************************
            List<IDirectoryRole> foundRoles = null;
            try
            {
                foundRoles = activeDirectoryClient.DirectoryRoles.ExecuteAsync().Result.CurrentPage.ToList();
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError getting Roles {0} {1}", e.Message,
                    e.InnerException != null ? e.InnerException.Message : "");
            }

            if (foundRoles != null && foundRoles.Count > 0)
            {
                foreach (IDirectoryRole role in foundRoles)
                {
                    Console.WriteLine("\n Found Role: {0} {1} {2} ",
                        role.DisplayName, role.Description, role.ObjectId);
                }
            }
            else
            {
                Console.WriteLine("Role Not Found {0}", searchString);
            }

            #endregion

            #region Get Service Principals

            //*********************************************************************
            // get the Service Principals
            //*********************************************************************
            IPagedCollection<IServicePrincipal> servicePrincipals = null;
            try
            {
                servicePrincipals = activeDirectoryClient.ServicePrincipals.ExecuteAsync().Result;
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError getting Service Principal {0} {1}",
                    e.Message, e.InnerException != null ? e.InnerException.Message : "");
            }
            if (servicePrincipals != null)
            {
                do
                {
                    List<IServicePrincipal> servicePrincipalsList = servicePrincipals.CurrentPage.ToList();
                    foreach (IServicePrincipal servicePrincipal in servicePrincipalsList)
                    {
                        Console.WriteLine("Service Principal AppId: {0}  Name: {1}", servicePrincipal.AppId,
                            servicePrincipal.DisplayName);
                    }
                    servicePrincipals = servicePrincipals.GetNextPageAsync().Result;
                } while (servicePrincipals != null);
            }

            #endregion

            #region Get Applications

            //*********************************************************************
            // get the Application objects
            //*********************************************************************
            IPagedCollection<IApplication> applications = null;
            try
            {
                applications = activeDirectoryClient.Applications.Take(999).ExecuteAsync().Result;
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError getting Applications {0} {1}", e.Message,
                    e.InnerException != null ? e.InnerException.Message : "");
            }
            if (applications != null)
            {
                do
                {
                    List<IApplication> appsList = applications.CurrentPage.ToList();
                    foreach (IApplication app in appsList)
                    {
                        Console.WriteLine("Application AppId: {0}  Name: {1}", app.AppId, app.DisplayName);
                    }
                    applications = applications.GetNextPageAsync().Result;
                } while (applications != null);
            }

            #endregion

            #region User License Assignment

            //*********************************************************************************************
            // User License Assignment - assign EnterprisePack license to new user, and disable SharePoint service
            //   first get a list of Tenant's subscriptions and find the "Enterprisepack" one
            //   Enterprise Pack includes service Plans for ExchangeOnline, SharePointOnline and LyncOnline
            //   validate that Subscription is Enabled and there are enough units left to assign to users
            //*********************************************************************************************
            IPagedCollection<ISubscribedSku> skus = null;
            try
            {
                skus = activeDirectoryClient.SubscribedSkus.ExecuteAsync().Result;
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError getting Applications {0} {1}", e.Message,
                    e.InnerException != null ? e.InnerException.Message : "");
            }
            if (skus != null)
            {
                do
                {
                    List<ISubscribedSku> subscribedSkus = skus.CurrentPage.ToList();
                    foreach (ISubscribedSku sku in subscribedSkus)
                    {
                        if (sku.SkuPartNumber == "ENTERPRISEPACK")
                        {
                            if ((sku.PrepaidUnits.Enabled.Value > sku.ConsumedUnits) &&
                                (sku.CapabilityStatus == "Enabled"))
                            {
                                // create addLicense object and assign the Enterprise Sku GUID to the skuId
                                // 
                                AssignedLicense addLicense = new AssignedLicense { SkuId = sku.SkuId.Value };

                                // find plan id of SharePoint Service Plan
                                foreach (ServicePlanInfo servicePlan in sku.ServicePlans)
                                {
                                    if (servicePlan.ServicePlanName.Contains("SHAREPOINT"))
                                    {
                                        addLicense.DisabledPlans.Add(servicePlan.ServicePlanId.Value);
                                        break;
                                    }
                                }

                                IList<AssignedLicense> licensesToAdd = new[] { addLicense };
                                IList<Guid> licensesToRemove = new Guid[] { };

                                // attempt to assign the license object to the new user 
                                try
                                {
                                    if (newUser.ObjectId != null)
                                    {
                                        newUser.AssignLicenseAsync(licensesToAdd, licensesToRemove).Wait();
                                        Console.WriteLine("\n User {0} was assigned license {1}",
                                            newUser.DisplayName,
                                            addLicense.SkuId);
                                    }
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine("\nLicense assingment failed {0} {1}", e.Message,
                                        e.InnerException != null ? e.InnerException.Message : "");
                                }
                            }
                        }
                    }
                    skus = skus.GetNextPageAsync().Result;
                } while (skus != null);
            }

            #endregion

            #region Switch to OAuth Authorization Code Grant (Acting as a user)

            activeDirectoryClient = AuthenticationHelper.GetActiveDirectoryClientAsUser();

            #endregion

            #region Create Application

            //*********************************************************************************************
            // Create a new Application object with App Role Assignment (Direct permission)
            //*********************************************************************************************
            Application appObject = new Application { DisplayName = "Test-Demo App" + Helper.GetRandomString(8) };
            appObject.IdentifierUris.Add("https://localhost/demo/" + Guid.NewGuid());
            appObject.ReplyUrls.Add("https://localhost/demo");
            AppRole appRole = new AppRole();
            appRole.Id = Guid.NewGuid();
            appRole.IsEnabled = true;
            appRole.AllowedMemberTypes.Add("User");
            appRole.DisplayName = "Something";
            appRole.Description = "Anything";
            appRole.Value = "policy.write";
            appObject.AppRoles.Add(appRole);

            // created Keycredential object for the new App object
            KeyCredential keyCredential = new KeyCredential
            {
                StartDate = DateTime.UtcNow,
                EndDate = DateTime.UtcNow.AddYears(1),
                Type = "Symmetric",
                Value = Convert.FromBase64String("g/TMLuxgzurjQ0Sal9wFEzpaX/sI0vBP3IBUE/H/NS4="),
                Usage = "Verify"
            };
            appObject.KeyCredentials.Add(keyCredential);

            try
            {
                activeDirectoryClient.Applications.AddApplicationAsync(appObject).Wait();
                Console.WriteLine("New Application created: " + appObject.ObjectId);
            }
            catch (Exception e)
            {
                Console.WriteLine("Application Creation execption: {0} {1}", e.Message,
                    e.InnerException != null ? e.InnerException.Message : "");
            }

            #endregion

            #region Create Service Principal

            //*********************************************************************************************
            // create a new Service principal
            //*********************************************************************************************
            ServicePrincipal newServicePrincpal = new ServicePrincipal();
            if (appObject != null)
            {
                newServicePrincpal.DisplayName = appObject.DisplayName;
                newServicePrincpal.AccountEnabled = true;
                newServicePrincpal.AppId = appObject.AppId;
                try
                {
                    activeDirectoryClient.ServicePrincipals.AddServicePrincipalAsync(newServicePrincpal).Wait();
                    Console.WriteLine("New Service Principal created: " + newServicePrincpal.ObjectId);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Service Principal Creation execption: {0} {1}", e.Message,
                        e.InnerException != null ? e.InnerException.Message : "");
                }
            }

            #endregion

            #region Create an Extension Property

            ExtensionProperty linkedInUserId = new ExtensionProperty
            {
                Name = "linkedInUserId",
                DataType = "String",
                TargetObjects = { "User" }
            };
            try
            {
                appObject.ExtensionProperties.Add(linkedInUserId);
                appObject.UpdateAsync().Wait();
                Console.WriteLine("\nUser object extended successfully.");
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError extending the user object {0} {1}", e.Message,
                    e.InnerException != null ? e.InnerException.Message : "");
            }

            #endregion

            #region Manipulate an Extension Property

            try
            {
                if (retrievedUser != null && retrievedUser.ObjectId != null)
                {
                    retrievedUser.SetExtendedProperty(linkedInUserId.Name, "ExtensionPropertyValue");
                    retrievedUser.UpdateAsync().Wait();
                    Console.WriteLine("\nUser {0}'s extended property set successully.", retrievedUser.DisplayName);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError Updating the user object {0} {1}", e.Message,
                    e.InnerException != null ? e.InnerException.Message : "");
            }

            #endregion

            #region Get an Extension Property

            try
            {
                if (retrievedUser != null && retrievedUser.ObjectId != null)
                {
                    IReadOnlyDictionary<string, object> extendedProperties = retrievedUser.GetExtendedProperties();
                    object extendedProperty = extendedProperties[linkedInUserId.Name];
                    Console.WriteLine("\n Retrieved User {0}'s extended property value is: {1}.", retrievedUser.DisplayName,
                        extendedProperty);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError Updating the user object {0} {1}", e.Message,
                    e.InnerException != null ? e.InnerException.Message : "");
            }

            #endregion

            #region Assign Direct Permission
            try
            {
                User user =
                        (User)activeDirectoryClient.Users.ExecuteAsync().Result.CurrentPage.ToList().FirstOrDefault();
                if (appObject.ObjectId != null && user != null && newServicePrincpal.ObjectId != null)
                {
                    AppRoleAssignment appRoleAssignment = new AppRoleAssignment();
                    appRoleAssignment.Id = appRole.Id;
                    appRoleAssignment.ResourceId = Guid.Parse(newServicePrincpal.ObjectId);
                    appRoleAssignment.PrincipalType = "User";
                    appRoleAssignment.PrincipalId = Guid.Parse(user.ObjectId);
                    user.AppRoleAssignments.Add(appRoleAssignment);
                    user.UpdateAsync().Wait();
                    Console.WriteLine("User {0} is successfully assigned direct permission.", retrievedUser.DisplayName);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Direct Permission Assignment failed: {0} {1}", e.Message,
                    e.InnerException != null ? e.InnerException.Message : "");
            }

            #endregion

            #region Get Devices

            //*********************************************************************************************
            // Get a list of Mobile Devices from tenant
            //*********************************************************************************************
            Console.WriteLine("\nGetting Devices");
            IPagedCollection<IDevice> devices = null;
            try
            {
                devices = activeDirectoryClient.Devices.ExecuteAsync().Result;
            }
            catch (Exception e)
            {
                Console.WriteLine("/nError getting devices {0} {1}", e.Message,
                    e.InnerException != null ? e.InnerException.Message : "");
            }

            if (devices != null)
            {
                do
                {
                    List<IDevice> devicesList = devices.CurrentPage.ToList();
                    foreach (IDevice device in devicesList)
                    {
                        if (device.ObjectId != null)
                        {
                            Console.WriteLine("Device ID: {0}, Type: {1}", device.DeviceId, device.DeviceOSType);
                            IPagedCollection<IDirectoryObject> registeredOwners = device.RegisteredOwners;
                            if (registeredOwners != null)
                            {
                                do
                                {
                                    List<IDirectoryObject> registeredOwnersList = registeredOwners.CurrentPage.ToList();
                                    foreach (IDirectoryObject owner in registeredOwnersList)
                                    {
                                        Console.WriteLine("Device Owner ID: " + owner.ObjectId);
                                    }
                                    registeredOwners = registeredOwners.GetNextPageAsync().Result;
                                } while (registeredOwners != null);
                            }
                        }
                    }
                    devices = devices.GetNextPageAsync().Result;
                } while (devices != null);
            }

            #endregion

            #region Create New Permission

            //*********************************************************************************************
            // Create new permission object
            //*********************************************************************************************
            OAuth2PermissionGrant permissionObject = new OAuth2PermissionGrant();
            permissionObject.ConsentType = "AllPrincipals";
            permissionObject.Scope = "user_impersonation";
            permissionObject.StartTime = DateTime.Now;
            permissionObject.ExpiryTime = (DateTime.Now).AddMonths(12);

            // resourceId is objectId of the resource, in this case objectId of AzureAd (Graph API)
            permissionObject.ResourceId = "52620afb-80de-4096-a826-95f4ad481686";

            //ClientId = objectId of servicePrincipal
            permissionObject.ClientId = newServicePrincpal.ObjectId;
            try
            {
                activeDirectoryClient.Oauth2PermissionGrants.AddOAuth2PermissionGrantAsync(permissionObject).Wait();
                Console.WriteLine("New Permission object created: " + permissionObject.ObjectId);
            }
            catch (Exception e)
            {
                Console.WriteLine("Permission Creation exception: {0} {1}", e.Message, e.InnerException != null ? e.InnerException.Message : "");
            }

            #endregion

            #region Get All Permissions

            //*********************************************************************************************
            // get all Permission Objects
            //*********************************************************************************************
            Console.WriteLine("\n Getting Permissions");
            IPagedCollection<IOAuth2PermissionGrant> permissions = null;
            try
            {
                permissions = activeDirectoryClient.Oauth2PermissionGrants.ExecuteAsync().Result;
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0} {1}", e.Message, e.InnerException != null ? e.InnerException.Message : "");
            }
            if (permissions != null)
            {
                do
                {
                    List<IOAuth2PermissionGrant> perms = permissions.CurrentPage.ToList();
                    foreach (IOAuth2PermissionGrant perm in perms)
                    {
                        Console.WriteLine("Permission: {0}  Name: {1}", perm.ClientId, perm.Scope);
                    }
                    permissions = permissions.GetNextPageAsync().Result;
                } while (permissions != null);
            }

            #endregion

            #region Delete Application

            //*********************************************************************************************
            // Delete Application Objects
            //*********************************************************************************************
            if (appObject.ObjectId != null)
            {
                try
                {
                    appObject.DeleteAsync().Wait();
                    Console.WriteLine("Deleted Application object: " + appObject.ObjectId);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Application Deletion execption: {0} {1}", e.Message,
                        e.InnerException != null ? e.InnerException.Message : "");
                }
            }

            #endregion

            #region Batch Operations

            //*********************************************************************************************
            // Show Batching with 3 operators.  Note: up to 5 operations can be in a batch
            //*********************************************************************************************
            IReadOnlyQueryableSet<User> userQuery = activeDirectoryClient.DirectoryObjects.OfType<User>();
            IReadOnlyQueryableSet<Group> groupsQuery = activeDirectoryClient.DirectoryObjects.OfType<Group>();
            IReadOnlyQueryableSet<DirectoryRole> rolesQuery =
                activeDirectoryClient.DirectoryObjects.OfType<DirectoryRole>();
            try
            {
                IBatchElementResult[] batchResult =
                    activeDirectoryClient.Context.ExecuteBatchAsync(userQuery, groupsQuery, rolesQuery).Result;
                int responseCount = 1;
                foreach (IBatchElementResult result in batchResult)
                {
                    if (result.FailureResult != null)
                    {
                        Console.WriteLine("Failed: {0} ",
                            result.FailureResult.InnerException);
                    }
                    if (result.SuccessResult != null)
                    {
                        Console.WriteLine("Batch Item Result {0} succeeded",
                            responseCount++);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Batch execution failed. : {0} {1}", e.Message,
                    e.InnerException != null ? e.InnerException.Message : "");
            }

            #endregion

            //*********************************************************************************************
            // End of Demo Console App
            //*********************************************************************************************

            Console.WriteLine("\nCompleted at {0} \n Press Any Key to Exit.", currentDateTime);
            Console.ReadKey();
        }
Esempio n. 11
0
 /// <summary>
 /// Grants OAuth2 permissions for the relevant resource Ids of an app.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='body'>
 /// The relevant app Service Principal Object Id and the Service Principal
 /// Object Id you want to grant.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <OAuth2PermissionGrant> CreateAsync(this IOAuth2PermissionGrantOperations operations, OAuth2PermissionGrant body = default(OAuth2PermissionGrant), CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.CreateWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Esempio n. 12
0
 /// <summary>
 /// Grants OAuth2 permissions for the relevant resource Ids of an app.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='body'>
 /// The relevant app Service Principal Object Id and the Service Principal
 /// Object Id you want to grant.
 /// </param>
 public static OAuth2PermissionGrant Create(this IOAuth2PermissionGrantOperations operations, OAuth2PermissionGrant body = default(OAuth2PermissionGrant))
 {
     return(operations.CreateAsync(body).GetAwaiter().GetResult());
 }
        /// <summary>
        /// Grants OAuth2 permissions for the relevant resource Ids of an app.
        /// </summary>
        /// <param name='body'>
        /// The relevant app Service Principal Object Id and the Service Principal
        /// Object Id you want to grant.
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <AzureOperationResponse <OAuth2PermissionGrant> > CreateWithHttpMessagesAsync(OAuth2PermissionGrant body = default(OAuth2PermissionGrant), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (Client.ApiVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
            }
            if (Client.TenantID == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.TenantID");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("body", body);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "Create", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{tenantID}/oauth2PermissionGrants").ToString();

            _url = _url.Replace("{tenantID}", System.Uri.EscapeDataString(Client.TenantID));
            List <string> _queryParameters = new List <string>();

            if (Client.ApiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
            }
            if (_queryParameters.Count > 0)
            {
                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("POST");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
            }


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            if (body != null)
            {
                _requestContent      = Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings);
                _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            }
            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 201)
            {
                var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <CloudError>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex      = new CloudException(_errorBody.Message);
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_httpResponse.Headers.Contains("x-ms-request-id"))
                {
                    ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                }
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationResponse <OAuth2PermissionGrant>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            // Deserialize Response
            if ((int)_statusCode == 201)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <OAuth2PermissionGrant>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
Esempio n. 14
0
        private async Task UpdatePermissionGrantsAsync(IGraphServiceClient client, Application app)
        {
            ServicePrincipal appPrincipal = await GetServicePrincipalAsync(client, app.AppId).ConfigureAwait(false);

            ServicePrincipal resourcePrincipal = await GetServicePrincipalAsync(client, "c5393580-f805-4401-95e8-94b7a6ef2fc2").ConfigureAwait(false);

            app.AssertNotNull(nameof(app));

            if (appPrincipal == null)
            {
                WriteDebug($"Creating a service principal for the {app.AppId} application");

                appPrincipal = await client.ServicePrincipals.Request().AddAsync(new ServicePrincipal
                {
                    AppId = app.AppId
                }, CancellationToken).ConfigureAwait(false);
            }

            WriteDebug($"Updating the required resources for the {app.Id} application");

            await client.Applications[app.Id].Request().UpdateAsync(new Application
            {
                RequiredResourceAccess = GetRequiredResourceAccess()
            }, CancellationToken).ConfigureAwait(false);

            IGraphServiceOauth2PermissionGrantsCollectionPage permissionGrants = null;

            try
            {
                permissionGrants = await client.Oauth2PermissionGrants.Request().Filter($"clientId eq '{appPrincipal.Id}'").GetAsync(CancellationToken).ConfigureAwait(false);
            }
            catch (ServiceException ex)
            {
                if (!ex.Error.Code.Equals("Request_ResourceNotFound", StringComparison.InvariantCultureIgnoreCase))
                {
                    throw;
                }
            }

            OAuth2PermissionGrant grant = permissionGrants?.CurrentPage.SingleOrDefault(x => x.ResourceId == resourcePrincipal.Id);

            if (grant != null)
            {
                WriteDebug($"Updating the Office 365 Management OAuth2 permission grant for the {app.Id} application");

                await client.Oauth2PermissionGrants[grant.Id].Request().UpdateAsync(new OAuth2PermissionGrant
                {
                    ClientId    = appPrincipal.Id,
                    ConsentType = "AllPrincipals",
                    ResourceId  = resourcePrincipal.Id,
                    Scope       = "ActivityFeed.Read ActivityFeed.ReadDlp ServiceHealth.Read"
                }, CancellationToken);
            }
            else
            {
                WriteDebug($"Creating the Office 365 Management OAuth2 permission grant for the {app.Id} application");

                await client.Oauth2PermissionGrants.Request().AddAsync(new OAuth2PermissionGrant
                {
                    ClientId    = appPrincipal.Id,
                    ConsentType = "AllPrincipals",
                    ResourceId  = resourcePrincipal.Id,
                    Scope       = "ActivityFeed.Read ActivityFeed.ReadDlp ServiceHealth.Read"
                }, CancellationToken);
            }

            resourcePrincipal = await GetServicePrincipalAsync(client, "00000003-0000-0000-c000-000000000000").ConfigureAwait(false);

            grant = permissionGrants?.CurrentPage.SingleOrDefault(x => x.ResourceId == resourcePrincipal.Id);

            if (grant != null)
            {
                WriteDebug($"Updating the Microsoft Graph OAuth2 permission grant for the {app.Id} application");

                await client.Oauth2PermissionGrants[grant.Id].Request().UpdateAsync(new OAuth2PermissionGrant
                {
                    ClientId    = appPrincipal.Id,
                    ConsentType = "AllPrincipals",
                    ResourceId  = resourcePrincipal.Id,
                    Scope       = "AuditLog.Read.All DeviceManagementApps.Read.All DeviceManagementConfiguration.Read.All DeviceManagementManagedDevices.Read.All DeviceManagementServiceConfig.Read.All Directory.Read.All IdentityRiskEvent.Read.All IdentityRiskyUser.Read.All InformationProtectionPolicy.Read Policy.Read.All Reports.Read.All SecurityEvents.Read.All User.Read"
                }, CancellationToken);
            }
            else
            {
                WriteDebug($"Creating the Microsoft Graph OAuth2 permission grant for the {app.Id} application");

                await client.Oauth2PermissionGrants.Request().AddAsync(new OAuth2PermissionGrant
                {
                    ClientId    = appPrincipal.Id,
                    ConsentType = "AllPrincipals",
                    ResourceId  = resourcePrincipal.Id,
                    Scope       = "AuditLog.Read.All DeviceManagementApps.Read.All DeviceManagementConfiguration.Read.All DeviceManagementManagedDevices.Read.All DeviceManagementServiceConfig.Read.All Directory.Read.All IdentityRiskEvent.Read.All IdentityRiskyUser.Read.All InformationProtectionPolicy.Read Policy.Read.All Reports.Read.All SecurityEvents.Read.All User.Read"
                }, CancellationToken);
            }
        }
Esempio n. 15
0
        private static void Main()
        {
            // record start DateTime of execution
            string currentDateTime = DateTime.Now.ToUniversalTime().ToString();

            #region Setup Active Directory Client

            //*********************************************************************
            // setup Active Directory Client
            //*********************************************************************
            ActiveDirectoryClient activeDirectoryClient;
            try
            {
                activeDirectoryClient = AuthenticationHelper.GetActiveDirectoryClientAsApplication();
            }
            catch (AuthenticationException ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Acquiring a token failed with the following error: {0}", ex.Message);
                if (ex.InnerException != null)
                {
                    //You should implement retry and back-off logic per the guidance given here:http://msdn.microsoft.com/en-us/library/dn168916.aspx
                    //InnerException Message will contain the HTTP error status codes mentioned in the link above
                    Console.WriteLine("Error detail: {0}", ex.InnerException.Message);
                }
                Console.ResetColor();
                Console.ReadKey();
                return;
            }

            #endregion

            #region TenantDetails

            //*********************************************************************
            // Get Tenant Details
            // Note: update the string TenantId with your TenantId.
            // This can be retrieved from the login Federation Metadata end point:
            // https://login.windows.net/GraphDir1.onmicrosoft.com/FederationMetadata/2007-06/FederationMetadata.xml
            //  Replace "GraphDir1.onMicrosoft.com" with any domain owned by your organization
            // The returned value from the first xml node "EntityDescriptor", will have a STS URL
            // containing your TenantId e.g. "https://sts.windows.net/4fd2b2f2-ea27-4fe5-a8f3-7b1a7c975f34/" is returned for GraphDir1.onMicrosoft.com
            //*********************************************************************
            VerifiedDomain initialDomain = new VerifiedDomain();
            VerifiedDomain defaultDomain = new VerifiedDomain();
            ITenantDetail  tenant        = null;
            Console.WriteLine("\n Retrieving Tenant Details");
            try
            {
                List <ITenantDetail> tenantsList = activeDirectoryClient.TenantDetails
                                                   .Where(tenantDetail => tenantDetail.ObjectId.Equals(Constants.TenantId))
                                                   .ExecuteAsync().Result.CurrentPage.ToList();
                if (tenantsList.Count > 0)
                {
                    tenant = tenantsList.First();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError getting TenantDetails {0} {1}", e.Message,
                                  e.InnerException != null ? e.InnerException.Message : "");
            }
            if (tenant == null)
            {
                Console.WriteLine("Tenant not found");
            }
            else
            {
                TenantDetail tenantDetail = (TenantDetail)tenant;
                Console.WriteLine("Tenant Display Name: " + tenantDetail.DisplayName);

                // Get the Tenant's Verified Domains
                initialDomain = tenantDetail.VerifiedDomains.First(x => x.Initial.HasValue && x.Initial.Value);
                Console.WriteLine("Initial Domain Name: " + initialDomain.Name);
                defaultDomain = tenantDetail.VerifiedDomains.First(x => [email protected] && [email protected]);
                Console.WriteLine("Default Domain Name: " + defaultDomain.Name);

                // Get Tenant's Tech Contacts
                foreach (string techContact in tenantDetail.TechnicalNotificationMails)
                {
                    Console.WriteLine("Tenant Tech Contact: " + techContact);
                }
            }

            #endregion

            #region Create a new User

            IUser newUser = new User();
            if (defaultDomain.Name != null)
            {
                newUser.DisplayName       = "Sample App Demo User (Manager)";
                newUser.UserPrincipalName = Helper.GetRandomString(10) + "@" + defaultDomain.Name;
                newUser.AccountEnabled    = true;
                newUser.MailNickname      = "SampleAppDemoUserManager";
                newUser.PasswordProfile   = new PasswordProfile
                {
                    Password = "******",
                    ForceChangePasswordNextLogin = true
                };
                newUser.UsageLocation = "US";
                try
                {
                    activeDirectoryClient.Users.AddUserAsync(newUser).Wait();
                    Console.WriteLine("\nNew User {0} was created", newUser.DisplayName);
                }
                catch (Exception e)
                {
                    Console.WriteLine("\nError creating new user {0} {1}", e.Message,
                                      e.InnerException != null ? e.InnerException.Message : "");
                }
            }

            #endregion

            #region List of max 4 Users by UPN

            //*********************************************************************
            // Demonstrate Getting a list of Users with paging (get 4 users), sorted by displayName
            //*********************************************************************
            int maxUsers = 4;
            try
            {
                Console.WriteLine("\n Retrieving Users");
                List <IUser> users = activeDirectoryClient.Users.OrderBy(user =>
                                                                         user.UserPrincipalName).Take(maxUsers).ExecuteAsync().Result.CurrentPage.ToList();
                foreach (IUser user in users)
                {
                    Console.WriteLine("UserObjectId: {0}  UPN: {1}", user.ObjectId, user.UserPrincipalName);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError getting Users. {0} {1}", e.Message,
                                  e.InnerException != null ? e.InnerException.Message : "");
            }

            #endregion

            #region Create a User with a temp Password

            //*********************************************************************************************
            // Create a new User with a temp Password
            //*********************************************************************************************
            IUser userToBeAdded = new User();
            userToBeAdded.DisplayName       = "Sample App Demo User";
            userToBeAdded.UserPrincipalName = Helper.GetRandomString(10) + "@" + defaultDomain.Name;
            userToBeAdded.AccountEnabled    = true;
            userToBeAdded.MailNickname      = "SampleAppDemoUser";
            userToBeAdded.PasswordProfile   = new PasswordProfile
            {
                Password = "******",
                ForceChangePasswordNextLogin = true
            };
            userToBeAdded.UsageLocation = "US";
            try
            {
                activeDirectoryClient.Users.AddUserAsync(userToBeAdded).Wait();
                Console.WriteLine("\nNew User {0} was created", userToBeAdded.DisplayName);
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError creating new user. {0} {1}", e.Message,
                                  e.InnerException != null ? e.InnerException.Message : "");
            }

            #endregion

            #region Update newly created User

            //*******************************************************************************************
            // update the newly created user's Password, PasswordPolicies and City
            //*********************************************************************************************
            if (userToBeAdded.ObjectId != null)
            {
                // update User's city and reset their User's Password
                userToBeAdded.City    = "Seattle";
                userToBeAdded.Country = "UK";
                PasswordProfile PasswordProfile = new PasswordProfile
                {
                    Password = "******",
                    ForceChangePasswordNextLogin = false
                };
                userToBeAdded.PasswordProfile  = PasswordProfile;
                userToBeAdded.PasswordPolicies = "DisablePasswordExpiration, DisableStrongPassword";
                try
                {
                    userToBeAdded.UpdateAsync().Wait();
                    Console.WriteLine("\nUser {0} was updated", userToBeAdded.DisplayName);
                }
                catch (Exception e)
                {
                    Console.WriteLine("\nError Updating the user {0} {1}", e.Message,
                                      e.InnerException != null ? e.InnerException.Message : "");
                }
            }

            #endregion

            #region Search User by UPN

            // search for a single user by UPN
            string searchString = "admin@" + initialDomain.Name;
            Console.WriteLine("\n Retrieving user with UPN {0}", searchString);
            User         retrievedUser  = new User();
            List <IUser> retrievedUsers = null;
            try
            {
                retrievedUsers = activeDirectoryClient.Users
                                 .Where(user => user.UserPrincipalName.Equals(searchString))
                                 .ExecuteAsync().Result.CurrentPage.ToList();
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError getting new user {0} {1}", e.Message,
                                  e.InnerException != null ? e.InnerException.Message : "");
            }
            // should only find one user with the specified UPN
            if (retrievedUsers != null && retrievedUsers.Count == 1)
            {
                retrievedUser = (User)retrievedUsers.First();
            }
            else
            {
                Console.WriteLine("User not found {0}", searchString);
            }

            #endregion

            #region User Operations

            if (retrievedUser.UserPrincipalName != null)
            {
                Console.WriteLine("\n Found User: "******"  UPN: " +
                                  retrievedUser.UserPrincipalName);

                #region Assign User a Manager

                //Assigning User a new manager.
                if (newUser.ObjectId != null)
                {
                    Console.WriteLine("\n Assign User {0}, {1} as Manager.", retrievedUser.DisplayName,
                                      newUser.DisplayName);
                    retrievedUser.Manager = newUser as DirectoryObject;
                    try
                    {
                        newUser.UpdateAsync().Wait();
                        Console.Write("User {0} is successfully assigned {1} as Manager.", retrievedUser.DisplayName,
                                      newUser.DisplayName);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("\nError assigning manager to user. {0} {1}", e.Message,
                                          e.InnerException != null ? e.InnerException.Message : "");
                    }
                }

                #endregion

                #region Get User's Manager

                //Get the retrieved user's manager.
                Console.WriteLine("\n Retrieving User {0}'s Manager.", retrievedUser.DisplayName);
                DirectoryObject usersManager = retrievedUser.Manager;
                if (usersManager != null)
                {
                    User manager = usersManager as User;
                    if (manager != null)
                    {
                        Console.WriteLine("User {0} Manager details: \nManager: {1}  UPN: {2}",
                                          retrievedUser.DisplayName, manager.DisplayName, manager.UserPrincipalName);
                    }
                }
                else
                {
                    Console.WriteLine("Manager not found.");
                }

                #endregion

                #region Get User's Direct Reports

                //*********************************************************************
                // get the user's Direct Reports
                //*********************************************************************
                if (newUser.ObjectId != null)
                {
                    Console.WriteLine("\n Getting User{0}'s Direct Reports.", newUser.DisplayName);
                    IUserFetcher newUserFetcher = (IUserFetcher)newUser;
                    try
                    {
                        IPagedCollection <IDirectoryObject> directReports =
                            newUserFetcher.DirectReports.ExecuteAsync().Result;
                        do
                        {
                            List <IDirectoryObject> directoryObjects = directReports.CurrentPage.ToList();
                            foreach (IDirectoryObject directoryObject in directoryObjects)
                            {
                                if (directoryObject is User)
                                {
                                    User directReport = directoryObject as User;
                                    Console.WriteLine("User {0} Direct Report is {1}", newUser.UserPrincipalName,
                                                      directReport.UserPrincipalName);
                                }
                            }
                            directReports = directReports.GetNextPageAsync().Result;
                        } while (directReports != null && directReports.MorePagesAvailable);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("\nError getting direct reports of user. {0} {1}", e.Message,
                                          e.InnerException != null ? e.InnerException.Message : "");
                    }
                }

                #endregion

                #region Get list of Group IDS, user is member of

                //*********************************************************************
                // get a list of Group IDs that the user is a member of
                //*********************************************************************
                //const bool securityEnabledOnly = false;
                //IEnumerable<string> memberGroups = retrievedUser.GetMemberGroupsAsync(securityEnabledOnly).Result;
                //Console.WriteLine("\n {0} is a member of the following Groups (IDs)", retrievedUser.DisplayName);
                //foreach (String memberGroup in memberGroups)
                //{
                //    Console.WriteLine("Member of Group ID: " + memberGroup);
                //}

                #endregion

                #region Get User's Group And Role Membership, Getting the complete set of objects

                //*********************************************************************
                // get the User's Group and Role membership, getting the complete set of objects
                //*********************************************************************
                Console.WriteLine("\n {0} is a member of the following Group and Roles (IDs)", retrievedUser.DisplayName);
                IUserFetcher retrievedUserFetcher = retrievedUser;
                try
                {
                    IPagedCollection <IDirectoryObject> pagedCollection = retrievedUserFetcher.MemberOf.ExecuteAsync().Result;
                    do
                    {
                        List <IDirectoryObject> directoryObjects = pagedCollection.CurrentPage.ToList();
                        foreach (IDirectoryObject directoryObject in directoryObjects)
                        {
                            if (directoryObject is Group)
                            {
                                Group group = directoryObject as Group;
                                Console.WriteLine(" Group: {0}  Description: {1}", group.DisplayName, group.Description);
                            }
                            if (directoryObject is DirectoryRole)
                            {
                                DirectoryRole role = directoryObject as DirectoryRole;
                                Console.WriteLine(" Role: {0}  Description: {1}", role.DisplayName, role.Description);
                            }
                        }
                        pagedCollection = pagedCollection.GetNextPageAsync().Result;
                    } while (pagedCollection != null && pagedCollection.MorePagesAvailable);
                }
                catch (Exception e)
                {
                    Console.WriteLine("\nError getting user's groups and roles memberships. {0} {1}", e.Message,
                                      e.InnerException != null ? e.InnerException.Message : "");
                }

                #endregion
            }

            #endregion

            #region Search for User (People Picker)

            //*********************************************************************
            // People picker
            // Search for a user using text string "Us" match against userPrincipalName, displayName, giveName, surname
            //*********************************************************************
            searchString = "Us";
            Console.WriteLine("\nSearching for any user with string {0} in UPN,DisplayName,First or Last Name",
                              searchString);
            List <IUser>             usersList     = null;
            IPagedCollection <IUser> searchResults = null;
            try
            {
                IUserCollection userCollection = activeDirectoryClient.Users;
                searchResults = userCollection.Where(user =>
                                                     user.UserPrincipalName.StartsWith(searchString) ||
                                                     user.DisplayName.StartsWith(searchString) ||
                                                     user.GivenName.StartsWith(searchString) ||
                                                     user.Surname.StartsWith(searchString)).ExecuteAsync().Result;
                usersList = searchResults.CurrentPage.ToList();
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError getting User {0} {1}", e.Message,
                                  e.InnerException != null ? e.InnerException.Message : "");
            }

            if (usersList != null && usersList.Count > 0)
            {
                do
                {
                    usersList = searchResults.CurrentPage.ToList();
                    foreach (IUser user in usersList)
                    {
                        Console.WriteLine("User DisplayName: {0}  UPN: {1}",
                                          user.DisplayName, user.UserPrincipalName);
                    }
                    searchResults = searchResults.GetNextPageAsync().Result;
                } while (searchResults != null && searchResults.MorePagesAvailable);
            }
            else
            {
                Console.WriteLine("User not found");
            }

            #endregion

            #region Search for Group using StartWith filter

            //*********************************************************************
            // Search for a group using a startsWith filter (displayName property)
            //*********************************************************************
            Group retrievedGroup = new Group();
            searchString = "US";
            List <IGroup> foundGroups = null;
            try
            {
                foundGroups = activeDirectoryClient.Groups
                              .Where(group => group.DisplayName.StartsWith(searchString))
                              .ExecuteAsync().Result.CurrentPage.ToList();
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError getting Group {0} {1}",
                                  e.Message, e.InnerException != null ? e.InnerException.Message : "");
            }
            if (foundGroups != null && foundGroups.Count > 0)
            {
                retrievedGroup = foundGroups.First() as Group;
            }
            else
            {
                Console.WriteLine("Group Not Found");
            }

            #endregion

            #region Assign Member to Group

            if (retrievedGroup.ObjectId != null)
            {
                try
                {
                    activeDirectoryClient.Context.AddLink(retrievedGroup, "members", newUser);
                    activeDirectoryClient.Context.SaveChanges();
                }
                catch (Exception e)
                {
                    Console.WriteLine("\nError assigning member to group. {0} {1}",
                                      e.Message, e.InnerException != null ? e.InnerException.Message : "");
                }
            }

            #endregion

            #region Get Group members

            if (retrievedGroup.ObjectId != null)
            {
                Console.WriteLine("\n Found Group: " + retrievedGroup.DisplayName + "  " + retrievedGroup.Description);

                //*********************************************************************
                // get the groups' membership -
                // Note this method retrieves ALL links in one request - please use this method with care - this
                // may return a very large number of objects
                //*********************************************************************
                IGroupFetcher retrievedGroupFetcher = retrievedGroup;
                try
                {
                    IPagedCollection <IDirectoryObject> members = retrievedGroupFetcher.Members.ExecuteAsync().Result;
                    Console.WriteLine(" Members:");
                    do
                    {
                        List <IDirectoryObject> directoryObjects = members.CurrentPage.ToList();
                        foreach (IDirectoryObject member in directoryObjects)
                        {
                            if (member is User)
                            {
                                User user = member as User;
                                Console.WriteLine("User DisplayName: {0}  UPN: {1}",
                                                  user.DisplayName,
                                                  user.UserPrincipalName);
                            }
                            if (member is Group)
                            {
                                Group group = member as Group;
                                Console.WriteLine("Group DisplayName: {0}", group.DisplayName);
                            }
                            if (member is Contact)
                            {
                                Contact contact = member as Contact;
                                Console.WriteLine("Contact DisplayName: {0}", contact.DisplayName);
                            }
                        }
                    } while (members != null && members.MorePagesAvailable);
                }
                catch (Exception e)
                {
                    Console.WriteLine("\nError getting groups' membership. {0} {1}",
                                      e.Message, e.InnerException != null ? e.InnerException.Message : "");
                }
            }

            #endregion

            #region Add User to Group

            //*********************************************************************************************
            // Add User to the "WA" Group
            //*********************************************************************************************
            if (retrievedGroup.ObjectId != null)
            {
                try
                {
                    activeDirectoryClient.Context.AddLink(retrievedGroup, "members", userToBeAdded);
                    activeDirectoryClient.Context.SaveChangesAsync().Wait();
                }
                catch (Exception e)
                {
                    Console.WriteLine("\nAdding user to group failed {0} {1}", e.Message,
                                      e.InnerException != null ? e.InnerException.Message : "");
                }
            }

            #endregion

            #region Create a new Group

            //*********************************************************************************************
            // Create a new Group
            //*********************************************************************************************
            Group californiaEmployees = new Group
            {
                DisplayName     = "California Employees" + Helper.GetRandomString(8),
                Description     = "Employees in the state of California",
                MailNickname    = "CalEmployees",
                MailEnabled     = false,
                SecurityEnabled = true
            };
            try
            {
                activeDirectoryClient.Groups.AddGroupAsync(californiaEmployees).Wait();
                Console.WriteLine("\nNew Group {0} was created", californiaEmployees.DisplayName);
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError creating new Group {0} {1}", e.Message,
                                  e.InnerException != null ? e.InnerException.Message : "");
            }

            #endregion

            #region Delete User

            //*********************************************************************************************
            // Delete the user that we just created
            //*********************************************************************************************
            if (userToBeAdded.ObjectId != null)
            {
                try
                {
                    userToBeAdded.DeleteAsync().Wait();
                    Console.WriteLine("\nUser {0} was deleted", userToBeAdded.DisplayName);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Deleting User failed {0} {1}", e.Message,
                                      e.InnerException != null ? e.InnerException.Message : "");
                }
            }
            if (newUser.ObjectId != null)
            {
                try
                {
                    newUser.DeleteAsync().Wait();
                    Console.WriteLine("\nUser {0} was deleted", newUser.DisplayName);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Deleting User failed {0} {1}", e.Message,
                                      e.InnerException != null ? e.InnerException.Message : "");
                }
            }

            #endregion

            #region Delete Group

            //*********************************************************************************************
            // Delete the Group that we just created
            //*********************************************************************************************
            if (californiaEmployees.ObjectId != null)
            {
                try
                {
                    californiaEmployees.DeleteAsync().Wait();
                    Console.WriteLine("\nGroup {0} was deleted", californiaEmployees.DisplayName);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Deleting Group failed {0} {1}", e.Message,
                                      e.InnerException != null ? e.InnerException.Message : "");
                }
            }

            #endregion

            #region Get All Roles

            //*********************************************************************
            // Get All Roles
            //*********************************************************************
            List <IDirectoryRole> foundRoles = null;
            try
            {
                foundRoles = activeDirectoryClient.DirectoryRoles.ExecuteAsync().Result.CurrentPage.ToList();
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError getting Roles {0} {1}", e.Message,
                                  e.InnerException != null ? e.InnerException.Message : "");
            }

            if (foundRoles != null && foundRoles.Count > 0)
            {
                foreach (IDirectoryRole role in foundRoles)
                {
                    Console.WriteLine("\n Found Role: {0} {1} {2} ",
                                      role.DisplayName, role.Description, role.ObjectId);
                }
            }
            else
            {
                Console.WriteLine("Role Not Found {0}", searchString);
            }

            #endregion

            #region Get Service Principals

            //*********************************************************************
            // get the Service Principals
            //*********************************************************************
            IPagedCollection <IServicePrincipal> servicePrincipals = null;
            try
            {
                servicePrincipals = activeDirectoryClient.ServicePrincipals.ExecuteAsync().Result;
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError getting Service Principal {0} {1}",
                                  e.Message, e.InnerException != null ? e.InnerException.Message : "");
            }
            if (servicePrincipals != null)
            {
                do
                {
                    List <IServicePrincipal> servicePrincipalsList = servicePrincipals.CurrentPage.ToList();
                    foreach (IServicePrincipal servicePrincipal in servicePrincipalsList)
                    {
                        Console.WriteLine("Service Principal AppId: {0}  Name: {1}", servicePrincipal.AppId,
                                          servicePrincipal.DisplayName);
                    }
                    servicePrincipals = servicePrincipals.GetNextPageAsync().Result;
                } while (servicePrincipals != null && servicePrincipals.MorePagesAvailable);
            }

            #endregion

            #region Get Applications

            //*********************************************************************
            // get the Application objects
            //*********************************************************************
            IPagedCollection <IApplication> applications = null;
            try
            {
                applications = activeDirectoryClient.Applications.Take(999).ExecuteAsync().Result;
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError getting Applications {0} {1}", e.Message,
                                  e.InnerException != null ? e.InnerException.Message : "");
            }
            if (applications != null)
            {
                do
                {
                    List <IApplication> appsList = applications.CurrentPage.ToList();
                    foreach (IApplication app in appsList)
                    {
                        Console.WriteLine("Application AppId: {0}  Name: {1}", app.AppId, app.DisplayName);
                    }
                    applications = applications.GetNextPageAsync().Result;
                } while (applications != null && applications.MorePagesAvailable);
            }

            #endregion

            #region User License Assignment

            //*********************************************************************************************
            // User License Assignment - assign EnterprisePack license to new user, and disable SharePoint service
            //   first get a list of Tenant's subscriptions and find the "Enterprisepack" one
            //   Enterprise Pack includes service Plans for ExchangeOnline, SharePointOnline and LyncOnline
            //   validate that Subscription is Enabled and there are enough units left to assign to users
            //*********************************************************************************************
            IPagedCollection <ISubscribedSku> skus = null;
            try
            {
                skus = activeDirectoryClient.SubscribedSkus.ExecuteAsync().Result;
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError getting Applications {0} {1}", e.Message,
                                  e.InnerException != null ? e.InnerException.Message : "");
            }
            if (skus != null)
            {
                do
                {
                    List <ISubscribedSku> subscribedSkus = skus.CurrentPage.ToList();
                    foreach (ISubscribedSku sku in subscribedSkus)
                    {
                        if (sku.SkuPartNumber == "ENTERPRISEPACK")
                        {
                            if ((sku.PrepaidUnits.Enabled.Value > sku.ConsumedUnits) &&
                                (sku.CapabilityStatus == "Enabled"))
                            {
                                // create addLicense object and assign the Enterprise Sku GUID to the skuId
                                //
                                AssignedLicense addLicense = new AssignedLicense {
                                    SkuId = sku.SkuId.Value
                                };

                                // find plan id of SharePoint Service Plan
                                foreach (ServicePlanInfo servicePlan in sku.ServicePlans)
                                {
                                    if (servicePlan.ServicePlanName.Contains("SHAREPOINT"))
                                    {
                                        addLicense.DisabledPlans.Add(servicePlan.ServicePlanId.Value);
                                        break;
                                    }
                                }

                                IList <AssignedLicense> licensesToAdd    = new[] { addLicense };
                                IList <Guid>            licensesToRemove = new Guid[] {};

                                // attempt to assign the license object to the new user
                                try
                                {
                                    if (newUser.ObjectId != null)
                                    {
                                        newUser.AssignLicenseAsync(licensesToAdd, licensesToRemove).Wait();
                                        Console.WriteLine("\n User {0} was assigned license {1}",
                                                          newUser.DisplayName,
                                                          addLicense.SkuId);
                                    }
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine("\nLicense assingment failed {0} {1}", e.Message,
                                                      e.InnerException != null ? e.InnerException.Message : "");
                                }
                            }
                        }
                    }
                    skus = skus.GetNextPageAsync().Result;
                } while (skus != null && skus.MorePagesAvailable);
            }

            #endregion

            #region Switch to OAuth Authorization Code Grant (Acting as a user)

            activeDirectoryClient = AuthenticationHelper.GetActiveDirectoryClientAsUser();

            #endregion

            #region Create Application

            //*********************************************************************************************
            // Create a new Application object with App Role Assignment (Direct permission)
            //*********************************************************************************************
            Application appObject = new Application {
                DisplayName = "Test-Demo App" + Helper.GetRandomString(8)
            };
            appObject.IdentifierUris.Add("https://localhost/demo/" + Guid.NewGuid());
            appObject.ReplyUrls.Add("https://localhost/demo");
            AppRole appRole = new AppRole();
            appRole.Id        = Guid.NewGuid();
            appRole.IsEnabled = true;
            appRole.AllowedMemberTypes.Add("User");
            appRole.DisplayName = "Something";
            appRole.Description = "Anything";
            appRole.Value       = "policy.write";
            appObject.AppRoles.Add(appRole);

            // created Keycredential object for the new App object
            KeyCredential keyCredential = new KeyCredential
            {
                StartDate = DateTime.UtcNow,
                EndDate   = DateTime.UtcNow.AddYears(1),
                Type      = "Symmetric",
                Value     = Convert.FromBase64String("g/TMLuxgzurjQ0Sal9wFEzpaX/sI0vBP3IBUE/H/NS4="),
                Usage     = "Verify"
            };
            appObject.KeyCredentials.Add(keyCredential);

            try
            {
                activeDirectoryClient.Applications.AddApplicationAsync(appObject).Wait();
                Console.WriteLine("New Application created: " + appObject.ObjectId);
            }
            catch (Exception e)
            {
                Console.WriteLine("Application Creation execption: {0} {1}", e.Message,
                                  e.InnerException != null ? e.InnerException.Message : "");
            }

            #endregion

            #region Create Service Principal

            //*********************************************************************************************
            // create a new Service principal
            //*********************************************************************************************
            ServicePrincipal newServicePrincpal = new ServicePrincipal();
            if (appObject != null)
            {
                newServicePrincpal.DisplayName    = appObject.DisplayName;
                newServicePrincpal.AccountEnabled = true;
                newServicePrincpal.AppId          = appObject.AppId;
                try
                {
                    activeDirectoryClient.ServicePrincipals.AddServicePrincipalAsync(newServicePrincpal).Wait();
                    Console.WriteLine("New Service Principal created: " + newServicePrincpal.ObjectId);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Service Principal Creation execption: {0} {1}", e.Message,
                                      e.InnerException != null ? e.InnerException.Message : "");
                }
            }

            #endregion

            #region Assign Direct Permission
            try
            {
                User user =
                    (User)activeDirectoryClient.Users.ExecuteAsync().Result.CurrentPage.ToList().FirstOrDefault();
                if (appObject.ObjectId != null && user != null && newServicePrincpal.ObjectId != null)
                {
                    AppRoleAssignment appRoleAssignment = new AppRoleAssignment();
                    appRoleAssignment.Id            = appRole.Id;
                    appRoleAssignment.ResourceId    = Guid.Parse(newServicePrincpal.ObjectId);
                    appRoleAssignment.PrincipalType = "User";
                    appRoleAssignment.PrincipalId   = Guid.Parse(user.ObjectId);
                    user.AppRoleAssignments.Add(appRoleAssignment);
                    user.UpdateAsync().Wait();
                    Console.WriteLine("User {0} is successfully assigned direct permission.", retrievedUser.DisplayName);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Direct Permission Assignment failed: {0} {1}", e.Message,
                                  e.InnerException != null ? e.InnerException.Message : "");
            }

            #endregion

            #region Get Devices

            //*********************************************************************************************
            // Get a list of Mobile Devices from tenant
            //*********************************************************************************************
            Console.WriteLine("\nGetting Devices");
            IPagedCollection <IDevice> devices = null;
            try
            {
                devices = activeDirectoryClient.Devices.ExecuteAsync().Result;
            }
            catch (Exception e)
            {
                Console.WriteLine("/nError getting devices {0} {1}", e.Message,
                                  e.InnerException != null ? e.InnerException.Message : "");
            }

            if (devices != null)
            {
                do
                {
                    List <IDevice> devicesList = devices.CurrentPage.ToList();
                    foreach (IDevice device in devicesList)
                    {
                        if (device.ObjectId != null)
                        {
                            Console.WriteLine("Device ID: {0}, Type: {1}", device.DeviceId, device.DeviceOSType);
                            IPagedCollection <IDirectoryObject> registeredOwners = device.RegisteredOwners;
                            if (registeredOwners != null)
                            {
                                do
                                {
                                    List <IDirectoryObject> registeredOwnersList = registeredOwners.CurrentPage.ToList();
                                    foreach (IDirectoryObject owner in registeredOwnersList)
                                    {
                                        Console.WriteLine("Device Owner ID: " + owner.ObjectId);
                                    }
                                    registeredOwners = registeredOwners.GetNextPageAsync().Result;
                                } while (registeredOwners != null && registeredOwners.MorePagesAvailable);
                            }
                        }
                    }
                    devices = devices.GetNextPageAsync().Result;
                } while (devices != null && devices.MorePagesAvailable);
            }

            #endregion

            #region Create New Permission

            //*********************************************************************************************
            // Create new permission object
            //*********************************************************************************************
            OAuth2PermissionGrant permissionObject = new OAuth2PermissionGrant();
            permissionObject.ConsentType = "AllPrincipals";
            permissionObject.Scope       = "user_impersonation";
            permissionObject.StartTime   = DateTime.Now;
            permissionObject.ExpiryTime  = (DateTime.Now).AddMonths(12);

            // resourceId is objectId of the resource, in this case objectId of AzureAd (Graph API)
            permissionObject.ResourceId = "52620afb-80de-4096-a826-95f4ad481686";

            //ClientId = objectId of servicePrincipal
            permissionObject.ClientId = newServicePrincpal.ObjectId;
            try
            {
                activeDirectoryClient.Oauth2PermissionGrants.AddOAuth2PermissionGrantAsync(permissionObject).Wait();
                Console.WriteLine("New Permission object created: " + permissionObject.ObjectId);
            }
            catch (Exception e)
            {
                Console.WriteLine("Permission Creation exception: {0} {1}", e.Message, e.InnerException != null ? e.InnerException.Message : "");
            }

            #endregion

            #region Get All Permissions

            //*********************************************************************************************
            // get all Permission Objects
            //*********************************************************************************************
            Console.WriteLine("\n Getting Permissions");
            IPagedCollection <IOAuth2PermissionGrant> permissions = null;
            try
            {
                permissions = activeDirectoryClient.Oauth2PermissionGrants.ExecuteAsync().Result;
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0} {1}", e.Message, e.InnerException != null ? e.InnerException.Message : "");
            }
            if (permissions != null)
            {
                do
                {
                    List <IOAuth2PermissionGrant> perms = permissions.CurrentPage.ToList();
                    foreach (IOAuth2PermissionGrant perm in perms)
                    {
                        Console.WriteLine("Permission: {0}  Name: {1}", perm.ClientId, perm.Scope);
                    }
                } while (permissions != null && permissions.MorePagesAvailable);
            }

            #endregion

            #region Delete Application

            //*********************************************************************************************
            // Delete Application Objects
            //*********************************************************************************************
            if (appObject.ObjectId != null)
            {
                try
                {
                    appObject.DeleteAsync().Wait();
                    Console.WriteLine("Deleted Application object: " + appObject.ObjectId);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Application Deletion execption: {0} {1}", e.Message,
                                      e.InnerException != null ? e.InnerException.Message : "");
                }
            }

            #endregion

            #region Batch Operations

            //*********************************************************************************************
            // Show Batching with 3 operators.  Note: up to 5 operations can be in a batch
            //*********************************************************************************************
            IReadOnlyQueryableSet <User>          userQuery   = activeDirectoryClient.DirectoryObjects.OfType <User>();
            IReadOnlyQueryableSet <Group>         groupsQuery = activeDirectoryClient.DirectoryObjects.OfType <Group>();
            IReadOnlyQueryableSet <DirectoryRole> rolesQuery  =
                activeDirectoryClient.DirectoryObjects.OfType <DirectoryRole>();
            try
            {
                IBatchElementResult[] batchResult =
                    activeDirectoryClient.Context.ExecuteBatchAsync(userQuery, groupsQuery, rolesQuery).Result;
                int responseCount = 1;
                foreach (IBatchElementResult result in batchResult)
                {
                    if (result.FailureResult != null)
                    {
                        Console.WriteLine("Failed: {0} ",
                                          result.FailureResult.InnerException);
                    }
                    if (result.SuccessResult != null)
                    {
                        Console.WriteLine("Batch Item Result {0} succeeded",
                                          responseCount++);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Batch execution failed. : {0} {1}", e.Message,
                                  e.InnerException != null ? e.InnerException.Message : "");
            }

            #endregion

            //*********************************************************************************************
            // End of Demo Console App
            //*********************************************************************************************

            Console.WriteLine("\nCompleted at {0} \n Press Any Key to Exit.", currentDateTime);
            Console.ReadKey();
        }