Ejemplo n.º 1
0
 public void DirectoryChanged(DirectoryObject oldObject, DirectoryObject newObject)
 {
     this.Directories.Remove(oldObject);
     this.Directories.Add(newObject);
     IndexImages();
 }
Ejemplo n.º 2
0
        public async Task RegisterApplicationsAsync(
            string applicationName,
            DirectoryObject owner,
            IEnumerable <string> tags           = null,
            CancellationToken cancellationToken = default
            )
        {
            tags ??= new List <string>();

            var serviceApplicationName = applicationName + "-service";
            var clientApplicationName  = applicationName + "-client";
            var aksApplicationName     = applicationName + "-aks";

            // Service Application /////////////////////////////////////////////
            // Register service application
            _serviceApplication = await RegisterServiceApplicationAsync(
                serviceApplicationName,
                owner,
                tags,
                cancellationToken
                );

            // Find service principal for service application
            _serviceApplicationSP = await _msGraphServiceClient
                                    .GetApplicationServicePrincipalAsync(_serviceApplication, cancellationToken);

            // Add current user or service principal as app owner for service
            // application, if it is not owner already.
            await _msGraphServiceClient
            .AddAsApplicationOwnerAsync(
                _serviceApplication,
                owner,
                cancellationToken
                );

            // Client Application //////////////////////////////////////////////
            // Register client application
            _clientApplication = await RegisterClientApplicationAsync(
                _serviceApplication,
                clientApplicationName,
                tags,
                cancellationToken
                );

            // Find service principal for client application
            _clientApplicationSP = await _msGraphServiceClient
                                   .GetApplicationServicePrincipalAsync(_clientApplication, cancellationToken);

            // Add current user or service principal as app owner for client
            // application, if it is not owner already.
            await _msGraphServiceClient
            .AddAsApplicationOwnerAsync(
                _clientApplication,
                owner,
                cancellationToken
                );

            // Update service application to include client application as knownClientApplications
            _serviceApplication = await _msGraphServiceClient
                                  .AddAsKnownClientApplicationAsync(
                _serviceApplication,
                _clientApplication,
                cancellationToken
                );

            // Grant admin consent for service application "user_impersonation" API permissions of client application
            // Grant admin consent for Microsoft Graph "User.Read" API permissions of client application
            await _msGraphServiceClient
            .GrantAdminConsentToClientApplicationAsync(
                _serviceApplicationSP,
                _clientApplicationSP,
                cancellationToken
                );

            // App Registration for AKS ////////////////////////////////////////
            // Register aks application
            var registrationResult = await RegisterAKSApplicationAsync(
                aksApplicationName,
                tags,
                cancellationToken
                );

            _aksApplication = registrationResult.Item1;
            _aksApplicationPasswordCredentialRbacSecret = registrationResult.Item2;

            // Find service principal for aks application
            _aksApplicationSP = await _msGraphServiceClient
                                .GetApplicationServicePrincipalAsync(_aksApplication, cancellationToken);

            // Add current user or service principal as app owner for aks
            // application, if it is not owner already.
            await _msGraphServiceClient
            .AddAsApplicationOwnerAsync(
                _aksApplication,
                owner,
                cancellationToken
                );
        }
Ejemplo n.º 3
0
 public void DeleteDirectory(DirectoryObject directory)
 {
     this.Directories.Remove(directory);
     IndexImages();
 }
Ejemplo n.º 4
0
 /// <summary>
 /// Refresh the properties of this file
 /// </summary>
 /// <returns></returns>
 public abstract Globals.ResultType Move(DirectoryObject destinationDirectoryObject);
Ejemplo n.º 5
0
        protected async Task <Application> RegisterServiceApplicationAsync(
            string serviceApplicationName,
            DirectoryObject owner,
            IEnumerable <string> tags           = null,
            CancellationToken cancellationToken = default
            )
        {
            try {
                tags ??= new List <string>();

                Log.Information("Creating service application registration ...");

                // Setup AppRoles for service application
                var serviceApplicationAppRoles = new List <AppRole>();

                var serviceApplicationApproverRoleId = Guid.NewGuid();
                serviceApplicationAppRoles.Add(new AppRole {
                    DisplayName        = "Approver",
                    Value              = "Sign",
                    Description        = "Approvers have the ability to issue certificates.",
                    AllowedMemberTypes = new List <string> {
                        "User", "Application"
                    },
                    Id = serviceApplicationApproverRoleId
                });

                var serviceApplicationWriterRoleId = Guid.NewGuid();
                serviceApplicationAppRoles.Add(new AppRole {
                    DisplayName        = "Writer",
                    Value              = "Write",
                    Description        = "Writers Have the ability to change entities.",
                    AllowedMemberTypes = new List <string> {
                        "User", "Application"
                    },
                    Id = serviceApplicationWriterRoleId
                });

                var serviceApplicationAdministratorRoleId = Guid.NewGuid();
                serviceApplicationAppRoles.Add(new AppRole {
                    DisplayName        = "Administrator",
                    Value              = "Admin",
                    Description        = "Admins can access advanced features.",
                    AllowedMemberTypes = new List <string> {
                        "User", "Application"
                    },
                    Id = serviceApplicationAdministratorRoleId
                });

                // Setup RequiredResourceAccess for service application

                var keyVaultUserImpersonationRequiredResourceAccess = new RequiredResourceAccess {
                    ResourceAppId  = AzureAppsConstants.AzureKeyVault.AppId,
                    ResourceAccess = new List <ResourceAccess> {
                        new ResourceAccess {
                            Id   = AzureAppsConstants.AzureKeyVault.ResourceAccess["user_impersonation"],
                            Type = "Scope"
                        }
                    }
                };

                var microsoftGraphUserReadRequiredResourceAccess = new RequiredResourceAccess {
                    ResourceAppId  = AzureAppsConstants.MicrosoftGraph.AppId,
                    ResourceAccess = new List <ResourceAccess> {
                        new ResourceAccess {
                            Id   = AzureAppsConstants.MicrosoftGraph.ResourceAccess["User.Read"],
                            Type = "Scope"
                        }
                    }
                };

                var serviceApplicationRequiredResourceAccess = new List <RequiredResourceAccess>()
                {
                    keyVaultUserImpersonationRequiredResourceAccess,
                    microsoftGraphUserReadRequiredResourceAccess
                };

                // Add OAuth2Permissions
                var oauth2Permissions = new List <PermissionScope> {
                    new PermissionScope {
                        AdminConsentDescription = $"Allow the app to access {serviceApplicationName} on behalf of the signed-in user.",
                        AdminConsentDisplayName = $"Access {serviceApplicationName}",
                        Id        = Guid.NewGuid(),
                        IsEnabled = true,
                        Type      = "User",
                        UserConsentDescription = $"Allow the application to access {serviceApplicationName} on your behalf.",
                        UserConsentDisplayName = $"Access {serviceApplicationName}",
                        Value = "user_impersonation"
                    }
                };

                var serviceApplicationApiApplication = new ApiApplication {
                    Oauth2PermissionScopes = oauth2Permissions
                };

                var serviceApplicationWebApplication = new WebApplication {
                    ImplicitGrantSettings = new ImplicitGrantSettings {
                        EnableIdTokenIssuance = true
                    }
                };

                var serviceApplicationDefinition = new Application {
                    DisplayName            = serviceApplicationName,
                    IsFallbackPublicClient = false,
                    IdentifierUris         = new List <string> {
                        $"https://{_tenantId.ToString()}/{serviceApplicationName}"
                    },
                    Tags                   = tags,
                    SignInAudience         = "AzureADMyOrg",
                    AppRoles               = serviceApplicationAppRoles,
                    RequiredResourceAccess = serviceApplicationRequiredResourceAccess,
                    Api = serviceApplicationApiApplication,
                    Web = serviceApplicationWebApplication,
                    PasswordCredentials = new List <PasswordCredential> {
                    }
                };

                var serviceApplication = await _msGraphServiceClient
                                         .CreateApplicationAsync(
                    serviceApplicationDefinition,
                    cancellationToken
                    );

                // Add Service Key PasswordCredential
                var serviceKeyName = "Service Key";
                await _msGraphServiceClient
                .AddApplication2YPasswordCredentialAsync(
                    serviceApplication,
                    serviceKeyName,
                    cancellationToken
                    );

                // We need to create ServicePrincipal for this application.
                var serviceApplicationSP = await _msGraphServiceClient
                                           .CreateApplicationServicePrincipalAsync(
                    serviceApplication,
                    tags,
                    cancellationToken
                    );

                // Add app role assignment to owner as Approver, Writer and Administrator.
                string PrincipalType;

                if (owner is User)
                {
                    PrincipalType = "User";
                }
                else if (owner is ServicePrincipal)
                {
                    PrincipalType = "ServicePrincipal";
                }
                else if (owner is Group)
                {
                    PrincipalType = "Group";
                }
                else
                {
                    throw new ArgumentException($"Owner is of unknown type: {owner.GetType()}", "owner");
                }

                var approverAppRoleAssignmentDefinition = new AppRoleAssignment {
                    PrincipalType       = PrincipalType,
                    PrincipalId         = new Guid(owner.Id),
                    ResourceId          = new Guid(serviceApplicationSP.Id),
                    ResourceDisplayName = "Approver",
                    Id        = serviceApplicationApproverRoleId.ToString(),
                    AppRoleId = serviceApplicationApproverRoleId
                };

                var writerAppRoleAssignmentDefinition = new AppRoleAssignment {
                    PrincipalType       = PrincipalType,
                    PrincipalId         = new Guid(owner.Id),
                    ResourceId          = new Guid(serviceApplicationSP.Id),
                    ResourceDisplayName = "Writer",
                    Id        = serviceApplicationWriterRoleId.ToString(),
                    AppRoleId = serviceApplicationWriterRoleId
                };

                var administratorAppRoleAssignmentDefinition = new AppRoleAssignment {
                    PrincipalType       = PrincipalType,
                    PrincipalId         = new Guid(owner.Id),
                    ResourceId          = new Guid(serviceApplicationSP.Id),
                    ResourceDisplayName = "Administrator",
                    Id        = serviceApplicationAdministratorRoleId.ToString(),
                    AppRoleId = serviceApplicationAdministratorRoleId
                };

                await _msGraphServiceClient
                .AddServicePrincipalAppRoleAssignmentAsync(
                    serviceApplicationSP,
                    approverAppRoleAssignmentDefinition,
                    cancellationToken
                    );

                await _msGraphServiceClient
                .AddServicePrincipalAppRoleAssignmentAsync(
                    serviceApplicationSP,
                    writerAppRoleAssignmentDefinition,
                    cancellationToken
                    );

                await _msGraphServiceClient
                .AddServicePrincipalAppRoleAssignmentAsync(
                    serviceApplicationSP,
                    administratorAppRoleAssignmentDefinition,
                    cancellationToken
                    );

                // Get updated definition
                serviceApplication = await _msGraphServiceClient
                                     .GetApplicationAsync(
                    new Guid(serviceApplication.Id),
                    cancellationToken
                    );

                Log.Information("Created service application registration.");

                return(serviceApplication);
            }
            catch (Exception) {
                Log.Error("Failed to create service application registration.");
                throw;
            }
        }
Ejemplo n.º 6
0
 public static DirectoryObject CreateDirectoryObject(string objectId)
 {
     DirectoryObject directoryObject = new DirectoryObject();
     directoryObject.objectId = objectId;
     return directoryObject;
 }
Ejemplo n.º 7
0
		public override void SaveDirectoryObject(DirectoryObject directoryObject) {
			if(directoryObject == null) {
				throw new ArgumentNullException("directoryObject");
			}
			using(DirectoryEntry directoryEntry = GetDirectoryEntry()) {
				string filter = string.Format(CultureInfo.InvariantCulture, FilterAndFormat, BaseFilter + string.Format(CultureInfo.InvariantCulture, FilterFormat, this.IdentifyingPropertyName, directoryObject.Id));
				using(DirectorySearcher directorySearcher = new DirectorySearcher(
						  directoryEntry,
						  filter,
						  PropertyNames,
						  SearchScope.Subtree)) {
					using(DirectoryEntry directoryEntryWrite = directorySearcher.FindOne().GetDirectoryEntry()) {
						bool commitChanges = false;
						foreach(string propertyName in this.PropertyNames) {
							PropertyValueCollection pvc = directoryEntryWrite.Properties[propertyName];
							string newValue = directoryObject[propertyName];
							if(pvc.Value != null) {
								if(!pvc.Value.ToString().Equals(newValue)) {
									if(!string.IsNullOrEmpty(newValue)) {
										pvc.Value = newValue;
									} else {
										pvc.RemoveAt(0);
									}
									commitChanges = true;
								}
							} else if(!string.IsNullOrEmpty(newValue)) {
								pvc.Add(newValue);
								commitChanges = true;
							}
						}
						if(commitChanges) {
							directoryEntryWrite.CommitChanges();
						}
					}
				}
			}
		}
        private void LoadDirectory()
        {
            string currentDirectory = directoryHistory[directoryHistory.Count - 1];
            lblFullPath.Text = currentDirectory;
            IList<XBDM.DirectoryObject> directoryObjects = App.XBDM.GetDirList(currentDirectory);

            filesInDirectory.Clear();
            foreach (XBDM.DirectoryObject directoryObject in directoryObjects)
            {
                DirectoryObject obj = new DirectoryObject();

                obj.IsXEX = directoryObject.IsXEX;
                obj.IsDirectory = directoryObject.IsDirectory;
                obj.Name = directoryObject.Name;
                obj.Base = directoryObject;

                if (!obj.IsDirectory)
                {
                    obj.FriendlySize = XDevKit.Helpers.GetFriendlySizeName(directoryObject.SizeLo);
                    obj.ShowSize = System.Windows.Visibility.Visible;
                }
                else
                {
                    obj.FriendlySize = "";
                    obj.ShowSize = System.Windows.Visibility.Collapsed;
                }

                filesInDirectory.Add(obj);
            }
        }
        public static void UserModeRequests()
        {
            try
            {
                //*********************************************************************
                // setup Microsoft Graph Client for user.
                //*********************************************************************
                if (Constants.ClientIdForUserAuthn != "ENTER_YOUR_CLIENT_ID")
                {
                    client = AuthenticationHelper.GetAuthenticatedClientForUser();
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("You haven't configured a value for ClientIdForUserAuthn in Constants.cs. Please follow the Readme instructions for configuring this application.");
                    Console.ResetColor();
                    Console.ReadKey();
                    return;
                }
            }
            catch (Exception 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;
            }

            Console.WriteLine("\nStarting user-mode requests...");
            Console.WriteLine("\n=============================\n\n");

            // GET current user

            try
            {
                User user = client.Me.Request().GetAsync().Result;
                Console.WriteLine("Current user:    Id: {0}  UPN: {1}", user.Id, user.UserPrincipalName);
            }

            catch (Exception e)
            {
                Console.WriteLine("\nError getting /me user {0} {1}",
                                  e.Message, e.InnerException != null ? e.InnerException.Message : "");
            }

            // Get current user photo (work or school accounts only). Returns an exception if no photo exists.

            try
            {
                Stream userPhoto = client.Me.Photo.Content.Request().GetAsync().Result;
                Console.WriteLine("Got stream photo");
            }

            catch (Exception e)
            {
                Console.WriteLine("\nError getting user photo {0} {1}",
                                  e.Message, e.InnerException != null ? e.InnerException.Message : "");
            }

            // Get current user's direct reports (work or school accounts only)
            try
            {
                IUserDirectReportsCollectionWithReferencesPage directReports = client.Me.DirectReports.Request().GetAsync().Result;

                if (directReports.Count == 0)
                {
                    Console.WriteLine("      no reports");
                }
                else
                {
                    foreach (User user in directReports)
                    {
                        Console.WriteLine("      Id: {0}  UPN: {1}", user.Id, user.UserPrincipalName);
                    }
                }
            }

            catch (Exception e)
            {
                Console.WriteLine("\nError getting directReports {0} {1}",
                                  e.Message, e.InnerException != null ? e.InnerException.Message : "");
            }

            // Get current user's manager (work or school accounts only). Returns an exception if no manager exists.
            try
            {
                DirectoryObject currentUserManager = client.Me.Manager.Request().GetAsync().Result;

                User user = client.Users[currentUserManager.Id].Request().GetAsync().Result;
                Console.WriteLine("\nManager      Id: {0}  UPN: {1}", user.Id, user.UserPrincipalName);
            }

            catch (Exception e)
            {
                Console.WriteLine("\nError getting manager {0} {1}",
                                  e.Message, e.InnerException != null ? e.InnerException.Message : "");
            }

            // Get current user's files

            try
            {
                List <DriveItem> items = client.Me.Drive.Root.Children.Request().GetAsync().Result.Take(5).ToList();

                foreach (DriveItem item in items)
                {
                    if (item.File != null)
                    {
                        Console.WriteLine("    This is a folder: Id: {0}  WebUrl: {1}", item.Id, item.WebUrl);
                    }
                    else
                    {
                        Console.WriteLine("    File Id: {0}  WebUrl: {1}", item.Id, item.WebUrl);
                    }
                }
            }

            catch (Exception e)
            {
                Console.WriteLine("\nError getting files {0} {1}",
                                  e.Message, e.InnerException != null ? e.InnerException.Message : "");
            }

            // Get current user's messages

            try
            {
                List <Message> messages = client.Me.Messages.Request().GetAsync().Result.Take(5).ToList();

                if (messages.Count == 0)
                {
                    Console.WriteLine("    no messages in mailbox");
                }
                foreach (Message message in messages)
                {
                    Console.WriteLine("    Message: {0} received {1} ", message.Subject, message.ReceivedDateTime);
                }
            }

            catch (Exception e)
            {
                Console.WriteLine("\nError getting messages {0} {1}",
                                  e.Message, e.InnerException != null ? e.InnerException.Message : "");
            }


            // Get current user's events
            try
            {
                List <Event> events = client.Me.Events.Request().GetAsync().Result.Take(5).ToList();

                if (events.Count == 0)
                {
                    Console.WriteLine("    no events scheduled");
                }
                foreach (Event _event in events)
                {
                    Console.WriteLine("    Event: {0} starts {1} ", _event.Subject, _event.Start);
                }
            }

            catch (Exception e)
            {
                Console.WriteLine("\nError getting events {0} {1}",
                                  e.Message, e.InnerException != null ? e.InnerException.Message : "");
            }

            // Get current user's contacts
            try
            {
                List <Contact> contacts = client.Me.Contacts.Request().GetAsync().Result.Take(5).ToList();

                if (contacts.Count == 0)
                {
                    Console.WriteLine("    You don't have any contacts");
                }
                foreach (Contact contact in contacts)
                {
                    Console.WriteLine("    Contact: {0} ", contact.DisplayName);
                }
            }

            catch (Exception e)
            {
                Console.WriteLine("\nError getting contacts {0} {1}",
                                  e.Message, e.InnerException != null ? e.InnerException.Message : "");
            }

            // Create a recipient list.
            IList <Recipient> messageToList = new List <Recipient>();

            // Get 10 users
            List <User> users = client.Users.Request().GetAsync().Result.Take(10).ToList();

            foreach (User user in users)
            {
                Recipient    messageTo   = new Recipient();
                EmailAddress emailAdress = new EmailAddress();
                emailAdress.Address    = user.UserPrincipalName;
                emailAdress.Name       = user.DisplayName;
                messageTo.EmailAddress = emailAdress;

                // Only uncomment this next line if you want to send this mail to the
                // first 10 accounts returned by a call to the graph.microsoft.com/v1.0/users endpoint.
                // Otherwise, this email will only be sent to the current user.

                //messageToList.Add(messageTo);
            }

            // Get current user
            User currentUser = client.Me.Request().GetAsync().Result;

            Recipient    currentUserRecipient   = new Recipient();
            EmailAddress currentUserEmailAdress = new EmailAddress();

            currentUserEmailAdress.Address    = currentUser.UserPrincipalName;
            currentUserEmailAdress.Name       = currentUser.DisplayName;
            currentUserRecipient.EmailAddress = currentUserEmailAdress;
            messageToList.Add(currentUserRecipient);

            // Send mail to signed in user and the recipient list

            Console.WriteLine();
            Console.WriteLine("Sending mail....");
            Console.WriteLine();

            try
            {
                ItemBody messageBody = new ItemBody();
                messageBody.Content     = "<report pending>";
                messageBody.ContentType = BodyType.Text;

                Message newMessage = new Message();
                newMessage.Subject      = "\nCompleted test run from console app.";
                newMessage.ToRecipients = messageToList;
                newMessage.Body         = messageBody;

                client.Me.SendMail(newMessage, true).Request().PostAsync();
                Console.WriteLine("\nMail sent to {0}", currentUser.DisplayName);
            }
            catch (Exception)
            {
                Console.WriteLine("\nUnexpected Error attempting to send an email");
                throw;
            }

            // The operations in this method require admin-level consent. Uncomment this line
            // if you want to run the sample with a non-admin account.
            // You'll also need to uncomment the Group.Read.All permission scope in AuthenticationHelper.cs
            //GetDetailsForGroups();
        }
Ejemplo n.º 10
0
 public void Ctor_NullPath()
 {
     var path = (string)null;
     var directory = new DirectoryObject(path, null);
 }
Ejemplo n.º 11
0
 private LoadContainer GetTopologyForDirectoryObject(DirectoryObject directoryObject)
 {
     return(this.GetExtractorFactory().GetExtractor(directoryObject).ExtractTopology());
 }
Ejemplo n.º 12
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();
        }
        /// <summary>
        /// ADs the object picker show dialog.
        /// </summary>
        /// <param name="handle">The owner handle.</param>
        /// <param name="showLocalUsersAndGroups">if set to <c>true</c> [show local users and groups].</param>
        /// <param name="showOnlyUsers">if set to <c>true</c> [show only users].</param>
        /// <param name="multipleSelection">if set to <c>true</c> [multiple selection].</param>
        /// <returns></returns>
        public static ADObject[] ADObjectPickerShowDialog(IWin32Window owner, bool showLocalUsersAndGroups, bool showOnlyUsers, bool multipleSelection)
        {
            #region OLD CODE
            //try
            //{
            //    // Initialize 1st search scope

            //    uint flType = 0;

            //    flType = flType |
            //        DSOP_SCOPE_TYPE_FLAGS.DSOP_SCOPE_TYPE_UPLEVEL_JOINED_DOMAIN |
            //        DSOP_SCOPE_TYPE_FLAGS.DSOP_SCOPE_TYPE_DOWNLEVEL_JOINED_DOMAIN |
            //        DSOP_SCOPE_TYPE_FLAGS.DSOP_SCOPE_TYPE_ENTERPRISE_DOMAIN |
            //        DSOP_SCOPE_TYPE_FLAGS.DSOP_SCOPE_TYPE_GLOBAL_CATALOG |
            //        DSOP_SCOPE_TYPE_FLAGS.DSOP_SCOPE_TYPE_EXTERNAL_DOWNLEVEL_DOMAIN |
            //        DSOP_SCOPE_TYPE_FLAGS.DSOP_SCOPE_TYPE_EXTERNAL_UPLEVEL_DOMAIN |
            //        DSOP_SCOPE_TYPE_FLAGS.DSOP_SCOPE_TYPE_USER_ENTERED_DOWNLEVEL_SCOPE |
            //        DSOP_SCOPE_TYPE_FLAGS.DSOP_SCOPE_TYPE_USER_ENTERED_UPLEVEL_SCOPE;
            //    //DSOP_SCOPE_TYPE_FLAGS.DSOP_SCOPE_TYPE_WORKGROUP;

            //    if (showLocalUsersAndGroups)
            //        flType = flType | DSOP_SCOPE_TYPE_FLAGS.DSOP_SCOPE_TYPE_TARGET_COMPUTER;


            //    uint flScope =
            //        DSOP_SCOPE_INIT_INFO_FLAGS.DSOP_SCOPE_FLAG_WANT_PROVIDER_LDAP |
            //        DSOP_SCOPE_INIT_INFO_FLAGS.DSOP_SCOPE_FLAG_DEFAULT_FILTER_USERS |
            //        DSOP_SCOPE_INIT_INFO_FLAGS.DSOP_SCOPE_FLAG_WANT_PROVIDER_WINNT |
            //        DSOP_SCOPE_INIT_INFO_FLAGS.DSOP_SCOPE_FLAG_STARTING_SCOPE |
            //        DSOP_SCOPE_INIT_INFO_FLAGS.DSOP_SCOPE_FLAG_WANT_DOWNLEVEL_BUILTIN_PATH; // Starting !?;

            //    if (!showOnlyUsers)
            //        flScope = flScope | DSOP_SCOPE_INIT_INFO_FLAGS.DSOP_SCOPE_FLAG_DEFAULT_FILTER_GROUPS;


            //    uint flBothModes =
            //        DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_INCLUDE_ADVANCED_VIEW |
            //        DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_USERS;

            //    if (!showOnlyUsers)
            //        flBothModes = flBothModes |
            //        DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_BUILTIN_GROUPS |
            //        //DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_DOMAIN_LOCAL_GROUPS_DL |
            //        DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_DOMAIN_LOCAL_GROUPS_SE |
            //        //DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_GLOBAL_GROUPS_DL |
            //        DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_GLOBAL_GROUPS_SE |
            //        //DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_UNIVERSAL_GROUPS_DL |
            //        DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_UNIVERSAL_GROUPS_SE |
            //        DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_WELL_KNOWN_PRINCIPALS;

            //    uint flDownlevel =
            //        //DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_ANONYMOUS |
            //        //DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_AUTHENTICATED_USER |
            //        //DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_BATCH |
            //        //DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_CREATOR_GROUP |
            //        //DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_CREATOR_OWNER |
            //        //DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_DIALUP |
            //        //DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_INTERACTIVE |
            //        //DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_LOCAL_SERVICE |
            //        //DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_NETWORK |
            //        //DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_NETWORK_SERVICE |
            //        //DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_REMOTE_LOGON |
            //        //DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_SERVICE |
            //        //DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_SYSTEM |
            //        //DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_TERMINAL_SERVER |
            //        DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_USERS;
            //    //DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_WORLD;

            //    if (!showOnlyUsers)
            //    {
            //        flDownlevel = flDownlevel
            //            | DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_ALL_WELLKNOWN_SIDS
            //            | DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_GLOBAL_GROUPS
            //            | DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_LOCAL_GROUPS;
            //    }



            //    ADObjectPickerClass cadObjectPicker = new ADObjectPickerClass();
            //    cadObjectPicker.InitInfo_OptionFlags = DSOP_INIT_INFO_FLAGS.DSOP_FLAG_SKIP_TARGET_COMPUTER_DC_CHECK;
            //    if (multipleSelection)
            //    {
            //        cadObjectPicker.InitInfo_OptionFlags = cadObjectPicker.InitInfo_OptionFlags
            //            | DSOP_INIT_INFO_FLAGS.DSOP_FLAG_MULTISELECT;
            //    }

            //    cadObjectPicker.ScopeTypeFlags = flType;
            //    cadObjectPicker.ScopeFlags = flScope;
            //    cadObjectPicker.UplevelFilterFlags_Both = flBothModes;
            //    cadObjectPicker.DownLevelFilterFlags = flDownlevel;
            //    cadObjectPicker.InvokeDialog(handle.ToInt32());
            //    ADObjectColl result = (ADObjectColl)cadObjectPicker.ADObjectsColl;
            //    ADObject[] results = new ADObject[result.Count];
            //    for (uint j = 1; j <= result.Count; j++)
            //    {
            //        try
            //        {
            //            int i = (int)j;
            //            ADObjectInfo info = (ADObjectInfo)result.Item(i);
            //            results[j - 1] = new ADObject();
            //            results[j - 1].ADSPath = info.ADPath;
            //            results[j - 1].ClassName = info.Class;
            //            results[j - 1].Name = info.Name;
            //            results[j - 1].UPN = info.UPN;
            //        }
            //        catch
            //        {
            //            continue;
            //        }
            //    }
            //    return results;
            //}
            //catch (System.ArgumentException)
            //{
            //    return new ADObject[0];
            //}
            #endregion OLD CODE
            try
            {
                // Show dialog
                DirectoryObjectPickerDialog picker = new DirectoryObjectPickerDialog();
                ObjectTypes allowedTypes           = ObjectTypes.None;

                if (!showOnlyUsers)
                {
                    allowedTypes = ObjectTypes.BuiltInGroups | ObjectTypes.Groups | ObjectTypes.Users | ObjectTypes.WellKnownPrincipals;
                }
                else
                {
                    allowedTypes = ObjectTypes.Users;
                }
                ObjectTypes defaultTypes = allowedTypes;
                picker.AllowedObjectTypes = allowedTypes;
                picker.DefaultObjectTypes = defaultTypes;
                Locations allowedLocations = Locations.None;
                Locations defaultLocations = Locations.None;
                if (showLocalUsersAndGroups)
                {
                    allowedLocations = Locations.All;
                    defaultLocations = Locations.GlobalCatalog | Locations.EnterpriseDomain | Locations.ExternalDomain | Locations.JoinedDomain;
                    if (Environment.MachineName.Equals(Environment.UserDomainName, StringComparison.CurrentCultureIgnoreCase))
                    {
                        //NOT JOINED TO A DOMAIN
                        defaultLocations |= Locations.LocalComputer;
                    }
                }
                else
                {
                    allowedLocations = Locations.GlobalCatalog | Locations.EnterpriseDomain | Locations.ExternalDomain | Locations.JoinedDomain;
                    defaultLocations = Locations.GlobalCatalog | Locations.EnterpriseDomain | Locations.ExternalDomain | Locations.JoinedDomain;
                }
                picker.AllowedLocations = allowedLocations;
                picker.DefaultLocations = defaultLocations;
                picker.MultiSelect      = multipleSelection;
                picker.ShowAdvancedView = true;
                DialogResult dialogResult = picker.ShowDialog(owner);
                if (dialogResult == DialogResult.OK)
                {
                    if (picker.SelectedObjects == null)
                    {
                        return(new ADObject[0]);
                    }
                    ADObject[] results = new ADObject[picker.SelectedObjects.Length];
                    for (int j = 0; j < picker.SelectedObjects.Length; j++)
                    {
                        try
                        {
                            DirectoryObject info = (DirectoryObject)picker.SelectedObjects[j];
                            results[j]           = new ADObject();
                            results[j].ADSPath   = info.Path;
                            results[j].ClassName = info.SchemaClassName;
                            results[j].Name      = info.Name;
                            results[j].UPN       = info.Upn;
                        }
                        catch
                        {
                            continue;
                        }
                    }
                    return(results);
                }
                else
                {
                    return(new ADObject[0]);
                }
            }
            catch
            {
                return(new ADObject[0]);
            }
        }
Ejemplo n.º 14
0
        public CatDatExtractor(string fullPath)
        {
            string        lastDir      = null;
            List <string> catFilesTemp = new List <string>();

            try
            {
                BasePath = fullPath.Substring(0, fullPath.LastIndexOf("\\"));
                lastDir  = BasePath.Substring(BasePath.LastIndexOf("\\") + 1);
                BasePath = BasePath + "\\";
            }
            catch (Exception ex)
            {
                throw new Exception("Unable to determine X-Rebirth base path.", ex);
            }

            try
            {
                catFilesTemp = Directory.GetFiles(BasePath, "*.cat").ToList();
                DatFiles     = Directory.GetFiles(BasePath, "*.dat").ToList();
            }
            catch (Exception ex)
            {
                throw new Exception("Unable to get cat and dat files.", ex);
            }

            try
            {
                foreach (string cat in catFilesTemp)
                {
                    string catName = cat.Substring(cat.LastIndexOf("\\") + 1);
                    CatFiles.Add(catName);
                    System.IO.StreamReader file = new System.IO.StreamReader(cat);
                    string b     = file.ReadLine();
                    uint   start = 0;
                    while (b != null)
                    {
                        try
                        {
                            int      i    = b.LastIndexOf('.');
                            string   a    = b.Substring(0, i);
                            string[] c    = b.Substring(i).Split(' ');
                            int      size = Convert.ToInt32(c[1]);
                            if (Structure == null)
                            {
                                Structure = new DirectoryObject(null, BasePath, catName, a + c[0], start, size, Convert.ToInt64(c[2]), c[3], 0);
                            }
                            else
                            {
                                Structure.AddPath(catName, a + c[0], start, size, Convert.ToInt64(c[2]), c[3], 0);
                            }
                            b      = file.ReadLine();
                            start += (uint)size;
                        }
                        catch (Exception ex)
                        {
                            if (b == null)
                            {
                                b = "";
                            }
                            Logger.Error("Error occurred while parsing line in cat file " + cat + " line: " + b, ex);
                        }
                    }
                }

                // Used to fill cache
                GetAllTypesCategories();

                // Async cache categories
                BackgroundWorker bw = new BackgroundWorker();

                // this allows our worker to report progress during work
                bw.WorkerReportsProgress = true;

                bw.DoWork += new DoWorkEventHandler(
                    delegate(object o, DoWorkEventArgs args)
                {
                    GetAllTypesInCategory("wares");
                });

                bw.RunWorkerAsync();
            }
            catch (Exception ex)
            {
                Logger.Error("Unable to parse cat files.", ex);
            }
        }
 public static DirectoryObject CreateDirectoryObject(string objectReference)
 {
     DirectoryObject directoryObject = new DirectoryObject();
     directoryObject.ObjectReference = objectReference;
     return directoryObject;
 }
 public MailboxEntityExtractor(DirectoryObject directoryObject, TopologyExtractorFactory extractorFactory, Band[] bands) : base(directoryObject, extractorFactory)
 {
     AnchorUtil.ThrowOnNullArgument(bands, "bands");
     this.bands = bands;
 }
Ejemplo n.º 17
0
        public async Task Should_call_graph_api_two_times_following_nextlink()
        {
            var expectedGroup = new Group {
                Id = _groupId, DisplayName = JudgeGroupName
            };

            DistributedCache.Setup(x => x.GetOrAddAsync(It.IsAny <string>(), It.IsAny <Func <Task <Group> > >())).ReturnsAsync(expectedGroup);

            _graphQueryResponse.Value.Add(_group);

            SecureHttpRequest
            .Setup(x => x.GetAsync(It.IsAny <string>(), _judgesGroup))
            .ReturnsAsync(ApiRequestHelper.CreateHttpResponseMessage(_graphQueryResponse, HttpStatusCode.OK));

            var users1 = new List <User>
            {
                new User {
                    Id = "Test123", DisplayName = "T Tester", GivenName = "Test", Surname = "Tester"
                },
                new User {
                    Id = "Test124", DisplayName = "T Test", GivenName = "Tester", Surname = "Test"
                }
            };

            var users2 = new List <User>
            {
                new User {
                    Id = "Test123", DisplayName = "T Tester", GivenName = "Test", Surname = "Tester"
                },
                new User {
                    Id = "Test124", DisplayName = "T Test", GivenName = "Tester", Surname = "Test"
                }
            };

            var directoryObject1 = new DirectoryObject {
                AdditionalData = new Dictionary <string, object>()
            };

            directoryObject1.AdditionalData.Add("value", JsonConvert.SerializeObject(users1));
            directoryObject1.AdditionalData.Add("@odata.nextLink", "someLinkToNextPage");

            var directoryObject2 = new DirectoryObject {
                AdditionalData = new Dictionary <string, object>()
            };

            directoryObject2.AdditionalData.Add("value", JsonConvert.SerializeObject(users2));

            SecureHttpRequest.Setup(s => s.GetAsync(GraphApiSettings.AccessToken, _accessUri))
            .ReturnsAsync(ApiRequestHelper.CreateHttpResponseMessage(directoryObject1, HttpStatusCode.OK));
            SecureHttpRequest.Setup(s => s.GetAsync(GraphApiSettings.AccessToken, "someLinkToNextPage"))
            .ReturnsAsync(ApiRequestHelper.CreateHttpResponseMessage(directoryObject2, HttpStatusCode.OK));

            Service = new UserApi.Services.UserAccountService
                      (
                SecureHttpRequest.Object, GraphApiSettings, IdentityServiceApiClient.Object, new Settings
            {
                IsLive  = false,
                AdGroup = new AdGroup
                {
                    Judge = JudgeGroupName
                }
            },
                DistributedCache.Object
                      );

            var response = (await Service.GetJudgesAsync()).ToList();

            response.Count.Should().Be(4);

            SecureHttpRequest.Verify(s => s.GetAsync(GraphApiSettings.AccessToken, _accessUri), Times.Once);
            SecureHttpRequest.Verify(s => s.GetAsync(GraphApiSettings.AccessToken, "someLinkToNextPage"), Times.Once);
        }
 public CachingTopologyExtractor(TopologyExtractorFactory topologyExtractorFactory, DirectoryObject directoryObject, ILogger logger, TopologyExtractor topologyExtractor, ITimer timer) : base(directoryObject, topologyExtractorFactory)
 {
     AnchorUtil.ThrowOnNullArgument(logger, "logger");
     AnchorUtil.ThrowOnNullArgument(timer, "timer");
     this.directoryObject   = directoryObject;
     this.logger            = logger;
     this.timer             = timer;
     this.topologyExtractor = (topologyExtractor ?? base.ExtractorFactory.GetExtractor(this.directoryObject));
     this.timer.SetAction(new Action(this.RefreshCachedValue), true);
 }
Ejemplo n.º 19
0
 public void AddTodirectoryObjects(DirectoryObject directoryObject)
 {
     base.AddObject("directoryObjects", directoryObject);
 }
Ejemplo n.º 20
0
 public RemoteServerTopologyExtractor(DirectoryObject directoryObject, TopologyExtractorFactory extractorFactory, Band[] bands, IClientFactory clientFactory) : base(directoryObject, extractorFactory)
 {
     this.bands         = bands;
     this.clientFactory = clientFactory;
 }
Ejemplo n.º 21
0
		public override DirectoryObject CreateDirectoryObjectInstance() {
			DirectoryObject propertiedObject = new DirectoryObject();
			Property[] properties = new Property[PropertyNames.Length];
			for(int i = 0; i < PropertyNames.Length; i++) {
				properties[i] = new Property(PropertyNames[i], null);
			}
			propertiedObject.Properties = properties;
			return propertiedObject;
		}
Ejemplo n.º 22
0
        public DirectoryObjectsAndLinks GetMsoRawObject(SyncObjectId syncObjectId, string serviceInstanceId, bool includeBackLinks, bool includeForwardLinks, int linksResultSize, out bool?allLinksCollected)
        {
            DirectoryObjectIdentity[] array = new DirectoryObjectIdentity[]
            {
                syncObjectId.ToMsoIdentity()
            };
            DirectoryObject[]        array2 = new DirectoryObject[1];
            DirectoryLink[]          array3 = new DirectoryLink[0];
            DirectoryObjectError[]   array4 = new DirectoryObjectError[0];
            DirectoryObjectsAndLinks directoryObjectsAndLinks = new DirectoryObjectsAndLinks
            {
                NextPageToken = null,
                More          = true
            };

            byte[] msoSyncCookie = this.GetMsoSyncCookie(serviceInstanceId);
            GetDirectoryObjectsOptions?getDirectoryObjectsOptions = new GetDirectoryObjectsOptions?(GetDirectoryObjectsOptions.None);

            if (includeBackLinks)
            {
                getDirectoryObjectsOptions |= GetDirectoryObjectsOptions.IncludeBackLinks;
            }
            if (includeForwardLinks)
            {
                getDirectoryObjectsOptions |= GetDirectoryObjectsOptions.IncludeForwardLinks;
            }
            if (includeForwardLinks || includeBackLinks)
            {
                allLinksCollected = new bool?(true);
            }
            else
            {
                allLinksCollected = null;
            }
            while (directoryObjectsAndLinks.More)
            {
                GetDirectoryObjectsRequest  request          = new GetDirectoryObjectsRequest((directoryObjectsAndLinks.NextPageToken == null) ? msoSyncCookie : null, (directoryObjectsAndLinks.NextPageToken == null) ? array : null, (directoryObjectsAndLinks.NextPageToken == null) ? getDirectoryObjectsOptions : null, directoryObjectsAndLinks.NextPageToken);
                GetDirectoryObjectsResponse directoryObjects = this.SyncProxy.GetDirectoryObjects(request);
                if (directoryObjects.GetDirectoryObjectsResult.Objects != null && directoryObjects.GetDirectoryObjectsResult.Objects.Length != 0 && array2[0] == null)
                {
                    directoryObjects.GetDirectoryObjectsResult.Objects.CopyTo(array2, 0);
                }
                if (allLinksCollected == true && directoryObjects.GetDirectoryObjectsResult.Links != null && directoryObjects.GetDirectoryObjectsResult.Links.Length != 0 && array3.Length <= linksResultSize)
                {
                    if (array3.Length == linksResultSize)
                    {
                        allLinksCollected = new bool?(false);
                    }
                    else
                    {
                        int num  = array3.Length;
                        int num2 = array3.Length + directoryObjects.GetDirectoryObjectsResult.Links.Length;
                        int num3 = Math.Min(linksResultSize, num2);
                        if (num2 > linksResultSize)
                        {
                            allLinksCollected = new bool?(false);
                        }
                        Array.Resize <DirectoryLink>(ref array3, num3);
                        Array.Copy(directoryObjects.GetDirectoryObjectsResult.Links, 0, array3, num, num3 - num);
                    }
                }
                if (directoryObjects.GetDirectoryObjectsResult.Errors != null && directoryObjects.GetDirectoryObjectsResult.Errors.Length != 0)
                {
                    Array.Resize <DirectoryObjectError>(ref array4, array4.Length + directoryObjects.GetDirectoryObjectsResult.Errors.Length);
                    directoryObjects.GetDirectoryObjectsResult.Errors.CopyTo(array4, array4.Length - directoryObjects.GetDirectoryObjectsResult.Errors.Length);
                }
                directoryObjectsAndLinks.NextPageToken = directoryObjects.GetDirectoryObjectsResult.NextPageToken;
                directoryObjectsAndLinks.More          = directoryObjects.GetDirectoryObjectsResult.More;
            }
            directoryObjectsAndLinks.Objects = ((array2 != null && array2[0] != null) ? array2 : new DirectoryObject[0]);
            directoryObjectsAndLinks.Links   = array3;
            directoryObjectsAndLinks.Errors  = array4;
            return(directoryObjectsAndLinks);
        }