예제 #1
0
        public void Update(UpdateOpContext context)
        {
            ExchangeConnector        exconn = (ExchangeConnector)context.Connector;
            ActiveDirectoryConnector adconn = exconn.ActiveDirectoryConnector;

            adconn.Update(context.UpdateType, context.ObjectClass, context.Uid, context.Attributes, context.Options);
        }
예제 #2
0
        /// <summary>
        /// Gets a user by his samAccountName.
        /// </summary>
        /// <param name="customerName"> The customer name. </param>
        /// <param name="samAccountName"> The samAccountName. </param>
        /// <returns>
        /// The retrieved user.
        /// </returns>
        public UserFromRepository GetBySamAccountName(string customerName, string samAccountName)
        {
            using (var activeDirectorySearcher = ActiveDirectoryConnector.GetDirectorySearcher(customerName))
            {
                activeDirectorySearcher.Filter = $"(&(sAMAccountName={samAccountName}))";

                var result = activeDirectorySearcher.FindOne();

                if (result == null)
                {
                    throw new UserNotFoundException($"The user with the sAMAccountName {samAccountName} could not be found.");
                }

                var userFromActiveDirectory = new UserFromActiveDirectory
                {
                    DistinguishedName = result.Properties["distinguishedName"][0].ToString(),
                    IsLocked          = (bool)result.GetDirectoryEntry().InvokeGet("IsAccountLocked"),
                    Attributes        = result.Properties
                };

                var userFromRepository = Mapper.Map <UserFromActiveDirectory, UserFromRepository>(userFromActiveDirectory);

                return(userFromRepository);
            }
        }
예제 #3
0
        public void Create(CreateOpContext context)
        {
            ExchangeConnector        exconn = (ExchangeConnector)context.Connector;
            ActiveDirectoryConnector adconn = exconn.ActiveDirectoryConnector;

            context.Uid = adconn.Create(context.ObjectClass, context.Attributes, context.Options);
        }
예제 #4
0
        public void ExecuteQuery(ExecuteQueryContext context)
        {
            ExchangeConnector        exconn = (ExchangeConnector)context.Connector;
            ActiveDirectoryConnector adconn = exconn.ActiveDirectoryConnector;

            adconn.ExecuteQuery(context.ObjectClass, context.Query, context.ResultsHandler, context.Options);
        }
예제 #5
0
        public void Delete(DeleteOpContext context)
        {
            ExchangeConnector        exconn = (ExchangeConnector)context.Connector;
            ActiveDirectoryConnector adconn = exconn.ActiveDirectoryConnector;

            adconn.Delete(context.ObjectClass, context.Uid, context.Options);
        }
예제 #6
0
        public void Sync(SyncOpContext context)
        {
            ExchangeConnector        exconn = (ExchangeConnector)context.Connector;
            ActiveDirectoryConnector adconn = exconn.ActiveDirectoryConnector;

            adconn.Sync(context.ObjectClass, context.SyncToken, context.SyncResultsHandler, context.Options);
        }
        /// <summary>
        /// Enables a single user by his samAccountName.
        /// </summary>
        /// <param name="customerName">The name of the customer the user belongs to.</param>
        /// <param name="samAccountName">The samAccountName of the user to unblock.</param>
        public void EnableBySamAccountName(string customerName, string samAccountName)
        {
            // Get the Directory Searcher from the Foundation
            using (var activeDirectorySearcher = ActiveDirectoryConnector.GetDirectorySearcher(customerName))
            {
                // Search for the user to activate.
                activeDirectorySearcher.Filter = "(&(sAMAccountName=" + samAccountName + "))";
                activeDirectorySearcher.PropertiesToLoad.Add("userAccountControl");

                var result = activeDirectorySearcher.FindOne();

                if (result == null)
                {
                    throw new UserNotFoundException("The user with the sAMAccountName " + samAccountName + " could not be found.");
                }

                // Get the DirectoryEntry that corresponds to the user.
                var entryToUpdate = result.GetDirectoryEntry();

                // Perform the Activation
                var val = (int)entryToUpdate.Properties["userAccountControl"].Value;
                entryToUpdate.Properties["userAccountControl"].Value = val & (int)~UserAccountControl.UF_ACCOUNT_DISABLE;

                entryToUpdate.CommitChanges();
                entryToUpdate.Close();
            }
        }
예제 #8
0
        /// <summary>
        /// Updates a single user by his samAccountName.
        /// </summary>
        /// <param name="customerNo"> The customer No. </param>
        /// <param name="samAccountName">The samAccountName of the user to update.</param>
        /// <param name="userData">The updated user data.</param>
        public void UpdateBySamAccountName(string customerNo, string samAccountName, UserFromRepository userData)
        {
            using (var activeDirectorySearcher = ActiveDirectoryConnector.GetDirectorySearcher(customerNo))
            {
                activeDirectorySearcher.Filter = $"(&(sAMAccountName={samAccountName}))";

                var result = activeDirectorySearcher.FindOne();

                if (result == null)
                {
                    throw new UserNotFoundException($"The user with the sAMAccountName {samAccountName} could not be found.");
                }

                var userEntry = result.GetDirectoryEntry();

                this.SetUserProperty(userEntry, ActiveDirectoryAttributeNames.AccountExpires, this.ParseDateToFileSystemTimeOrDefault(userData.ExpirationDate));
                this.SetUserProperty(userEntry, ActiveDirectoryAttributeNames.FirstName, userData.ForeName);
                this.SetUserProperty(userEntry, ActiveDirectoryAttributeNames.LastName, userData.SurName);
                this.SetUserProperty(userEntry, ActiveDirectoryAttributeNames.Mail, userData.Email);
                this.SetUserProperty(userEntry, ActiveDirectoryAttributeNames.Description, userData.Description);
                this.SetUserProperty(userEntry, ActiveDirectoryAttributeNames.DisplayName, userData.DisplayName);

                userEntry.CommitChanges();
                userEntry.Close();
            }
        }
예제 #9
0
        /// <summary>
        /// Creates a user with the given profile data.
        /// </summary>
        /// <param name="customerName"> The requesting users customer name. </param>
        /// <param name="userData">The data for the new account.</param>
        public void Create(string customerName, UserFromRepository userData)
        {
            using (var directoryRootEntry = ActiveDirectoryConnector.GetDirectorEntry(customerName))
            {
                userData.Name = $"{userData.ForeName} {userData.SurName}";
                userData.Cn   = userData.SamAccountName;

                try
                {
                    if (this.DirectoryEntryContainsUser(directoryRootEntry, userData.Cn))
                    {
                        throw new UserAlreadyExistsException($"A user with the CN '{userData.Cn}' already exists.");
                    }

                    if (this.DirectoryEntryContainsAccount(directoryRootEntry, userData.SamAccountName))
                    {
                        throw new UserAlreadyExistsException($"A user with the sAMAccountName '{userData.SamAccountName}' already exists.");
                    }

                    var newUser = directoryRootEntry.Children.Add($"CN={userData.Cn}", "user");

                    var userPrincipalName = $"{userData.SamAccountName}@Blueprint.local";
                    this.SetUserProperty(newUser, ActiveDirectoryAttributeNames.UserPrincipalName, userPrincipalName);
                    this.SetUserProperty(newUser, ActiveDirectoryAttributeNames.SamAccountName, userData.SamAccountName);
                    this.SetUserProperty(newUser, ActiveDirectoryAttributeNames.AccountExpires, this.ParseDateToFileSystemTimeOrDefault(userData.ExpirationDate));
                    this.SetUserProperty(newUser, ActiveDirectoryAttributeNames.Name, userData.Name);
                    this.SetUserProperty(newUser, ActiveDirectoryAttributeNames.FirstName, userData.ForeName);
                    this.SetUserProperty(newUser, ActiveDirectoryAttributeNames.LastName, userData.SurName);
                    this.SetUserProperty(newUser, ActiveDirectoryAttributeNames.Mail, userData.Email);
                    this.SetUserProperty(newUser, ActiveDirectoryAttributeNames.Description, userData.Description);
                    this.SetUserProperty(newUser, ActiveDirectoryAttributeNames.DisplayName, userData.DisplayName);

                    // Password and Group Memberships cannot be set during an initial registration.
                    // Both can only be set on already existing users, therefore the user must be saved, before we can proceed.
                    try
                    {
                        newUser.CommitChanges();
                    }
                    catch (Exception ex)
                    {
                        newUser.Close();
                        throw new UserNotCreatedException("Failed to create user!", ex);
                    }

                    // Set the new users password to the given value.
                    this.SetUserPassword(newUser, userData.Password);

                    // Add the User to some groups.
                    this.AddUserToSampleGroups(directoryRootEntry, newUser, customerName);
                }
                finally
                {
                    directoryRootEntry.Close();
                }
            }
        }
        public static void Run()
        {
            var userName = "******";
            var password = "******";

            try
            {
                // Create a connector
                var connector = new ActiveDirectoryConnector(userName, password);

                // Initialze Powershell Client
                using (var client = PowerShellClient.Create(connector))
                {
                    // Create Command
                    var geUserCommand = new PowershellCommand
                    {
                        Name              = "GetUser",
                        CommandText       = "Get-User",
                        CommandParameters = new List <PowershellCommandParameter> {
                            new PowershellCommandParameter {
                                Name = "ResultSize", Value = "unlimited"
                            },                                                                                   //"100"
                            new PowershellCommandParameter {
                                Name = "OrganizationalUnit", Value = "Marketing"
                            }
                        }
                    };

                    // Execute Command
                    var result = client.Execute <ActiveDirectory>(new List <PowershellCommand> {
                        geUserCommand
                    });

                    // Success, get the data
                    if (result.Status == StatusCode.SUCCESS)
                    {
                        var adUsers = result.Content;

                        Console.WriteLine($"{adUsers.Count} users found");
                    }
                    else // Failes show the errors
                    {
                        Console.WriteLine(result.Status);
                        Console.WriteLine(result.StatusText);
                        Console.WriteLine(result.Errors);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
예제 #11
0
        public void Sync(SyncOpContext context)
        {
            ExchangeConnector        exconn = (ExchangeConnector)context.Connector;
            ActiveDirectoryConnector adconn = exconn.ActiveDirectoryConnector;

            ICollection <string> attsToGet = null;

            if (context.Options != null && context.Options.AttributesToGet != null)
            {
                attsToGet = CollectionUtil.NewSet(context.Options.AttributesToGet);
            }

            // delegate to get the exchange attributes if requested
            SyncResultsHandler xchangeHandler = new SyncResultsHandler()
            {
                Handle = delta =>
                {
                    if (delta.DeltaType == SyncDeltaType.DELETE)
                    {
                        return(context.SyncResultsHandler.Handle(delta));
                    }

                    // replace the ad attributes with exchange ones and add recipient type and database (if requested)
                    ConnectorObject updated = ExchangeUtility.ConvertAdAttributesToExchange(delta.Object);
                    //updated = this.AddExchangeAttributes(exconn, context.ObjectClass, updated, attsToGet);
                    if (updated != delta.Object)
                    {
                        // build new sync delta, cause we changed the object
                        SyncDeltaBuilder deltaBuilder = new SyncDeltaBuilder
                        {
                            DeltaType = delta.DeltaType,
                            Token     = delta.Token,
                            Uid       = delta.Uid,
                            Object    = updated
                        };
                        delta = deltaBuilder.Build();
                    }

                    return(context.SyncResultsHandler.Handle(delta));
                }
            };

            // call AD sync, use xchangeHandler
            adconn.SyncInternal(context.ObjectClass,
                                context.SyncToken, xchangeHandler, context.Options,
                                GetAdAttributesToReturn(adconn, context.ObjectClass, context.Options));
        }
 public ExchangeConnector()
 {
     _activeDirectoryConnector = new ActiveDirectoryConnector();
     _handlers = new Dictionary <string, ObjectClassHandler>()
     {
         { ObjectClass.ACCOUNT_NAME, new AccountHandler() },
         { ActiveDirectoryConnector.OBJECTCLASS_OU, new DelegateToActiveDirectoryHandler() },
         { ActiveDirectoryConnector.OBJECTCLASS_GROUP, new DelegateToActiveDirectoryHandler() },
         { AcceptedDomainHandler.OBJECTCLASS_NAME, new AcceptedDomainHandler() },
         { GlobalAddressListHandler.OBJECTCLASS_NAME, new GlobalAddressListHandler() },
         { AddressListHandler.OBJECTCLASS_NAME, new AddressListHandler() },
         { OfflineAddressBookHandler.OBJECTCLASS_NAME, new OfflineAddressBookHandler() },
         { AddressBookPolicyHandler.OBJECTCLASS_NAME, new AddressBookPolicyHandler() },
         { DistributionGroupHandler.OBJECTCLASS_NAME, new DistributionGroupHandler() },
         { EmailAddressPolicyHandler.OBJECTCLASS_NAME, new EmailAddressPolicyHandler() }
     };
 }
예제 #13
0
        private ICollection <string> GetAdAttributesToReturn(ActiveDirectoryConnector adConnector, ObjectClass oclass, OperationOptions options)
        {
            ICollection <string> attNames = adConnector.GetAdAttributesToReturn(oclass, options);

            // In attNames there is a mix of attributes - some AD-only ones (from ObjectClasses.xml),
            // and some Exchange ones (from the schema) and some AD-only-for-Exchange ones (from the schema).
            // We should convert Exchange ones to their AD counterparts and add "hidden useful" AD attributes.

            if (oclass.Is(ObjectClass.ACCOUNT_NAME))
            {
                ICollection <string> newAttNames = new HashSet <string>(attNames);

                // IMPORTANT: we assume that "options" do not imply any additional AD attributes
                CollectionUtil.AddAll(newAttNames, ExchangeConnectorAttributes.AttMapFromAD.Keys);
                CollectionUtil.AddAll(newAttNames, ExchangeConnectorAttributes.HiddenAdAttributesToRetrieve);
                CollectionUtil.AddAll(newAttNames, ExchangeConnectorAttributes.VisibleAdAttributesToRetrieve);
                attNames = newAttNames;
            }
            return(attNames);
        }
예제 #14
0
        /// <summary>
        /// Gets all users for the given customer number.
        /// </summary>
        /// <param name="customerName">The customers name.</param>
        /// <param name="expression">The expression by which to filter the users. Empty String = Get all users.</param>
        /// <returns>A list of all retrieved users.</returns>
        public IEnumerable <UserFromRepository> GetUsers(string customerName, string expression)
        {
            // Get the DirectorySearcher from the Foundation
            using (var activeDirectorySearcher = ActiveDirectoryConnector.GetDirectorySearcher(customerName))
            {
                activeDirectorySearcher.Filter = this.GetSearchFilter(expression);

                // Get all the users for the customer
                var results = activeDirectorySearcher.FindAll();

                // Convert the search result into a viable dataset.
                var userList = (from SearchResult entry in results
                                select new UserFromActiveDirectory
                {
                    DistinguishedName = entry.Properties["distinguishedName"][0].ToString(),
                    IsLocked = (bool)entry.GetDirectoryEntry().InvokeGet("IsAccountLocked"),
                    Attributes = entry.Properties
                }).ToList();

                // Map the Users into UserFromRepository Objects to make them actually readable.
                var usersFromRepository = Mapper.Map <List <UserFromActiveDirectory>, List <UserFromRepository> >(userList);
                return(usersFromRepository);
            }
        }
        public void DeleteAndVerifyObject(ActiveDirectoryConnector connector,
            ObjectClass oclass, Uid uid, bool verifyExists, bool verifyDeleted)
        {
            Filter uidFilter = FilterBuilder.EqualTo(uid);

            if (verifyExists)
            {
                // verify that object currently exists
                ICollection<ConnectorObject> foundObjects = TestHelpers.SearchToList(
                    connector, oclass, uidFilter);

                // verify that it was deleted
                Assert.AreEqual(1, foundObjects.Count);
            }

            // delete
            try
            {
                connector.Delete(oclass, uid, null);
            }
            catch
            {
                if (verifyDeleted)
                {
                    throw;
                }
            }

            if (verifyDeleted)
            {
                // verify that object was deleted
                ICollection<ConnectorObject> deletedObjects = TestHelpers.SearchToList(
                    connector, oclass, uidFilter);

                // verify that it was deleted
                Assert.AreEqual(0, deletedObjects.Count);
            }
        }
예제 #16
0
        private async void btnCreateBackup_Click(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(TxtDlAlias.Text))
            {
                var credManager     = new CredentialManager();
                var userCredentials = credManager.GetUserCredentials();

                if (userCredentials != null)
                {
                    // Disabling pieces of UI that might interfere.
                    DlGroupMigrationViewModel.Instance.BackupControlsEnabled  = false;
                    DlGroupMigrationViewModel.Instance.RestoreControlsEnabled = false;

                    TxtBackupStatus.Text = "Identifying alias...";

                    var adConnector = new ActiveDirectoryConnector();
                    var dl          = new DistributionList {
                        Name = TxtDlAlias.Text
                    };
                    var  owner = string.Empty;
                    bool isValidDl;
                    if (!AccountSettingsViewModel.Instance.IsInternal)
                    {
                        // The user is external.
                        var connector = new ExchangeConnector();
                        owner = connector.GetExternalDistributionListOwner(TxtDlAlias.Text, userCredentials, out isValidDl);
                    }
                    else
                    {
                        // The user is internal
                        var dlDetails = await adConnector.GetDistributionListOwner(TxtDlAlias.Text);

                        owner     = dlDetails.Item1;
                        isValidDl = dlDetails.Item2;
                    }

                    bool resolveMembers = !string.IsNullOrWhiteSpace(owner);

                    if (!isValidDl)
                    {
                        var result =
                            ModernDialog.ShowMessage(
                                "The alias you provided doesn't map to a valid DL.",
                                "Hummingbird", MessageBoxButton.OK);
                        resolveMembers = false;
                    }
                    else if (!resolveMembers)
                    {
                        var result =
                            ModernDialog.ShowMessage(
                                "The group owner couldn't be found. If you attempt to retrieve members for the group, the backup will be missing the Owner property. Continue?",
                                "Hummingbird", MessageBoxButton.YesNo);
                        resolveMembers = result == MessageBoxResult.Yes;
                    }

                    if (resolveMembers)
                    {
                        dl.Owner = owner;

                        TxtBackupStatus.Text = "getting members...";

                        var members = await adConnector.GetDistributionListMembers(TxtDlAlias.Text);

                        if (members != null)
                        {
                            dl.Members = members;

                            var fsOperator = new FileSystemOperator();
                            var filePath   = fsOperator.StoreDistributionListInformation(dl);

                            if (!string.IsNullOrWhiteSpace(filePath))
                            {
                                var result =
                                    ModernDialog.ShowMessage(
                                        "A backup was created for the distribution list. Do you want to open File Explorer to find its location?",
                                        "Hummingbird", MessageBoxButton.YesNo);

                                if (result == MessageBoxResult.Yes)
                                {
                                    Process.Start("explorer.exe", string.Concat("/select, ", filePath));
                                }
                            }
                            else
                            {
                                ModernDialog.ShowMessage(
                                    "We couldn't create a backup file for this distribution list. Please try again.", "Hummingbird",
                                    MessageBoxButton.OK);
                            }
                        }
                        else
                        {
                            ModernDialog.ShowMessage(
                                "We couldn't retrieve members of the distribution list. Check your credentials and try again.", "Hummingbird",
                                MessageBoxButton.OK);
                        }
                    }

                    // Re-enable the pieces of UI that might interfere.
                    DlGroupMigrationViewModel.Instance.BackupControlsEnabled  = true;
                    DlGroupMigrationViewModel.Instance.RestoreControlsEnabled = true;
                }
                else
                {
                    ModernDialog.ShowMessage(
                        "No credentials were provided. Open Settings and add your credentials.", "Hummingbird",
                        MessageBoxButton.OK);
                }
            }
            else
            {
                ModernDialog.ShowMessage("You must include an alias.", "Hummingbird", MessageBoxButton.OK);
            }
        }
        public void TestSearchByName_group()
        {
            ActiveDirectoryConnector connector = new ActiveDirectoryConnector();
            connector.Init(ConfigHelper.GetConfiguration());

            Uid createUid = null;

            try
            {
                createUid = CreateAndVerifyObject(connector, ActiveDirectoryConnector.groupObjectClass,
                    GetNormalAttributes_Group());

                // find out what the name was
                ConnectorObject newObject = GetConnectorObjectFromUid(connector,
                    ActiveDirectoryConnector.groupObjectClass, createUid);
                Name nameAttr = newObject.Name;
                Assert.IsNotNull(nameAttr);

                //search normally
                ICollection<ConnectorObject> results = TestHelpers.SearchToList(connector,
                    ActiveDirectoryConnector.groupObjectClass, FilterBuilder.EqualTo(nameAttr));

                // there really should only be one
                Assert.AreEqual(results.Count, 1);

                // and it must have the value we were searching for
                String createName = ActiveDirectoryUtils.NormalizeLdapString(nameAttr.GetNameValue());
                String foundName = ActiveDirectoryUtils.NormalizeLdapString(results.ElementAt(0).Name.GetNameValue());
                Assert.AreEqual(createName, foundName);

                //search in uppercase
                ConnectorAttribute nameUpper = ConnectorAttributeBuilder.Build(
                    nameAttr.Name, nameAttr.GetNameValue().ToUpper());
                results = TestHelpers.SearchToList(connector,
                    ActiveDirectoryConnector.groupObjectClass, FilterBuilder.EqualTo(nameUpper));

                // there really should only be one
                Assert.AreEqual(results.Count, 1);

                // and it must have the value we were searching for
                createName = ActiveDirectoryUtils.NormalizeLdapString(nameAttr.GetNameValue());
                foundName = ActiveDirectoryUtils.NormalizeLdapString(results.ElementAt(0).Name.GetNameValue());
                Assert.AreEqual(createName, foundName);

                //search in lowercase
                ConnectorAttribute nameLower = ConnectorAttributeBuilder.Build(
                    nameAttr.Name, nameAttr.GetNameValue().ToLower());
                results = TestHelpers.SearchToList(connector,
                    ActiveDirectoryConnector.groupObjectClass, FilterBuilder.EqualTo(nameLower));

                // there really should only be one
                Assert.AreEqual(results.Count, 1);

                // and it must have the value we were searching for
                createName = ActiveDirectoryUtils.NormalizeLdapString(nameAttr.GetNameValue());
                foundName = ActiveDirectoryUtils.NormalizeLdapString(results.ElementAt(0).Name.GetNameValue());
                Assert.AreEqual(createName, foundName);

            }
            finally
            {
                if (createUid != null)
                {
                    //remove the one we created
                    DeleteAndVerifyObject(connector, ActiveDirectoryConnector.groupObjectClass,
                        createUid, false, true);
                }
            }
        }
        public void TestSearchByRegularAttributeWithWildcard_account()
        {
            ActiveDirectoryConnector connector = new ActiveDirectoryConnector();
            connector.Init(ConfigHelper.GetConfiguration());

            ICollection<Uid> uids = new HashSet<Uid>();

            try
            {
                int randomNumber = GetRandomNumber();

                String snPrefix = "nunitWCTest";

                for (int i = 0; i < 10; i++)
                {
                    ICollection<ConnectorAttribute> attributes =
                        GetNormalAttributes_Account();
                    attributes.Remove(ConnectorAttributeUtil.Find("sn", attributes));
                    attributes.Add(ConnectorAttributeBuilder.Build("sn",
                        snPrefix + GetRandomNumber()));
                    Uid tempUid = CreateAndVerifyObject(connector, ObjectClass.ACCOUNT,
                        attributes);
                    Assert.IsNotNull(tempUid);
                    uids.Add(tempUid);
                }

                ICollection<ConnectorObject> results = TestHelpers.SearchToList(connector,
                    ObjectClass.ACCOUNT, FilterBuilder.StartsWith(
                    ConnectorAttributeBuilder.Build("sn", snPrefix)));

                // there should be at least the newly created one
                Assert.GreaterOrEqual(results.Count, 1);

                // make a duplicate list
                ICollection<Uid> uidsToValidate = new HashSet<Uid>(uids);

                // and it must have the value we were searching for
                foreach (ConnectorObject resultObject in results)
                {
                    ConnectorAttribute foundSnAttr =
                        resultObject.GetAttributeByName("sn");
                    String snValue = ConnectorAttributeUtil.GetStringValue(foundSnAttr);
                    Assert.That(snValue.StartsWith(snPrefix));
                    uidsToValidate.Remove(resultObject.Uid);
                    if (uidsToValidate.Count == 0)
                    {
                        break;
                    }
                }
                Assert.AreEqual(0, uidsToValidate.Count);
            }
            finally
            {
                foreach (Uid createdUid in uids)
                {
                    //remove the one we created
                    DeleteAndVerifyObject(connector, ObjectClass.ACCOUNT,
                        createdUid, false, true);
                }
            }
        }
        public void TestBasics_Group()
        {
            //Initialize Connector
            ActiveDirectoryConnector connector = new ActiveDirectoryConnector();
            connector.Init(ConfigHelper.GetConfiguration());

            Uid uidToDelete = null;
            try
            {
                // create group
                ICollection<ConnectorAttribute> createAttributes = GetNormalAttributes_Group();
                createAttributes.Add(ConnectorAttributeBuilder.Build(ActiveDirectoryConnector.ATT_ACCOUNTS,
                    CreateGroupMember(connector)));

                // create object
                uidToDelete = connector.Create(ActiveDirectoryConnector.groupObjectClass, createAttributes, null);
                Uid createUid = uidToDelete;
                Assert.IsNotNull(createUid);

                // find new object ... have to add groups to list of things to return
                OperationOptionsBuilder optionsBuilder = new OperationOptionsBuilder();
                ICollection<String> attributesToGet = GetDefaultAttributesToGet(ActiveDirectoryConnector.groupObjectClass);
                attributesToGet.Add(ActiveDirectoryConnector.ATT_ACCOUNTS);
                optionsBuilder.AttributesToGet = attributesToGet.ToArray();

                ConnectorObject newObject = GetConnectorObjectFromUid(connector,
                    ActiveDirectoryConnector.groupObjectClass, createUid, optionsBuilder.Build());
                VerifyObject(createAttributes, newObject);
                // update the group - replace
                ICollection<ConnectorAttribute> updateReplaceAttrs =
                    new List<ConnectorAttribute>();
                Name oldName = ConnectorAttributeUtil.GetNameFromAttributes(createAttributes);
                String newName = ActiveDirectoryUtils.GetRelativeName(oldName);
                newName = newName.Trim() + "_new, " + GetProperty(ConfigHelper.CONFIG_PROPERTY_CONTAINER);

                updateReplaceAttrs.Add(createUid);
                updateReplaceAttrs.Add(ConnectorAttributeBuilder.Build(
                    Name.NAME, newName));
                updateReplaceAttrs.Add(ConnectorAttributeBuilder.Build(
                    "description", "New description"));
                uidToDelete = UpdateReplaceAndVerifyObject(connector,
                    ActiveDirectoryConnector.groupObjectClass, createUid, updateReplaceAttrs);
                Uid updateReplaceUid = uidToDelete;

                // update the group - add
                ICollection<ConnectorAttribute> updateAddAttrs =
                    new List<ConnectorAttribute>();
                updateAddAttrs.Add(ConnectorAttributeBuilder.Build(ActiveDirectoryConnector.ATT_ACCOUNTS,
                    CreateGroupMember(connector), CreateGroupMember(connector)));

                uidToDelete = UpdateAddAndVerifyUser(connector,
                    ActiveDirectoryConnector.groupObjectClass, updateReplaceUid, updateAddAttrs, optionsBuilder.Build());
            }
            finally
            {
                if (uidToDelete != null)
                {
                    // delete user
                    DeleteAndVerifyObject(connector, ActiveDirectoryConnector.groupObjectClass, uidToDelete, true, true);
                }
            }
        }
        public void TestBasics_Account()
        {
            //Initialize Connector
            ActiveDirectoryConnector connector = new ActiveDirectoryConnector();
            connector.Init(ConfigHelper.GetConfiguration());

            // create user
            ICollection<ConnectorAttribute> createAttributes = GetNormalAttributes_Account();
            Uid createUid = CreateAndVerifyObject(connector,
                ObjectClass.ACCOUNT, createAttributes);

            // update the user - replace
            ICollection<ConnectorAttribute> updateReplaceAttrs =
                new List<ConnectorAttribute>();
            Name oldName = ConnectorAttributeUtil.GetNameFromAttributes(createAttributes);
            String newName = ActiveDirectoryUtils.GetRelativeName(oldName);
            newName = newName.Trim() + "_new, " + GetProperty(ConfigHelper.CONFIG_PROPERTY_CONTAINER);
            updateReplaceAttrs.Add(ConnectorAttributeBuilder.Build(
                Name.NAME, newName));
            updateReplaceAttrs.Add(ConnectorAttributeBuilder.Build(
                "sn", "newsn"));
            Uid updateReplaceUid = UpdateReplaceAndVerifyObject(connector,
                ObjectClass.ACCOUNT, createUid, updateReplaceAttrs);

            // update the user - add
            ICollection<ConnectorAttribute> updateAddAttrs =
                new List<ConnectorAttribute>();
            updateAddAttrs.Add(ConnectorAttributeBuilder.Build("otherHomePhone", "123.456.7890", "098.765.4321"));
            Uid updateAddUid = UpdateAddAndVerifyUser(connector,
                ObjectClass.ACCOUNT, createUid, updateAddAttrs, null);

            // update the user - delete

            // delete user
            DeleteAndVerifyObject(connector, ObjectClass.ACCOUNT, createUid, true, true);
        }
        public void TestSearchNoFilter_Group()
        {
            ActiveDirectoryConnector connector = new ActiveDirectoryConnector();
            connector.Init(ConfigHelper.GetConfiguration());
            ICollection<Uid> createdUids = new HashSet<Uid>();

            try
            {
                int numCreated = 0;
                for (numCreated = 0; numCreated < 5; numCreated++)
                {
                    createdUids.Add(CreateAndVerifyObject(connector,
                        ActiveDirectoryConnector.groupObjectClass, GetNormalAttributes_Group()));
                }

                ICollection<ConnectorObject> results = TestHelpers.SearchToList(connector,
                    ActiveDirectoryConnector.groupObjectClass, null);

                // not sure how many should be found ... it should find everything
                // it's hard to say how many that is, but it should at least find the
                // number we created
                Assert.GreaterOrEqual(results.Count, numCreated);

                // check that they are all of the proper objectclass
                foreach (ConnectorObject co in results)
                {
                    ConnectorAttribute objectClassAttr =
                        co.GetAttributeByName("objectClass");
                    Boolean foundCorrectObjectClass = false;
                    foreach (Object o in objectClassAttr.Value)
                    {
                        if ((o is String) && (o != null))
                        {
                            String stringValue = (String)o;
                            if (stringValue.ToUpper().Trim().Equals(
                                ActiveDirectoryConnector.OBJECTCLASS_GROUP, StringComparison.CurrentCultureIgnoreCase))
                            {
                                foundCorrectObjectClass = true;
                            }
                        }
                    }
                    Assert.IsTrue(foundCorrectObjectClass);
                }
            }
            finally
            {
                foreach (Uid uid in createdUids)
                {
                    if (uid != null)
                    {
                        DeleteAndVerifyObject(connector, ActiveDirectoryConnector.groupObjectClass, uid, false, true);
                    }
                }
            }
        }
        public Uid UpdateAddAndVerifyUser(ActiveDirectoryConnector connector,
            ObjectClass oclass, Uid uid, ICollection<ConnectorAttribute> attributes,
            OperationOptions searchOptions)
        {
            // find the existing one, and save off all attributes
            Filter uidFilter = FilterBuilder.EqualTo(uid);
            ICollection<ConnectorObject> currentObjects = TestHelpers.SearchToList(
                connector, oclass, uidFilter, searchOptions);
            Assert.IsTrue(currentObjects.Count == 1);
            ICollection<ConnectorAttribute> currentAttributes =
                currentObjects.ElementAt(0).GetAttributes();

            // build a list that has the 'added' values added to the existing values
            ICollection<ConnectorAttribute> comparisonAttributes = new List<ConnectorAttribute>();
            foreach (ConnectorAttribute updateAttribute in attributes)
            {
                ConnectorAttribute existingAttribute = ConnectorAttributeUtil.Find(
                    updateAttribute.Name, currentAttributes);
                comparisonAttributes.Add(AttConcat(updateAttribute, existingAttribute));
            }

            // make sure the uid is present in the attributes
            attributes.Add(uid);
            // now update with ADD to add additional home phones
            Uid updatedUid = connector.Update(UpdateType.ADD, oclass,
                attributes, null);

            // find it back
            ICollection<ConnectorObject> updatedObjects = TestHelpers.SearchToList(
                connector, oclass, uidFilter, searchOptions);
            Assert.IsTrue(updatedObjects.Count == 1);

            VerifyObject(comparisonAttributes, updatedObjects.ElementAt(0));

            return updatedUid;
        }
        public void Test_OpAtt_Enabled_Account()
        {
            //Initialize Connector
            ActiveDirectoryConnector connector = new ActiveDirectoryConnector();
            connector.Init(ConfigHelper.GetConfiguration());
            Uid createUid = null;

            try
            {
                // create user
                ICollection<ConnectorAttribute> createAttributes = GetNormalAttributes_Account();
                createAttributes.Add(ConnectorAttributeBuilder.BuildEnabled(true));
                createUid = CreateAndVerifyObject(connector,
                    ObjectClass.ACCOUNT, createAttributes);

                ICollection<ConnectorAttribute> updateReplaceAttributes =
                    new HashSet<ConnectorAttribute>();
                updateReplaceAttributes.Add(ConnectorAttributeBuilder.BuildEnabled(false));
                UpdateReplaceAndVerifyObject(connector, ObjectClass.ACCOUNT,
                    createUid, updateReplaceAttributes);
            }
            finally
            {
                if (createUid != null)
                {
                    //remove the one we created
                    DeleteAndVerifyObject(connector, ObjectClass.ACCOUNT,
                        createUid, false, true);
                }
            }
        }
        public void TestUserPasswordChange()
        {
            //Initialize Connector
            ActiveDirectoryConnector connector = new ActiveDirectoryConnector();
            connector.Init(ConfigHelper.GetConfiguration());
            Uid createUid = null;

            try
            {
                // create user
                ICollection<ConnectorAttribute> createAttributes = GetNormalAttributes_Account();
                // remove password, and set to something memorable
                createAttributes.Remove(ConnectorAttributeUtil.Find(OperationalAttributes.PASSWORD_NAME, createAttributes));
                GuardedString gsCurrentPassword = GetGuardedString("1Password");
                createAttributes.Add(ConnectorAttributeBuilder.BuildPassword(gsCurrentPassword));
                createAttributes.Add(ConnectorAttributeBuilder.BuildEnabled(true));
                createUid = CreateAndVerifyObject(connector,
                    ObjectClass.ACCOUNT, createAttributes);

                // make sure authenticate works here
                connector.Authenticate(ObjectClass.ACCOUNT,
                    ConnectorAttributeUtil.GetAsStringValue(ConnectorAttributeUtil.Find("sAMAccountName", createAttributes)),
                    gsCurrentPassword, null);

                ICollection<ConnectorAttribute> updateReplaceAttributes =
                    new HashSet<ConnectorAttribute>();
                GuardedString gsNewPassword = GetGuardedString("LongPassword2MeetTheRequirements!");
                updateReplaceAttributes.Add(ConnectorAttributeBuilder.BuildCurrentPassword(gsCurrentPassword));
                updateReplaceAttributes.Add(ConnectorAttributeBuilder.BuildPassword(gsNewPassword));
                UpdateReplaceAndVerifyObject(connector, ObjectClass.ACCOUNT,
                    createUid, updateReplaceAttributes);

                // make sure authenticate works here
                connector.Authenticate(ObjectClass.ACCOUNT,
                    ConnectorAttributeUtil.GetAsStringValue(ConnectorAttributeUtil.Find("sAMAccountName", createAttributes)),
                    gsNewPassword, null);

                bool caughtAuthenticateFailedException = false;
                try
                {
                    // make sure authenticate doesnt work with original password
                    connector.Authenticate(ObjectClass.ACCOUNT,
                        ConnectorAttributeUtil.GetAsStringValue(ConnectorAttributeUtil.Find("sAMAccountName", createAttributes)),
                        gsCurrentPassword, null);
                }
                catch (Exception e)
                {
                    caughtAuthenticateFailedException = true;
                }

                Assert.IsTrue(caughtAuthenticateFailedException, "Negative test case should throw an exception");

                // now a negative test case
                GuardedString gsBogusPassword = GetGuardedString("BogusPassword");
                ICollection<ConnectorAttribute> updateErrorReplaceAttributes =
                    new HashSet<ConnectorAttribute>();
                updateErrorReplaceAttributes.Add(ConnectorAttributeBuilder.BuildCurrentPassword(gsBogusPassword));
                updateErrorReplaceAttributes.Add(ConnectorAttributeBuilder.BuildPassword(gsNewPassword));
                bool caughtWrongCurrentPasswordException = false;
                try
                {
                    // update should fail due to wrong current password
                    UpdateReplaceAndVerifyObject(connector, ObjectClass.ACCOUNT,
                        createUid, updateErrorReplaceAttributes);
                }
                catch (Exception e)
                {
                    caughtWrongCurrentPasswordException = true;
                }

                Assert.IsTrue(caughtWrongCurrentPasswordException, "Negative test case should throw an exception");

                // make sure authenticate works here

            }
            finally
            {
                if (createUid != null)
                {
                    //remove the one we created
                    DeleteAndVerifyObject(connector, ObjectClass.ACCOUNT,
                        createUid, false, true);
                }
            }
        }
        public void TestUnmatchedCaseGUIDSearch()
        {
            //Initialize Connector
            ActiveDirectoryConnector connector = new ActiveDirectoryConnector();
            connector.Init(ConfigHelper.GetConfiguration());
            Uid userUid = null;
            try
            {
                // test normal case
                userUid = CreateAndVerifyObject(connector,
                    ObjectClass.ACCOUNT, GetNormalAttributes_Account());
                Filter userUidFilter = FilterBuilder.EqualTo(userUid);
                IList<ConnectorObject> foundUserObjects =
                    TestHelpers.SearchToList(connector, ObjectClass.ACCOUNT, userUidFilter);
                Assert.AreEqual(1, foundUserObjects.Count);

                // now test for searching with uppercase guid
                userUidFilter = FilterBuilder.EqualTo(new Uid(userUid.GetUidValue().ToUpper()));
                foundUserObjects = TestHelpers.SearchToList(
                    connector, ObjectClass.ACCOUNT, userUidFilter);
                Assert.AreEqual(1, foundUserObjects.Count);

                // now test for searching with lowercase guid
                userUidFilter = FilterBuilder.EqualTo(new Uid(userUid.GetUidValue().ToLower()));
                foundUserObjects = TestHelpers.SearchToList(
                    connector, ObjectClass.ACCOUNT, userUidFilter);
                Assert.AreEqual(1, foundUserObjects.Count);
            }
            finally
            {
                if (userUid != null)
                {
                    DeleteAndVerifyObject(connector, ObjectClass.ACCOUNT, userUid, false, false);
                }
            }
        }
        public void TestTest()
        {
            ActiveDirectoryConnector connectorGood = new ActiveDirectoryConnector();
            ActiveDirectoryConfiguration config = (ActiveDirectoryConfiguration)ConfigHelper.GetConfiguration();
            connectorGood.Init(config);
            connectorGood.Test();

            var objectClass = config.ObjectClass;
            try
            {
                config.ObjectClass = "BadObjectClass";
                ActiveDirectoryConnector connectorBad = new ActiveDirectoryConnector();
                connectorBad.Init(config);
                connectorBad.Test();

                Assert.Fail("Bad configuration should have caused an exception");
            }
            catch (ConnectorException e)
            {
                config.ObjectClass = objectClass;
            }

            var container = config.Container;
            try
            {
                config.Container += ",DC=BadDC";
                ActiveDirectoryConnector connectorBad = new ActiveDirectoryConnector();
                connectorBad.Init(config);
                connectorBad.Test();

                Assert.Fail("Configuration with bad DC in Container should have caused an exception");
            }
            catch (ConnectorException e)
            {
                config.Container = container;
            }
        }
        public void TestSync(bool searchChildDomains, String container)
        {
            //Initialize Connector
            ActiveDirectoryConnector connector = new ActiveDirectoryConnector();
            ActiveDirectoryConfiguration configuration =
                (ActiveDirectoryConfiguration)ConfigHelper.GetConfiguration();
            configuration.SearchContext = container;
            configuration.SearchChildDomains = searchChildDomains;
            connector.Init(configuration);

            Uid createUid = null;

            ICollection<Uid> createdUids = new List<Uid>();
            try
            {
                SyncTestHelper syncHelper = new SyncTestHelper();

                // do the first sync
                //connector.Sync(ObjectClass.ACCOUNT, syncHelper.Token, syncHelper.SyncHandler_Initial, null);

                syncHelper.Init(connector.GetLatestSyncToken(ObjectClass.ACCOUNT));
                ICollection<ConnectorAttribute> attributes = null;

                // create some users
                for (int i = 0; i < 10; i++)
                {
                    attributes = GetNormalAttributes_Account();
                    createUid = CreateAndVerifyObject(connector, ObjectClass.ACCOUNT,
                        attributes);
                    syncHelper.AddModUid(createUid, attributes);
                    createdUids.Add(createUid);
                }

                // sync, and verify
                connector.Sync(ObjectClass.ACCOUNT, syncHelper._token, syncHelper.SyncHandler_ModifiedAccounts, null);
                syncHelper.CheckAllSyncsProcessed();

                // reset everything
                syncHelper.Init(connector.GetLatestSyncToken(ObjectClass.ACCOUNT));

                // modify a user, then add some users, then modify one of the added users
                attributes = new List<ConnectorAttribute>();
                attributes.Add(createdUids.First());
                attributes.Add(ConnectorAttributeBuilder.Build("sn", "replaced"));
                connector.Update(UpdateType.REPLACE, ObjectClass.ACCOUNT, attributes, null);
                syncHelper.AddModUid(createdUids.First(), attributes);

                for (int i = 0; i < 10; i++)
                {
                    attributes = GetNormalAttributes_Account();
                    createUid = CreateAndVerifyObject(connector, ObjectClass.ACCOUNT,
                        attributes);
                    syncHelper.AddModUid(createUid, attributes);
                    createdUids.Add(createUid);
                }

                attributes = new List<ConnectorAttribute>();
                attributes.Add(createdUids.Last());
                attributes.Add(ConnectorAttributeBuilder.Build("sn", "replaced"));
                connector.Update(UpdateType.REPLACE, ObjectClass.ACCOUNT, attributes, null);
                syncHelper.AddModUid(createdUids.Last(), attributes);

                // sync, and verify
                connector.Sync(ObjectClass.ACCOUNT, syncHelper._token, syncHelper.SyncHandler_ModifiedAccounts, null);
                syncHelper.CheckAllSyncsProcessed();

                syncHelper.Init(connector.GetLatestSyncToken(ObjectClass.ACCOUNT));
                // delete the user
                foreach (Uid uid in createdUids)
                {
                    DeleteAndVerifyObject(connector, ObjectClass.ACCOUNT, uid,
                        false, true);
                    syncHelper.AddDelUid(uid);
                }
                // sync and verify
                connector.Sync(ObjectClass.ACCOUNT, syncHelper._token, syncHelper.SyncHandler_DeletedAccounts, null);
                syncHelper.CheckAllSyncsProcessed();

                createUid = CreateAndVerifyObject(connector, ObjectClass.ACCOUNT,
                    GetNormalAttributes_Account());
                syncHelper.AddModUid(createUid, attributes);
                createdUids.Add(createUid);

                // now get the latest sync token, and it
                // should be greater or equal to the last one we saw
                SyncToken latestToken = connector.GetLatestSyncToken(ObjectClass.ACCOUNT);
                Assert.Greater(GetUpdateUsnFromToken(latestToken), GetUpdateUsnFromToken(syncHelper._token));
                Assert.GreaterOrEqual(GetDeleteUsnFromToken(latestToken), GetDeleteUsnFromToken(syncHelper._token));
            }
            finally
            {
                foreach (Uid uid in createdUids)
                {
                    DeleteAndVerifyObject(connector, ObjectClass.ACCOUNT, uid,
                        false, false);
                }
            }
        }
        public void TestShortnameAndDescription()
        {
            //Initialize Connector
            ActiveDirectoryConnector connector = new ActiveDirectoryConnector();
            connector.Init(ConfigHelper.GetConfiguration());
            Uid uidAccount = null;
            Uid uidGroup = null;
            Uid uidOu = null;
            string accountDescription = "nunit test account description";
            string groupDescription = "nunit test group description";
            string ouDescription = "nunit test ou description";
            try
            {
                ICollection<ConnectorAttribute> accountAttributes = GetNormalAttributes_Account();
                RemoveAttributeByName(accountAttributes, "description");
                accountAttributes.Add(ConnectorAttributeBuilder.Build(
                    "description", accountDescription));
                ICollection<ConnectorAttribute> groupAttributes = GetNormalAttributes_Group();
                RemoveAttributeByName(groupAttributes, "description");
                groupAttributes.Add(ConnectorAttributeBuilder.Build(
                    "description", groupDescription));
                ICollection<ConnectorAttribute> ouAttributes = GetNormalAttributes_OrganizationalUnit();
                RemoveAttributeByName(ouAttributes, "description");
                ouAttributes.Add(ConnectorAttributeBuilder.Build(
                    "description", ouDescription));

                uidAccount = CreateObject(connector, ObjectClass.ACCOUNT, accountAttributes);

                OperationOptionsBuilder accountOptionsBuilder = new OperationOptionsBuilder();
                ICollection<String> accountAttributesToGet = GetDefaultAttributesToGet(ObjectClass.ACCOUNT);
                accountAttributesToGet.Add(PredefinedAttributes.DESCRIPTION);
                accountAttributesToGet.Add(PredefinedAttributes.SHORT_NAME);
                accountAttributesToGet.Add("name");
                accountAttributesToGet.Add("description");
                accountOptionsBuilder.AttributesToGet = accountAttributesToGet.ToArray();

                ConnectorObject accountObject = GetConnectorObjectFromUid(connector,
                    ObjectClass.ACCOUNT, uidAccount, accountOptionsBuilder.Build());

                // compare description
                string foundAccountDescription = ConnectorAttributeUtil.GetStringValue(
                    ConnectorAttributeUtil.Find(PredefinedAttributes.DESCRIPTION, accountObject.GetAttributes()));
                Assert.AreEqual(accountDescription, foundAccountDescription);

                // compare shortname
                string accountShortName = ConnectorAttributeUtil.GetStringValue(
                    ConnectorAttributeUtil.Find(
                    PredefinedAttributes.SHORT_NAME, accountObject.GetAttributes()));
                string accountDisplayName = ConnectorAttributeUtil.GetStringValue(
                    ConnectorAttributeUtil.Find(
                    "name", accountObject.GetAttributes()));
                Assert.AreEqual(accountShortName, accountDisplayName);

                uidGroup = CreateObject(connector, ActiveDirectoryConnector.groupObjectClass, groupAttributes);

                OperationOptionsBuilder groupOptionsBuilder = new OperationOptionsBuilder();
                ICollection<String> groupAttributesToGet = GetDefaultAttributesToGet(ActiveDirectoryConnector.groupObjectClass);
                groupAttributesToGet.Add(PredefinedAttributes.DESCRIPTION);
                groupAttributesToGet.Add(PredefinedAttributes.SHORT_NAME);
                groupAttributesToGet.Add("name");
                groupAttributesToGet.Add("description");
                groupOptionsBuilder.AttributesToGet = groupAttributesToGet.ToArray();

                ConnectorObject groupObject = GetConnectorObjectFromUid(connector,
                    ActiveDirectoryConnector.groupObjectClass, uidGroup, groupOptionsBuilder.Build());

                // compare description
                string foundGroupDescription = ConnectorAttributeUtil.GetStringValue(
                    ConnectorAttributeUtil.Find(PredefinedAttributes.DESCRIPTION, groupObject.GetAttributes()));
                Assert.AreEqual(groupDescription, foundGroupDescription);

                // compare shortnameB
                string groupShortName = ConnectorAttributeUtil.GetStringValue(
                    ConnectorAttributeUtil.Find(
                    PredefinedAttributes.SHORT_NAME, groupObject.GetAttributes()));
                string groupDisplayName = ConnectorAttributeUtil.GetStringValue(
                    ConnectorAttributeUtil.Find(
                    "name", groupObject.GetAttributes()));
                Assert.AreEqual(groupShortName, groupDisplayName);

                uidOu = CreateObject(connector, ActiveDirectoryConnector.ouObjectClass, ouAttributes);
                OperationOptionsBuilder ouOptionsBuilder = new OperationOptionsBuilder();
                ICollection<String> ouAttributesToGet = GetDefaultAttributesToGet(ActiveDirectoryConnector.ouObjectClass);
                ouAttributesToGet.Add(PredefinedAttributes.DESCRIPTION);
                ouAttributesToGet.Add(PredefinedAttributes.SHORT_NAME);
                ouAttributesToGet.Add("name");
                ouAttributesToGet.Add("description");
                ouOptionsBuilder.AttributesToGet = ouAttributesToGet.ToArray();

                ConnectorObject ouObject = GetConnectorObjectFromUid(connector,
                    ActiveDirectoryConnector.ouObjectClass, uidOu, ouOptionsBuilder.Build());

                // compare description
                string foundOuDescription = ConnectorAttributeUtil.GetStringValue(
                    ConnectorAttributeUtil.Find(PredefinedAttributes.DESCRIPTION, ouObject.GetAttributes()));
                Assert.AreEqual(ouDescription, foundOuDescription);

                // compare shortname
                string ouShortName = ConnectorAttributeUtil.GetStringValue(
                    ConnectorAttributeUtil.Find(
                    PredefinedAttributes.SHORT_NAME, ouObject.GetAttributes()));
                string ouDisplayName = ConnectorAttributeUtil.GetStringValue(
                    ConnectorAttributeUtil.Find(
                    "name", ouObject.GetAttributes()));
                Assert.AreEqual(ouShortName, ouDisplayName);
            }
            finally
            {
                if (uidAccount != null)
                {
                    //remove the one we created
                    DeleteAndVerifyObject(connector, ObjectClass.ACCOUNT,
                        uidAccount, false, true);
                }
                if (uidGroup != null)
                {
                    //remove the one we created
                    DeleteAndVerifyObject(connector, ActiveDirectoryConnector.groupObjectClass,
                        uidGroup, false, true);
                }
                if (uidOu != null)
                {
                    //remove the one we created
                    DeleteAndVerifyObject(connector, ActiveDirectoryConnector.ouObjectClass,
                        uidOu, false, true);
                }
            }
        }
예제 #29
0
        public void Create(CreateOpContext context)
        {
            context.Attributes = DeduplicateEmailAddresses(context, context.Attributes);

            // get recipient type
            string rcptType = ExchangeUtility.GetAttValue(ExchangeConnectorAttributes.AttRecipientType, context.Attributes) as string;

            if (rcptType == null || rcptType.Equals(""))
            {
                rcptType = ExchangeConnectorAttributes.RcptTypeUser;
            }

            ExchangeConnector        exconn = (ExchangeConnector)context.Connector;
            ActiveDirectoryConnector adconn = exconn.ActiveDirectoryConnector;

            PSExchangeConnector.CommandInfo cmdInfoEnable = null;
            PSExchangeConnector.CommandInfo cmdInfoSet    = null;
            switch (rcptType)
            {
            case ExchangeConnectorAttributes.RcptTypeMailBox:
                cmdInfoEnable = PSExchangeConnector.CommandInfo.EnableMailbox;
                cmdInfoSet    = PSExchangeConnector.CommandInfo.SetMailbox;
                break;

            case ExchangeConnectorAttributes.RcptTypeMailUser:
                cmdInfoEnable = PSExchangeConnector.CommandInfo.EnableMailUser;
                cmdInfoSet    = PSExchangeConnector.CommandInfo.SetMailUser;
                break;

            case ExchangeConnectorAttributes.RcptTypeUser:
                break;

            default:
                throw new ArgumentException(
                          context.ConnectorConfiguration.ConnectorMessages.Format(
                              "ex_bad_rcpt", "Recipient type [{0}] is not supported", rcptType));
            }

            // first create the object in AD
            ICollection <ConnectorAttribute> adAttributes = ExchangeUtility.FilterOut(context.Attributes,
                                                                                      PSExchangeConnector.CommandInfo.EnableMailbox,
                                                                                      PSExchangeConnector.CommandInfo.SetMailbox,
                                                                                      PSExchangeConnector.CommandInfo.EnableMailUser,
                                                                                      PSExchangeConnector.CommandInfo.SetMailUser);
            Uid uid = adconn.Create(context.ObjectClass, adAttributes, context.Options);

            if (rcptType == ExchangeConnectorAttributes.RcptTypeUser)
            {
                // AD account only, we do nothing
                context.Uid = uid;
                return;
            }

            // add a empty "EmailAddresses" attribute if needed (address policy is disabled and no addresses are provided)
            ICollection <ConnectorAttribute> enhancedAttributes;
            ConnectorAttribute policyEnabledAttribute = ConnectorAttributeUtil.Find(ExchangeConnectorAttributes.AttEmailAddressPolicyEnabled, context.Attributes);

            if (policyEnabledAttribute != null &&
                ConnectorAttributeUtil.GetBooleanValue(policyEnabledAttribute).HasValue&&
                ConnectorAttributeUtil.GetBooleanValue(policyEnabledAttribute).Value == false &&
                ConnectorAttributeUtil.Find(ExchangeConnectorAttributes.AttPrimarySmtpAddress, context.Attributes) == null &&
                ConnectorAttributeUtil.Find(ExchangeConnectorAttributes.AttEmailAddresses, context.Attributes) == null)
            {
                enhancedAttributes = new HashSet <ConnectorAttribute>(context.Attributes);
                enhancedAttributes.Add(ConnectorAttributeBuilder.Build(ExchangeConnectorAttributes.AttEmailAddresses));
                LOGGER.TraceEvent(TraceEventType.Verbose, CAT_DEFAULT, "Added empty EmailAddresses attribute because address policy use is disabled and no addresses were provided");
            }
            else
            {
                enhancedAttributes = context.Attributes;        // no change
            }

            // prepare the command
            Command cmdEnable = ExchangeUtility.GetCommand(cmdInfoEnable, enhancedAttributes, uid, (ExchangeConfiguration)context.ConnectorConfiguration);
            Command cmdSet    = ExchangeUtility.GetCommand(cmdInfoSet, enhancedAttributes, uid, (ExchangeConfiguration)context.ConnectorConfiguration);

            try {
                _helper.InvokePipeline(exconn, cmdEnable);
                _helper.InvokePipeline(exconn, cmdSet);
            }
            catch {
                LOGGER.TraceEvent(TraceEventType.Information, CAT_DEFAULT, "Rolling back AD create for UID: " + uid.GetUidValue());

                // rollback AD create
                try {
                    adconn.Delete(context.ObjectClass, uid, context.Options);
                } catch {
                    LOGGER.TraceEvent(TraceEventType.Warning, CAT_DEFAULT, "Not able to rollback AD create for UID: " + uid.GetUidValue());
                    // note: this is not perfect, we hide the original exception
                    throw;
                }

                // rethrow original exception
                throw;
            }

            context.Uid = uid;
        }
 public Uid UpdateDeleteAndVerifyUser(ActiveDirectoryConnector connector,
     ICollection<ConnectorAttribute> attributes)
 {
     throw new NotImplementedException();
 }
        public void TestAuthenticateUser()
        {
            //Initialize Connector
            ActiveDirectoryConnector connector = new ActiveDirectoryConnector();
            connector.Init(ConfigHelper.GetConfiguration());
            Uid createUid = null;

            try
            {
                // create user
                ICollection<ConnectorAttribute> createAttributes = GetNormalAttributes_Account();
                // remove password, and set to something memorable
                createAttributes.Remove(ConnectorAttributeUtil.Find(OperationalAttributes.PASSWORD_NAME, createAttributes));
                GuardedString gsCurrentPassword = GetGuardedString("1Password");
                createAttributes.Add(ConnectorAttributeBuilder.BuildPassword(gsCurrentPassword));
                createAttributes.Add(ConnectorAttributeBuilder.BuildEnabled(true));
                createUid = CreateAndVerifyObject(connector,
                    ObjectClass.ACCOUNT, createAttributes);

                // make sure authenticate works here
                Uid authUid = connector.Authenticate(ObjectClass.ACCOUNT,
                    ConnectorAttributeUtil.GetAsStringValue(ConnectorAttributeUtil.Find("sAMAccountName", createAttributes)),
                    gsCurrentPassword, null);

                Assert.AreEqual(createUid, authUid);

                // make sure authenticate fails - wrong password
                bool caughtException = false;
                try
                {
                    connector.Authenticate(ObjectClass.ACCOUNT,
                        ConnectorAttributeUtil.GetAsStringValue(ConnectorAttributeUtil.Find("sAMAccountName", createAttributes)),
                        GetGuardedString("boguspassword"), null);

                }
                catch (InvalidCredentialException e)
                {
                    caughtException = true;
                }
                Assert.IsTrue(caughtException, "Negative test case should throw InvalidCredentialsException");

                // change password
                ICollection<ConnectorAttribute> updateReplaceAttributes =
                    new HashSet<ConnectorAttribute>();
                GuardedString gsNewPassword = GetGuardedString("LongPassword2MeetTheRequirements!");
                updateReplaceAttributes.Add(ConnectorAttributeBuilder.BuildCurrentPassword(gsCurrentPassword));
                updateReplaceAttributes.Add(ConnectorAttributeBuilder.BuildPassword(gsNewPassword));
                UpdateReplaceAndVerifyObject(connector, ObjectClass.ACCOUNT,
                    createUid, updateReplaceAttributes);

                // make sure authenticate works here - new password
                connector.Authenticate(ObjectClass.ACCOUNT,
                    ConnectorAttributeUtil.GetAsStringValue(ConnectorAttributeUtil.Find("sAMAccountName", createAttributes)),
                    gsNewPassword, null);

                // make sure it fails with the wrong password
                caughtException = false;
                try
                {
                    connector.Authenticate(ObjectClass.ACCOUNT,
                        ConnectorAttributeUtil.GetAsStringValue(ConnectorAttributeUtil.Find("sAMAccountName", createAttributes)),
                        GetGuardedString("bogusPassword"), null);
                }
                catch (Exception e)
                {
                    caughtException = true;
                }
                Assert.IsTrue(caughtException, "Negative test case should throw an exception");

                // now set user must change password attribute
                ICollection<ConnectorAttribute> expirePasswordAttrs =
                    new HashSet<ConnectorAttribute>();
                expirePasswordAttrs.Add(ConnectorAttributeBuilder.BuildPasswordExpired(true));
                UpdateReplaceAndVerifyObject(connector, ObjectClass.ACCOUNT,
                    createUid, expirePasswordAttrs);

                // make sure authenticate fails - correct password, but expired
                caughtException = false;
                try
                {
                    // make sure authenticate fails with correct password
                    connector.Authenticate(ObjectClass.ACCOUNT,
                        ConnectorAttributeUtil.GetAsStringValue(ConnectorAttributeUtil.Find("sAMAccountName", createAttributes)),
                        gsNewPassword, null);
                }
                catch (PasswordExpiredException e)
                {
                    caughtException = true;
                    Assert.AreEqual(createUid, e.Uid);
                }
                Assert.IsTrue(caughtException, "Negative test case should throw an exception");

                // make sure authenticate fails - incorrect password, and expired
                caughtException = false;
                try
                {
                    // make sure authenticate fails with wrong password (invalid credentials exception)
                    connector.Authenticate(ObjectClass.ACCOUNT,
                        ConnectorAttributeUtil.GetAsStringValue(ConnectorAttributeUtil.Find("sAMAccountName", createAttributes)),
                        GetGuardedString("bogusPassword"), null);
                }
                catch (InvalidCredentialException e)
                {
                    caughtException = true;
                }
                Assert.IsTrue(caughtException, "Negative test case should throw an exception");
            }
            finally
            {
                if (createUid != null)
                {
                    //remove the one we created
                    DeleteAndVerifyObject(connector, ObjectClass.ACCOUNT,
                        createUid, false, true);
                }
            }
        }
        public Uid UpdateReplaceAndVerifyObject(ActiveDirectoryConnector connector,
            ObjectClass oclass, Uid uid, ICollection<ConnectorAttribute> attributes)
        {
            attributes.Add(uid);
            Filter uidFilter = FilterBuilder.EqualTo(uid);

            // find the object ... can't update if it doesn't exist
            ICollection<ConnectorObject> currentConnectorObjects = TestHelpers.SearchToList(
                connector, oclass, uidFilter);
            Assert.AreEqual(1, currentConnectorObjects.Count);

            Uid updatedUid = connector.Update(UpdateType.REPLACE, oclass,
                attributes, null);

            Assert.IsNotNull(updatedUid);

            uidFilter = FilterBuilder.EqualTo(updatedUid);
            ICollection<ConnectorObject> updatedConnectorObjects = TestHelpers.SearchToList(
                connector, oclass, uidFilter);
            Assert.IsTrue(updatedConnectorObjects.Count == 1);
            VerifyObject(attributes, updatedConnectorObjects.ElementAt(0));
            return updatedUid;
        }
 public Uid CreateAndVerifyObject(ActiveDirectoryConnector connector,
     ObjectClass oclass, ICollection<ConnectorAttribute> attributes)
 {
     // create object
     Uid uid = CreateObject(connector, oclass, attributes);
     VerifyObject(connector, uid, oclass, attributes);
     return uid;
 }
 public void VerifyObject(ActiveDirectoryConnector connector, Uid uid,
     ObjectClass oclass, ICollection<ConnectorAttribute> attributes)
 {
     // verify the object
     VerifyObject(attributes, GetConnectorObjectFromUid(connector, oclass, uid));
 }
        public void TestContainerChange_account()
        {
            ActiveDirectoryConnector connector = new ActiveDirectoryConnector();
            connector.Init(ConfigHelper.GetConfiguration());

            Uid createOuUid = null;
            Uid createUserUid = null;

            try
            {
                // create container for this test
                ICollection<ConnectorAttribute> ouAttributes = GetNormalAttributes_OrganizationalUnit();
                createOuUid = CreateAndVerifyObject(connector,
                    ActiveDirectoryConnector.ouObjectClass, ouAttributes);
                ICollection<ConnectorObject> ouResults = TestHelpers.SearchToList(
                    connector, ActiveDirectoryConnector.ouObjectClass, FilterBuilder.EqualTo(createOuUid));
                Assert.AreEqual(1, ouResults.Count);
                Assert.AreEqual(createOuUid, ouResults.ElementAt(0).Uid);

                // as a reminder, the uid is the dn for non account objects (idm backward compatiblity)
                String ouPath = createOuUid.GetUidValue();

                // create user
                ICollection<ConnectorAttribute> userAttributes = GetNormalAttributes_Account();
                createUserUid = CreateAndVerifyObject(connector,
                    ObjectClass.ACCOUNT, userAttributes);

                //now change user container to the newly created one
                Name createdName = ConnectorAttributeUtil.GetNameFromAttributes(userAttributes);
                String newName = ActiveDirectoryUtils.GetRelativeName(createdName);
                newName += ", " + ouPath;
                ICollection<ConnectorAttribute> updateAttrs = new HashSet<ConnectorAttribute>();
                updateAttrs.Add(new Name(newName));
                updateAttrs.Add(createUserUid);

                connector.Update(UpdateType.REPLACE, ObjectClass.ACCOUNT, updateAttrs, null);

                ICollection<ConnectorObject> results = TestHelpers.SearchToList(
                    connector, ObjectClass.ACCOUNT, FilterBuilder.EqualTo(createUserUid));
                Assert.AreEqual(1, results.Count);
                Assert.AreEqual(createUserUid, results.ElementAt(0).Uid);
                ConnectorAttribute foundContainerAttr = results.ElementAt(0).GetAttributeByName("ad_container");
                Assert.IsNotNull(foundContainerAttr);

                String lhs = ActiveDirectoryUtils.NormalizeLdapString(ouPath);
                String rhs = ActiveDirectoryUtils.NormalizeLdapString(ConnectorAttributeUtil.GetStringValue(foundContainerAttr));
                Assert.AreEqual(lhs, rhs);
            }
            finally
            {
                if (createUserUid != null)
                {
                    //remove the one we created
                    DeleteAndVerifyObject(connector, ObjectClass.ACCOUNT,
                        createUserUid, false, true);
                }

                if (createOuUid != null)
                {
                    //remove the one we created
                    DeleteAndVerifyObject(connector, ActiveDirectoryConnector.ouObjectClass,
                        createOuUid, false, true);
                }
            }
        }
예제 #36
0
        public void Update(UpdateOpContext context)
        {
            ExchangeConnector        exconn = (ExchangeConnector)context.Connector;
            ActiveDirectoryConnector adconn = exconn.ActiveDirectoryConnector;

            // update in AD first
            var filtered = ExchangeUtility.FilterOut(
                context.Attributes,
                PSExchangeConnector.CommandInfo.EnableMailbox,
                PSExchangeConnector.CommandInfo.EnableMailUser,
                PSExchangeConnector.CommandInfo.SetMailbox,
                PSExchangeConnector.CommandInfo.SetMailUser);

            adconn.Update(context.UpdateType, context.ObjectClass, context.Uid, filtered, context.Options);

            // retrieve Exchange-related information about the user
            string          query         = "(objectGUID=" + ActiveDirectoryUtils.ConvertUIDToSearchString(context.Uid) + ")";
            ConnectorObject currentObject = _helper.GetCurrentObject(context, query);
            ICollection <ConnectorAttribute> attributesForReplace = _helper.DetermineNewAttributeValues(context, currentObject);

            attributesForReplace = DeduplicateEmailAddresses(context, attributesForReplace);

            string origRcptType;
            var    newRcptType = _helper.DetermineOrigAndNewAttributeValue(context, currentObject, attributesForReplace, ExchangeConnectorAttributes.AttRecipientType, out origRcptType);

            if (newRcptType == null)
            {
                newRcptType = ExchangeConnectorAttributes.RcptTypeUser;
            }

            string origDatabase;
            var    newDatabase = _helper.DetermineOrigAndNewAttributeValue(context, currentObject, attributesForReplace, ExchangeConnectorAttributes.AttDatabase, out origDatabase);

            // PART 1 - DEALING WITH MailUser CASE

            if (ExchangeConnectorAttributes.RcptTypeMailUser.Equals(newRcptType))
            {
                // disabling Mailbox if needed
                if (ExchangeConnectorAttributes.RcptTypeMailBox.Equals(origRcptType))
                {
                    Command cmdDisable = ExchangeUtility.GetCommand(PSExchangeConnector.CommandInfo.DisableMailbox, attributesForReplace, context.Uid, exconn.Configuration);
                    cmdDisable.Parameters.Add("Confirm", false);
                    _helper.InvokePipeline(exconn, cmdDisable);
                }

                // enabling MailUser if needed
                if (!ExchangeConnectorAttributes.RcptTypeMailUser.Equals(origRcptType))
                {
                    // Enable-MailUser needs the value of ExternalEmailAddress, so we have to get it
                    string origExternalEmailAddress;
                    var    newExternalEmailAddress = _helper.DetermineOrigAndNewAttributeValue(context, currentObject, attributesForReplace, ExchangeConnectorAttributes.AttExternalEmailAddress, out origExternalEmailAddress);

                    if (String.IsNullOrEmpty(newExternalEmailAddress))
                    {
                        throw new InvalidOperationException("Missing ExternalEmailAddress value, which is required for a MailUser");
                    }
                    ExchangeUtility.SetAttValue(ExchangeConnectorAttributes.AttExternalEmailAddress, newExternalEmailAddress, attributesForReplace);

                    // now execute the Enable-MailUser command
                    Command cmdEnable = ExchangeUtility.GetCommand(
                        PSExchangeConnector.CommandInfo.EnableMailUser, attributesForReplace, context.Uid, exconn.Configuration);
                    _helper.InvokePipeline(exconn, cmdEnable);
                }

                // setting MailUser attributes
                Command cmdSet = ExchangeUtility.GetCommand(PSExchangeConnector.CommandInfo.SetMailUser, attributesForReplace, context.Uid, exconn.Configuration);
                _helper.InvokePipeline(exconn, cmdSet);
            }

            // PART 2 - DEALING WITH UserMailbox CASE

            else if (ExchangeConnectorAttributes.RcptTypeMailBox.Equals(newRcptType))
            {
                // enable mailbox if necessary

                // we should execute something like this here:
                // get-user -identity id|?{$_.RecipientType -eq "User"}|enable-mailbox -database "db"
                // unfortunately I was not able to get it working with the pipeline... that's why there are two commands
                // executed :-(
                // alternatively there can be something like:
                // get-user -identity id -RecipientTypeDetails User|enable-mailbox -database "db", but we have then trouble
                // with detecting attempt to change the database attribute
                if (!ExchangeConnectorAttributes.RcptTypeMailBox.Equals(origRcptType))
                {
                    Command cmdEnable = ExchangeUtility.GetCommand(PSExchangeConnector.CommandInfo.EnableMailbox, attributesForReplace, context.Uid, exconn.Configuration);
                    _helper.InvokePipeline(exconn, cmdEnable);
                }
                else
                {
                    // are we trying to update the database?
                    if (newDatabase != null && origDatabase != null && !newDatabase.Equals(origDatabase))
                    {
                        throw new ArgumentException(
                                  context.ConnectorConfiguration.ConnectorMessages.Format(
                                      "ex_not_updatable", "Update of [{0}] attribute is not supported", ExchangeConnectorAttributes.AttDatabase));
                    }
                }

                Command cmdSet = ExchangeUtility.GetCommand(PSExchangeConnector.CommandInfo.SetMailbox, attributesForReplace, context.Uid, exconn.Configuration);
                _helper.InvokePipeline(exconn, cmdSet);
            }

            // PART 3 - DEALING WITH User CASE

            else if (ExchangeConnectorAttributes.RcptTypeUser.Equals(newRcptType))
            {
                if (ExchangeConnectorAttributes.RcptTypeMailBox.Equals(origRcptType))
                {
                    Command cmdDisable = ExchangeUtility.GetCommand(PSExchangeConnector.CommandInfo.DisableMailbox, attributesForReplace, context.Uid, exconn.Configuration);
                    cmdDisable.Parameters.Add("Confirm", false);
                    _helper.InvokePipeline(exconn, cmdDisable);
                }
                else if (ExchangeConnectorAttributes.RcptTypeMailUser.Equals(origRcptType))
                {
                    Command cmdDisable = ExchangeUtility.GetCommand(PSExchangeConnector.CommandInfo.DisableMailUser, attributesForReplace, context.Uid, exconn.Configuration);
                    cmdDisable.Parameters.Add("Confirm", false);
                    _helper.InvokePipeline(exconn, cmdDisable);
                }
                else if (ExchangeConnectorAttributes.RcptTypeUser.Equals(origRcptType))
                {
                    // if orig is User, there is no need to disable anything
                }
                else
                {
                    throw new InvalidOperationException("Invalid original recipient type: " + origRcptType);
                }

                Command cmdSet = ExchangeUtility.GetCommand(PSExchangeConnector.CommandInfo.SetUser, attributesForReplace, context.Uid, exconn.Configuration);
                _helper.InvokePipeline(exconn, cmdSet);
            }
            else
            {
                // unsupported rcpt type
                throw new ArgumentException(
                          context.ConnectorConfiguration.ConnectorMessages.Format(
                              "ex_bad_rcpt", "Recipient type [{0}] is not supported", newRcptType));
            }
        }
 public ConnectorObject GetConnectorObjectFromUid(
     ActiveDirectoryConnector connector, ObjectClass oclass, Uid uid)
 {
     return GetConnectorObjectFromUid(connector, oclass, uid, null);
 }
 public ConnectorObject GetConnectorObjectFromUid(
     ActiveDirectoryConnector connector, ObjectClass oclass, Uid uid,
     OperationOptions options)
 {
     // get sid to check permissions
     Filter uidFilter = FilterBuilder.EqualTo(uid);
     ICollection<ConnectorObject> objects = TestHelpers.SearchToList(connector,
         oclass, uidFilter, options);
     Assert.AreEqual(1, objects.Count);
     return objects.ElementAt(0);
 }
        public void TestSearchByCNWithWildcard_account()
        {
            ActiveDirectoryConnector connector = new ActiveDirectoryConnector();
            connector.Init(ConfigHelper.GetConfiguration());

            Uid uid1 = null;
            Uid uid2 = null;

            try
            {
                // create a couple things to find
                uid1 = CreateAndVerifyObject(connector, ObjectClass.ACCOUNT,
                    GetNormalAttributes_Account());
                uid2 = CreateAndVerifyObject(connector, ObjectClass.ACCOUNT,
                    GetNormalAttributes_Account());

                ICollection<ConnectorObject> results = TestHelpers.SearchToList(connector,
                    ObjectClass.ACCOUNT, FilterBuilder.EqualTo(
                    ConnectorAttributeBuilder.Build("CN", "nunit*")));

                // there should be at least the two we just created
                Assert.GreaterOrEqual(results.Count, 2);
                foreach (ConnectorObject co in results)
                {
                    // and it must have the value we were searching for
                    String foundName = ActiveDirectoryUtils.NormalizeLdapString(
                        co.Name.GetNameValue());
                    Assert.That(foundName.ToUpper().StartsWith("CN=NUNIT"));
                }
            }
            finally
            {
                if (uid1 != null)
                {
                    //remove the one we created
                    DeleteAndVerifyObject(connector, ObjectClass.ACCOUNT,
                        uid1, false, true);
                }
                if (uid2 != null)
                {
                    //remove the one we created
                    DeleteAndVerifyObject(connector, ObjectClass.ACCOUNT,
                        uid2, false, true);
                }
            }
        }
        public ICollection<String> GetDefaultAttributesToGet(ObjectClass oclass)
        {
            ICollection<string> attributesToGet = new HashSet<String>();

            ActiveDirectoryConnector connector = new ActiveDirectoryConnector();
            connector.Init(ConfigHelper.GetConfiguration());
            Schema schema = connector.Schema();
            ObjectClassInfo ocInfo = schema.FindObjectClassInfo(oclass.GetObjectClassValue());
            Assert.IsNotNull(ocInfo);

            foreach (ConnectorAttributeInfo caInfo in ocInfo.ConnectorAttributeInfos)
            {
                if (caInfo.IsReturnedByDefault)
                {
                    attributesToGet.Add(caInfo.Name);
                }
            }

            return attributesToGet;
        }
        public void TestScriptOnResource()
        {
            //Initialize Connector
            ActiveDirectoryConnector connector = new ActiveDirectoryConnector();
            connector.Init(ConfigHelper.GetConfiguration());

            try
            {
                RunScript(connector, "", "", "");
                RunScript(connector, GetProperty(ConfigHelper.CONFIG_PROPERTY_SCRIPT_USER_LOCAL),
                    GetProperty(ConfigHelper.CONFIG_PROPERTY_SCRIPT_PASSWORD_LOCAL), "");
                RunScript(connector, GetProperty(ConfigHelper.CONFIG_PROPERTY_SCRIPT_USER_DOMAIN),
                    GetProperty(ConfigHelper.CONFIG_PROPERTY_SCRIPT_PASSWORD_DOMAIN), "");

                // now try one with the prefix set
                ActiveDirectoryConfiguration prefixConfig = (ActiveDirectoryConfiguration)ConfigHelper.GetConfiguration();
                string prefix = "UnitTest_";
                connector.Dispose();
                connector.Init(prefixConfig);
                RunScript(connector, "", "", prefix);

                // try with invalid credentials
                bool scriptFailed = false;
                try
                {
                    RunScript(connector, GetProperty(ConfigHelper.CONFIG_PROPERTY_USER), "bogus", "");
                }
                catch (Exception e)
                {
                    scriptFailed = true;
                }
                Assert.That(scriptFailed);
            }
            finally
            {
            }
        }
        public void RunScript(ActiveDirectoryConnector connector, String user,
            string password, string prefix)
        {
            string tempFileName = Path.GetTempFileName();
            String arg0Name = "ARG0";
            String arg1Name = "ARG1";

            string scriptText = String.Format(
                "echo %{0}%:%{1}%:%USERNAME%:%PASSWORD% > \"{2}\"", prefix + arg0Name,
                prefix + arg1Name, tempFileName);

            IDictionary<string, object> arguments = new Dictionary<string, object>();
            string arg0 = "argument_zero";
            string arg1 = "argument one";
            arguments.Add(arg0Name, arg0);
            arguments.Add(arg1Name, arg1);

            OperationOptionsBuilder builder = new OperationOptionsBuilder();
            if (user.Length > 0)
            {
                builder.RunAsUser = user;
            }
            if (password.Length > 0)
            {
                builder.RunWithPassword = GetGuardedString(password);
            }
            builder.Options["variablePrefix"] = prefix;

            ScriptContext context = new ScriptContext("Shell", scriptText, arguments);
            object resultObject = connector.RunScriptOnResource(context, builder.Build());
            Assert.IsNotNull(resultObject);
            Assert.That(resultObject is int);
            Assert.AreEqual(0, resultObject);
            FileStream outputFs = new FileStream(tempFileName, FileMode.Open, FileAccess.Read);
            StreamReader outputReader = new StreamReader(outputFs);
            // read the first line
            string output = outputReader.ReadLine();
            string[] returnedArray = output.Split(':');
            Assert.AreEqual(4, returnedArray.Length);
            Assert.AreEqual((arg0), returnedArray[0]);
            Assert.AreEqual((arg1), returnedArray[1]);
        }
        public void TestSchema()
        {
            ActiveDirectoryConnector connector = new ActiveDirectoryConnector();
            connector.Init(ConfigHelper.GetConfiguration());
            Schema schema = connector.Schema();
            Boolean foundOptionalAttributes = false;
            Boolean foundOperationalAttributes = false;

            // just a very high level check of things.  Should have 3 ObjectClassInfos,
            // (group, account, and organizationalUnit) and nothing contained in them
            // should be null.  Group and account should have some operational
            // attributes
            Assert.AreEqual(3, schema.ObjectClassInfo.Count);
            foreach (ObjectClassInfo ocInfo in schema.ObjectClassInfo)
            {
                Assert.IsNotNull(ocInfo);
                Assert.That((ocInfo.ObjectType == ObjectClass.ACCOUNT.GetObjectClassValue())
                    || (ocInfo.ObjectType == ActiveDirectoryConnector.OBJECTCLASS_GROUP)
                    || (ocInfo.ObjectType == ActiveDirectoryConnector.OBJECTCLASS_OU));
                Trace.WriteLine("****** " + ocInfo.ObjectType);

                // skip this for organizational unit ... it doesnt really have this
                if (ocInfo.ObjectType.Equals(ActiveDirectoryConnector.ouObjectClass))
                {
                    continue;
                }

                foreach (ConnectorAttributeInfo caInfo in ocInfo.ConnectorAttributeInfos)
                {
                    Assert.IsNotNull(caInfo);
                    Trace.WriteLine(String.Format("{0} {1} {2} {3}", caInfo.Name,
                        caInfo.IsCreatable ? "createable" : "",
                        caInfo.IsUpdateable ? "updateable" : "",
                        caInfo.IsRequired ? "required" : "",
                        caInfo.IsMultiValued ? "multivalue" : ""));
                    if (ConnectorAttributeUtil.IsSpecial(caInfo))
                    {
                        foundOperationalAttributes = true;
                    }
                    else
                    {
                        if (!caInfo.IsRequired)
                        {
                            foundOptionalAttributes = true;
                        }
                    }
                }
                Assert.That(foundOperationalAttributes && foundOptionalAttributes);
            }
        }
        public void TestAccountLocked()
        {
            //Initialize Connector
            ActiveDirectoryConnector connector = new ActiveDirectoryConnector();
            connector.Init(ConfigHelper.GetConfiguration());
            Uid createUid = null;

            try
            {
                // create user
                ICollection<ConnectorAttribute> createAttributes = GetNormalAttributes_Account();
                // remove password, and set to something memorable
                createAttributes.Remove(ConnectorAttributeUtil.Find(OperationalAttributes.PASSWORD_NAME, createAttributes));
                GuardedString gsCurrentPassword = GetGuardedString("1Password");
                createAttributes.Add(ConnectorAttributeBuilder.BuildPassword(gsCurrentPassword));
                createAttributes.Add(ConnectorAttributeBuilder.BuildEnabled(true));
                createUid = CreateAndVerifyObject(connector,
                    ObjectClass.ACCOUNT, createAttributes);

                // make sure authenticate works here
                connector.Authenticate(ObjectClass.ACCOUNT,
                    ConnectorAttributeUtil.GetAsStringValue(ConnectorAttributeUtil.Find("sAMAccountName", createAttributes)),
                    gsCurrentPassword, null);

                // not allowed to lock ... only unlock, so test unlock
                // setting on machine must lockout user after 3 unsuccessful
                // attempst for this to work.
                // lock out by having unsucessful attempts.
                try
                {
                    connector.Authenticate(ObjectClass.ACCOUNT,
                        ConnectorAttributeUtil.GetAsStringValue(ConnectorAttributeUtil.Find("sAMAccountName", createAttributes)),
                        GetGuardedString("bogusPassword"), null);
                }
                catch (Exception e)
                {
                }

                try
                {
                    connector.Authenticate(ObjectClass.ACCOUNT,
                        ConnectorAttributeUtil.GetAsStringValue(ConnectorAttributeUtil.Find("sAMAccountName", createAttributes)),
                        GetGuardedString("bogusPassword"), null);
                }
                catch (Exception e)
                {
                }

                try
                {
                    connector.Authenticate(ObjectClass.ACCOUNT,
                        ConnectorAttributeUtil.GetAsStringValue(ConnectorAttributeUtil.Find("sAMAccountName", createAttributes)),
                        GetGuardedString("bogusPassword"), null);
                }
                catch (Exception e)
                {
                }

                bool exceptionCaught = false;
                try
                {
                    connector.Authenticate(ObjectClass.ACCOUNT,
                        ConnectorAttributeUtil.GetAsStringValue(ConnectorAttributeUtil.Find("sAMAccountName", createAttributes)),
                        gsCurrentPassword, null);
                }
                catch (Exception e)
                {
                    exceptionCaught = true;
                }
                Assert.IsTrue(exceptionCaught, "Account not locked.  Make sure that the server is setup for account lockout after 3 attempts");

                ICollection<ConnectorAttribute> unlockAttrs =
                    new HashSet<ConnectorAttribute>();
                unlockAttrs.Add(
                    ConnectorAttributeBuilder.BuildLockOut(false));
                UpdateReplaceAndVerifyObject(connector, ObjectClass.ACCOUNT,
                    createUid, unlockAttrs);

                // make sure succeeds
                connector.Authenticate(ObjectClass.ACCOUNT,
                    ConnectorAttributeUtil.GetAsStringValue(ConnectorAttributeUtil.Find("sAMAccountName", createAttributes)),
                    gsCurrentPassword, null);

                // now try to write lockout.   Should get connector exception
                bool connectorExceptionCaught = false;
                try
                {
                    ICollection<ConnectorAttribute> lockAttrs =
                        new HashSet<ConnectorAttribute>();
                    lockAttrs.Add(
                        ConnectorAttributeBuilder.BuildLockOut(true));
                    UpdateReplaceAndVerifyObject(connector, ObjectClass.ACCOUNT,
                        createUid, lockAttrs);

                }
                catch (ConnectorException e)
                {
                    connectorExceptionCaught = true;
                }
                Assert.IsTrue(connectorExceptionCaught);
            }
            finally
            {
                if (createUid != null)
                {
                    //remove the one we created
                    DeleteAndVerifyObject(connector, ObjectClass.ACCOUNT,
                        createUid, false, true);
                }
            }
        }
예제 #45
0
        public void ExecuteQuery(ExecuteQueryContext context)
        {
            ExchangeConnector        exconn = (ExchangeConnector)context.Connector;
            ActiveDirectoryConnector adconn = exconn.ActiveDirectoryConnector;

            ICollection <string> attsToGet = null;

            if (context.Options != null && context.Options.AttributesToGet != null)
            {
                attsToGet = CollectionUtil.NewList(context.Options.AttributesToGet);
            }

            // delegate to get the exchange attributes if requested
            ResultsHandler filter = new SearchResultsHandler()
            {
                Handle = cobject =>
                {
                    LOGGER.TraceEvent(TraceEventType.Verbose, CAT_DEFAULT, "Object returned from AD connector: {0}", CommonUtils.DumpConnectorAttributes(cobject.GetAttributes()));
                    ConnectorObject filtered = ExchangeUtility.ConvertAdAttributesToExchange(cobject);
                    //filtered = AddExchangeAttributes(exconn, context.ObjectClass, filtered, attsToGet);
                    LOGGER.TraceEvent(TraceEventType.Verbose, CAT_DEFAULT, "Object as passed from Exchange connector: {0}", CommonUtils.DumpConnectorAttributes(filtered.GetAttributes()));
                    return(context.ResultsHandler.Handle(filtered));
                },

                HandleResult = result =>
                {
                    if (context.ResultsHandler is SearchResultsHandler)
                    {
                        ((SearchResultsHandler)context.ResultsHandler).HandleResult(result);
                    }
                }
            };

            ResultsHandler   handler2use = filter;
            OperationOptions options2use = context.Options;

            // mapping AttributesToGet from Exchange to AD "language"
            // actually, we don't need this code any more, because there are no attribute that are not retrieved by default
            // Uncomment this code if necessary in the future.
            if (context.Options != null && context.Options.AttributesToGet != null)
            {
                /*
                 * ISet<string> mappedExchangeAttributesToGet = new HashSet<string>(AttMap2AD.Keys);
                 * mappedExchangeAttributesToGet.IntersectWith(options.AttributesToGet);
                 * if (mappedExchangeAttributesToGet.Count > 0 || attsToGet.Contains(AttRecipientType))
                 * {
                 *  // replace Exchange attributes with AD names
                 *  var newAttsToGet = ExchangeUtility.FilterReplace(attsToGet, AttMap2AD);
                 *
                 *  // we have to remove recipient type, as it is unknown to AD
                 *  newAttsToGet.Remove(AttRecipientType);
                 *
                 *  // build new op options
                 *  var builder = new OperationOptionsBuilder(options);
                 *  string[] attributesToGet = new string[newAttsToGet.Count];
                 *  newAttsToGet.CopyTo(attributesToGet, 0);
                 *  builder.AttributesToGet = attributesToGet;
                 *  options2use = builder.Build();
                 * } */

                /*
                 * if (attsToGet.Contains(ExchangeConnectorAttributes.AttDatabase))
                 * {
                 *  attsToGet.Remove(ExchangeConnectorAttributes.AttDatabase);
                 *
                 *  // build new op options
                 *  var builder = new OperationOptionsBuilder(context.Options);
                 *  string[] attributesToGet = new string[attsToGet.Count];
                 *  attsToGet.CopyTo(attributesToGet, 0);
                 *  builder.AttributesToGet = attributesToGet;
                 *  options2use = builder.Build();
                 * }
                 */
            }

            adconn.ExecuteQueryInternal(context.ObjectClass,
                                        context.Query, handler2use, options2use,
                                        GetAdAttributesToReturn(adconn, context.ObjectClass, context.Options));
        }
        public void TestAddGroup_Account()
        {
            //Initialize Connector
            ActiveDirectoryConnector connector = new ActiveDirectoryConnector();
            connector.Init(ConfigHelper.GetConfiguration());
            Uid groupUid = null;
            Uid userUid = null;
            try
            {
                userUid = CreateAndVerifyObject(connector,
                    ObjectClass.ACCOUNT, GetNormalAttributes_Account());
                Filter userUidFilter = FilterBuilder.EqualTo(userUid);
                IList<ConnectorObject> foundUserObjects =
                    TestHelpers.SearchToList(connector, ObjectClass.ACCOUNT, userUidFilter);
                Assert.AreEqual(1, foundUserObjects.Count);

                groupUid = CreateAndVerifyObject(connector,
                    ActiveDirectoryConnector.groupObjectClass, GetNormalAttributes_Group());
                Filter groupUidFilter = FilterBuilder.EqualTo(groupUid);
                IList<ConnectorObject> foundGroupObjects =
                    TestHelpers.SearchToList(connector, ActiveDirectoryConnector.groupObjectClass, groupUidFilter);
                Assert.AreEqual(1, foundGroupObjects.Count);
                String groupName = foundGroupObjects[0].Name.GetNameValue();

                ICollection<ConnectorAttribute> modifiedAttrs = new HashSet<ConnectorAttribute>();
                modifiedAttrs.Add(ConnectorAttributeBuilder.Build(PredefinedAttributes.GROUPS_NAME, groupName));
                OperationOptionsBuilder optionsBuilder = new OperationOptionsBuilder();
                ICollection<String> attributesToGet = GetDefaultAttributesToGet(ObjectClass.ACCOUNT);
                attributesToGet.Add(PredefinedAttributes.GROUPS_NAME);
                optionsBuilder.AttributesToGet = attributesToGet.ToArray();
                UpdateAddAndVerifyUser(connector, ObjectClass.ACCOUNT,
                    userUid, modifiedAttrs, optionsBuilder.Build());

            }
            finally
            {
                DeleteAndVerifyObject(connector, ObjectClass.ACCOUNT, userUid, false, false);
                DeleteAndVerifyObject(connector, ActiveDirectoryConnector.groupObjectClass, groupUid, false, false);
            }
        }
        private void RenameObjectAndVerify(ActiveDirectoryConnector connector, ObjectClass oc, ICollection<ConnectorAttribute> createAttributes)
        {
            Uid createdUid = null;
            Uid updatedUid = null;
            try
            {
                // create the objec
                createdUid = CreateAndVerifyObject(connector, oc, createAttributes);

                // update the name of the object
                var oldName = ConnectorAttributeUtil.GetNameFromAttributes(createAttributes);
                var newName = ActiveDirectoryUtils.GetRelativeName(oldName);
                newName = newName.Trim() + "_new, " + GetProperty(ConfigHelper.CONFIG_PROPERTY_CONTAINER);

                updatedUid = UpdateReplaceAndVerifyObject(connector, oc, createdUid,
                                                          new List<ConnectorAttribute>() { ConnectorAttributeBuilder.Build(Name.NAME, newName) });

                if (oc.Equals(ObjectClass.ACCOUNT))
                {
                    Assert.AreEqual(createdUid, updatedUid, "The Uid of an object of type ACCOUNT must not change.");
                }

                // test if the original object exists
                var nameFilter = FilterBuilder.EqualTo(ConnectorAttributeBuilder.Build(Name.NAME, oldName.Value));
                var optionsBuilder = new OperationOptionsBuilder()
                {
                    AttributesToGet = new[] { Name.NAME }
                };
                var originalObjects = TestHelpers.SearchToList(connector, oc, nameFilter, optionsBuilder.Build());
                Assert.AreEqual(0, originalObjects.Count,
                                string.Format(System.Globalization.CultureInfo.InvariantCulture,
                                              "An object of type '{0}' with the original name exists.", oc));
            }
            finally
            {
                if (createdUid != null)
                {
                    DeleteAndVerifyObject(connector, oc, createdUid, false, false);
                }

                //make sure that the updated object is deleted as well
                if (updatedUid != null)
                {
                    DeleteAndVerifyObject(connector, oc, updatedUid, false, false);
                }
            }
        }
        public void TestSearchByRegularAttribute_account()
        {
            ActiveDirectoryConnector connector = new ActiveDirectoryConnector();
            connector.Init(ConfigHelper.GetConfiguration());

            Uid createUid = null;

            try
            {
                ConnectorAttribute createSnAttr =
                    ConnectorAttributeBuilder.Build("sn", "nunitSearch");
                ICollection<ConnectorAttribute> attributes = GetNormalAttributes_Account();
                attributes.Remove(ConnectorAttributeUtil.Find("sn", attributes));
                attributes.Add(createSnAttr);
                createUid = CreateAndVerifyObject(connector, ObjectClass.ACCOUNT,
                    attributes);

                ICollection<ConnectorObject> results = TestHelpers.SearchToList(connector,
                    ObjectClass.ACCOUNT, FilterBuilder.EqualTo(createSnAttr));

                // there should be at least the newly created one
                Assert.GreaterOrEqual(results.Count, 1);

                // and it must have the value we were searching for
                Boolean foundCreated = false;
                foreach (ConnectorObject resultObject in results)
                {
                    ConnectorAttribute foundSnAttr =
                        resultObject.GetAttributeByName("sn");
                    Assert.AreEqual(createSnAttr, foundSnAttr);

                    // keep track of if we've found the one we created
                    if (createUid.Equals(resultObject.Uid))
                    {
                        // cant have it twice
                        Assert.IsFalse(foundCreated);
                        foundCreated = true;
                    }
                }
                // be certain we saw the one we created
                Assert.IsTrue(foundCreated);
            }
            finally
            {
                if (createUid != null)
                {
                    //remove the one we created
                    DeleteAndVerifyObject(connector, ObjectClass.ACCOUNT,
                        createUid, false, true);
                }
            }
        }