Builder for OperationOptions.
        public void TestSearchByteAttributes()
        {
            OperationOptionsBuilder builder = new OperationOptionsBuilder();
            builder.AttributesToGet = new[] { "attributeByte", "attributeByteMultivalue", "attributeByteArray", "attributeByteArrayMultivalue" };
            var co = GetFacade().GetObject(Test, new Uid("UID01"), builder.Build());
            Assert.IsNotNull(co);

            IList<Object> value = co.GetAttributeByName("attributeByte").Value;
            Assert.AreEqual(1, value.Count);
            Assert.IsInstanceOf(typeof(byte), value[0]);

            value = co.GetAttributeByName("attributeByteMultivalue").Value;
            Assert.AreEqual(2, value.Count);
            Assert.IsInstanceOf(typeof(byte), value[0]);
            Assert.IsInstanceOf(typeof(byte), value[1]);

            value = co.GetAttributeByName("attributeByteArray").Value;
            Assert.AreEqual(1, value.Count);
            Assert.IsInstanceOf(typeof(byte[]), value[0]);

            value = co.GetAttributeByName("attributeByteArrayMultivalue").Value;
            Assert.AreEqual(2, value.Count);
            Assert.IsInstanceOf(typeof(byte[]), value[0]);
            Assert.IsInstanceOf(typeof(byte[]), value[1]);
        }
        public virtual void TestSearch2()
        {
            ConnectorFacade search = GetFacade();
            for (int i = 0; i < 100; i++)
            {
                ICollection<ConnectorAttribute> co = GetTestCreateConnectorObject(string.Format("TEST{0:D5}", i));
                co.Add(ConnectorAttributeBuilder.Build("sortKey", i));
                search.Create(ObjectClass.ACCOUNT, co, null);
            }

            OperationOptionsBuilder builder = new OperationOptionsBuilder { PageSize = 10, SortKeys = new[] { new SortKey("sortKey", false) } };
            SearchResult result = null;

            ICollection<ConnectorObject> resultSet = new HashSet<ConnectorObject>();
            int pageIndex = 0;
            int index = 101;

            while ((result = search.Search(ObjectClass.ACCOUNT, FilterBuilder.StartsWith(ConnectorAttributeBuilder.Build(Name.NAME, "TEST")), new ResultsHandler()
            {
                Handle = connectorObject =>
                {
                    int? idx = ConnectorAttributeUtil.GetIntegerValue(connectorObject.GetAttributeByName("sortKey"));
                    Assert.IsTrue(idx < index);
                    if (idx != null) { index = (int)idx; }
                    resultSet.Add(connectorObject);
                    return true;
                }
            }, builder.Build())).PagedResultsCookie != null)
            {

                builder = new OperationOptionsBuilder(builder.Build()) { PagedResultsCookie = result.PagedResultsCookie };
                Assert.AreEqual(10 * ++pageIndex, resultSet.Count);
            }
            Assert.AreEqual(9, pageIndex);
            Assert.AreEqual(100, resultSet.Count);
        }
 public void TestSearchAttributes()
 {
     OperationOptionsBuilder builder = new OperationOptionsBuilder();
     builder.AttributesToGet = new[] { "attributeString", "attributeMap"};
     GetFacade().Search(Test, null, new ResultsHandler
     {
         Handle = connectorObject =>
         {
             Assert.AreEqual(4, connectorObject.GetAttributes().Count);
             return true;
         }
     }, builder.Build());
 }
 public void TestCreateTestRunAs()
 {
     ICollection<ConnectorAttribute> createAttributes = GetTestCreateConnectorObject("TEST5");
     var builder = new OperationOptionsBuilder();
     builder.RunAsUser = "******";
     builder.RunWithPassword = new GuardedString(GetSecure(Password));
     Uid uid = GetFacade().Create(Test, createAttributes, builder.Build());
     Assert.AreEqual(uid.GetUidValue(), "TEST5");
 }
 public void TestCreateTestRunAsFailed()
 {
     ICollection<ConnectorAttribute> createAttributes = GetTestCreateConnectorObject("TEST5");
     var builder = new OperationOptionsBuilder();
     builder.RunAsUser = "******";
     var secret = new SecureString();
     "__FAKE__".ToCharArray().ToList().ForEach(secret.AppendChar);
     builder.RunWithPassword = new GuardedString(secret);
     Uid uid = GetFacade().Create(Test, createAttributes, builder.Build());
     Assert.AreEqual(uid.GetUidValue(), "TEST5");
 }
        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);
                }
            }
        }
        /// <summary>
        /// Builds new Operation options and add the specified attribute names as 
        /// AttributesToGet (add to existing AttributesToGet)
        /// </summary>
        /// <param name="options">Existing Operation Options</param>
        /// <param name="attNames">attribute names to be add to AttributeToGet</param>
        /// <returns>New Operation Options</returns>
        internal static OperationOptions AddAttributeToOptions(OperationOptions options, params string[] attNames)
        {
            OperationOptionsBuilder optionsBuilder = new OperationOptionsBuilder(options);
            List<string> attsToGet = new List<string>();
            if (options.AttributesToGet != null)
            {
                attsToGet.AddRange(options.AttributesToGet);
            }

            foreach (string attName in attNames)
            {
                attsToGet.Add(attName);
            }

            optionsBuilder.AttributesToGet = attsToGet.ToArray();
            return optionsBuilder.Build();
        }
        public void TestPagedSearch()
        {
            ConnectorPoolManager.Dispose();
            ConnectorInfoManager manager = GetConnectorInfoManager();
            ConnectorInfo info1 = FindConnectorInfo(manager, "1.0.0.0", "org.identityconnectors.testconnector.TstStatefulPoolableConnector");
            Assert.IsNotNull(info1);

            APIConfiguration config = info1.CreateDefaultAPIConfiguration();
            config.ProducerBufferSize = 0;

            config.ConnectorPoolConfiguration.MinIdle = 1;
            config.ConnectorPoolConfiguration.MaxIdle = 2;
            config.ResultsHandlerConfiguration.FilteredResultsHandlerInValidationMode = true;           // for paged searches, the filtered results handler should be either disabled or put into validation mode

            ConnectorFacade facade1 = ConnectorFacadeFactory.GetInstance().NewInstance(config);

            OperationOptionsBuilder builder = new OperationOptionsBuilder();
            builder.PageSize = 10;
            builder.SetSortKeys(new ICF.SortKey(Name.NAME, true));

            SearchResult searchResult = null;
            ISet<Uid> UIDs = new HashSet<Uid>();

            int iteration = 0;
            do
            {

                if (null != searchResult)
                {
                    builder.PagedResultsCookie = searchResult.PagedResultsCookie;
                }

                int size = 0;
                searchResult = facade1.Search(ObjectClass.ACCOUNT, null, new ResultsHandler()
                {

                    Handle = obj =>
                    {
                        if (size >= 10)
                        {
                            Assert.Fail("More then 10 objects was handled!");
                        }
                        size++;
                        if (UIDs.Contains(obj.Uid))
                        {
                            Assert.Fail("Duplicate Entry in results");
                        }
                        return UIDs.Add(obj.Uid);
                    }
                }, builder.Build());
                iteration++;
                Assert.IsNotNull(searchResult);
                Assert.AreEqual(searchResult.RemainingPagedResults, 100 - (iteration * 10));

            } while (searchResult.PagedResultsCookie != null);

            // Search with paged results offset

            builder = new OperationOptionsBuilder();
            builder.PageSize = 10;
            builder.PagedResultsOffset = 5;
            builder.SetSortKeys(new ICF.SortKey(Name.NAME, true));

            searchResult = null;

            UIDs.Clear();
            Filter filter = FilterBuilder.EqualTo(ConnectorAttributeBuilder.BuildEnabled(true));

            iteration = 0;
            do
            {

                if (null != searchResult)
                {
                    builder.PagedResultsCookie = searchResult.PagedResultsCookie;
                }

                int size = 0;
                searchResult = facade1.Search(ObjectClass.ACCOUNT, filter, new ResultsHandler()
                {
                    Handle = obj =>
                    {
                        if (size >= 10)
                        {
                            Assert.Fail("More then 10 objects was handled!");
                        }
                        size++;
                        if (UIDs.Contains(obj.Uid))
                        {
                            Assert.Fail("Duplicate Entry in results");
                        }
                        return UIDs.Add(obj.Uid);
                    }
                }, builder.Build());
                iteration++;
                Assert.IsNotNull(searchResult);
                Assert.AreEqual(searchResult.RemainingPagedResults, Math.Max(50 - (iteration * 15), 0));

            } while (searchResult.PagedResultsCookie != null);
        }
        public void TestTimeout()
        {
            ConnectorInfoManager manager = GetConnectorInfoManager();
            ConnectorInfo info1 = FindConnectorInfo(manager, "1.0.0.0", "org.identityconnectors.testconnector.TstConnector");
            Assert.IsNotNull(info1);

            APIConfiguration config = info1.CreateDefaultAPIConfiguration();
            config.SetTimeout(SafeType<APIOperation>.ForRawType(typeof(CreateApiOp)), 5000);
            config.SetTimeout(SafeType<APIOperation>.ForRawType(typeof(SearchApiOp)), 5000);
            ConfigurationProperties props = config.ConfigurationProperties;
            ConfigurationProperty property = props.GetProperty("numResults");
            // 1000 is several times the remote size between pauses
            property.Value = 2;
            OperationOptionsBuilder opBuilder = new OperationOptionsBuilder();
            opBuilder.SetOption("delay", 10000);

            ConnectorFacade facade1 = ConnectorFacadeFactory.GetInstance().NewInstance(config);

            ICollection<ConnectorAttribute> attrs = CollectionUtil.NewReadOnlySet<ConnectorAttribute>();
            try
            {
                facade1.Create(ObjectClass.ACCOUNT, attrs, opBuilder.Build()).GetUidValue();
                Assert.Fail("expected timeout");
            }
            catch (OperationTimeoutException)
            {
                // expected
            }
            //catch (RemoteWrappedException e)
            //{
            //    Assert.IsTrue(e.Is(typeof(OperationTimeoutException)));
            //}

            try
            {
                facade1.Search(ObjectClass.ACCOUNT, null, new ResultsHandler()
                {
                    Handle = obj =>
                    {
                        return true;
                    }
                }, opBuilder.Build());
                Assert.Fail("expected timeout");
            }
            catch (OperationTimeoutException)
            {
                // expected
            }
            //catch (RemoteWrappedException e)
            //{
            //    Assert.IsTrue(e.Is(typeof(OperationTimeoutException)));
            //}
        }
        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);
                }
            }
        }
示例#11
0
        public void TestConnectionPooling()
        {
            ConnectorPoolManager.Dispose();
            ConnectorInfoManager manager =
                GetConnectorInfoManager();
            ConnectorInfo info1 =
                FindConnectorInfo(manager,
                                  "1.0.0.0",
                                  "org.identityconnectors.testconnector.TstConnector");
            Assert.IsNotNull(info1);
            //reset connection count
            {
                //trigger TstConnection.init to be called
                APIConfiguration config2 =
                    info1.CreateDefaultAPIConfiguration();
                config2.ConfigurationProperties.GetProperty("resetConnectionCount").Value = (true);
                ConnectorFacade facade2 =
                    ConnectorFacadeFactory.GetInstance().NewInstance(config2);
                facade2.Schema(); //force instantiation
            }

            APIConfiguration config =
                info1.CreateDefaultAPIConfiguration();

            config.ConnectorPoolConfiguration.MinIdle = (0);
            config.ConnectorPoolConfiguration.MaxIdle = (0);

            ConnectorFacade facade1 =
                ConnectorFacadeFactory.GetInstance().NewInstance(config);

            OperationOptionsBuilder builder = new OperationOptionsBuilder();
            builder.SetOption("testPooling", "true");
            OperationOptions options = builder.Build();
            ICollection<ConnectorAttribute> attrs = CollectionUtil.NewReadOnlySet<ConnectorAttribute>();
            Assert.AreEqual("1", facade1.Create(ObjectClass.ACCOUNT, attrs, options).GetUidValue());
            Assert.AreEqual("2", facade1.Create(ObjectClass.ACCOUNT, attrs, options).GetUidValue());
            Assert.AreEqual("3", facade1.Create(ObjectClass.ACCOUNT, attrs, options).GetUidValue());
            Assert.AreEqual("4", facade1.Create(ObjectClass.ACCOUNT, attrs, options).GetUidValue());
            config =
                info1.CreateDefaultAPIConfiguration();
            config.ConnectorPoolConfiguration.MinIdle = (1);
            config.ConnectorPoolConfiguration.MaxIdle = (2);
            facade1 =
                ConnectorFacadeFactory.GetInstance().NewInstance(config);
            Assert.AreEqual("5", facade1.Create(ObjectClass.ACCOUNT, attrs, options).GetUidValue());
            Assert.AreEqual("5", facade1.Create(ObjectClass.ACCOUNT, attrs, options).GetUidValue());
            Assert.AreEqual("5", facade1.Create(ObjectClass.ACCOUNT, attrs, options).GetUidValue());
            Assert.AreEqual("5", facade1.Create(ObjectClass.ACCOUNT, attrs, options).GetUidValue());
        }
        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);
            }
        }
        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]);
        }
        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);
                }
            }
        }
示例#15
0
 public void TestOperationOptions()
 {
     OperationOptionsBuilder builder = new OperationOptionsBuilder();
     builder.SetOption("foo", "bar");
     builder.SetOption("foo2", "bar2");
     OperationOptions v1 = builder.Build();
     OperationOptions v2 = (OperationOptions)CloneObject(v1);
     Assert.AreEqual(2, v2.Options.Count);
     Assert.AreEqual("bar", v2.Options["foo"]);
     Assert.AreEqual("bar2", v2.Options["foo2"]);
 }
        public void TestNullOperations()
        {
            IAsyncConnectorInfoManager manager = ConnectorInfoManager;
            var task = manager.FindConnectorInfoAsync(TestStatefulConnectorKey);
            Assert.IsTrue(task.Wait(TimeSpan.FromMinutes(5)));

            ConnectorFacade facade = GetConnectorFacade(true, true);
            OperationOptionsBuilder optionsBuilder = new OperationOptionsBuilder();
            facade.Test();
            Assert.IsNull(facade.Schema());

            var guardedString = new GuardedString();
            "Passw0rd".ToCharArray().ToList().ForEach(p => guardedString.AppendChar(p));

            Uid uid = facade.Create(ObjectClass.ACCOUNT,
                CollectionUtil.NewSet(new Name("CREATE_01"), ConnectorAttributeBuilder.BuildPassword(guardedString)),
                optionsBuilder.Build());
            Assert.IsNull(uid);

            Uid resolvedUid = facade.ResolveUsername(ObjectClass.ACCOUNT, "CREATE_01", optionsBuilder.Build());
            Assert.IsNull(resolvedUid);

            Uid authenticatedUid = facade.Authenticate(ObjectClass.ACCOUNT, "CREATE_01", guardedString,
                optionsBuilder.Build());
            Assert.IsNull(authenticatedUid);

            SyncToken token = facade.GetLatestSyncToken(ObjectClass.ACCOUNT);
            Assert.IsNull(token);

            SyncToken lastToken = facade.Sync(ObjectClass.ACCOUNT, new SyncToken(-1),
                new SyncResultsHandler {Handle = delta => true}, optionsBuilder.Build());

            Assert.IsNull(lastToken);

            SearchResult searchResult = facade.Search(ObjectClass.ACCOUNT, null,
                new ResultsHandler {Handle = connectorObject => true}, optionsBuilder.Build());

            Assert.IsNull(searchResult);

            Uid updatedUid = facade.Update(ObjectClass.ACCOUNT, new Uid("1"),
                CollectionUtil.NewSet(ConnectorAttributeBuilder.BuildLockOut(true)), optionsBuilder.Build());
            Assert.IsNull(updatedUid);

            ConnectorObject co = facade.GetObject(ObjectClass.ACCOUNT, new Uid("1"), optionsBuilder.Build());
            Assert.IsNull(co);

            ScriptContextBuilder contextBuilder = new ScriptContextBuilder
            {
                ScriptLanguage = "Boo",
                ScriptText = "arg"
            };
            contextBuilder.AddScriptArgument("arg", "test");

            object o = facade.RunScriptOnConnector(contextBuilder.Build(), optionsBuilder.Build());
            Assert.AreEqual(o, "test");
            o = facade.RunScriptOnResource(contextBuilder.Build(), optionsBuilder.Build());
            Assert.IsNull(o);
        }
 public virtual void SyncAllCallFailPattern()
 {
     TestCallPattern(new TestOperationPattern()
     {
         MakeCall = facade =>
         {
             // create an empty results handler..
             SyncResultsHandler rh = new SyncResultsHandler()
             {
                 Handle = obj =>
                     {
                         return true;
                     }
             };
             // call the sync method..
             var builder = new OperationOptionsBuilder();
             builder.Options["FAIL_DELETE"] = true;
             facade.Sync(ObjectClass.ALL, new SyncToken(1), rh, builder.Build());
         },
         CheckCalls = calls =>
         {
             Assert.AreEqual("Sync", GetAndRemoveMethodName(calls));
         }
     });
 }
        public void TestCreateWithHomeDirectory_Account()
        {
            //Initialize Connector
            ActiveDirectoryConnector connector = new ActiveDirectoryConnector();
            ActiveDirectoryConfiguration config = (ActiveDirectoryConfiguration)ConfigHelper.GetConfiguration();
            config.CreateHomeDirectory = true;
            connector.Init(config);
            Uid userUid = null;
            try
            {
                // get the normal attributes
                ICollection<ConnectorAttribute> createAttributes = GetNormalAttributes_Account();

                // read the homedir path, and append the samaccountname
                StringBuilder homeDirPathBuilder = new StringBuilder(GetProperty(ConfigHelper.TEST_PARAM_SHARED_HOME_FOLDER));
                if (!homeDirPathBuilder.ToString().EndsWith("\\"))
                {
                    homeDirPathBuilder.Append('\\');
                }
                ConnectorAttribute samAccountNameAttr = ConnectorAttributeUtil.Find(
                    ActiveDirectoryConnector.ATT_SAMACCOUNT_NAME, createAttributes);
                homeDirPathBuilder.Append(ConnectorAttributeUtil.GetStringValue(samAccountNameAttr));

                // if it exists, delete it
                String homeDir = homeDirPathBuilder.ToString();
                if (Directory.Exists(homeDir))
                {
                    Directory.Delete(homeDir);
                }
                Assert.IsFalse(Directory.Exists(homeDir));

                // add homeDirectory to the attributes, and create user
                createAttributes.Add(ConnectorAttributeBuilder.Build("homeDirectory", homeDir));
                userUid = CreateAndVerifyObject(connector,
                    ObjectClass.ACCOUNT, createAttributes);

                // now directory should exist
                Assert.IsTrue(Directory.Exists(homeDir));

                // get sid to check permissions
                OperationOptionsBuilder optionsBuilder = new OperationOptionsBuilder();
                ICollection<String> attributesToGet = GetDefaultAttributesToGet(ObjectClass.ACCOUNT);
                attributesToGet.Add(ActiveDirectoryConnector.ATT_OBJECT_SID);
                optionsBuilder.AttributesToGet = attributesToGet.ToArray();

                ConnectorObject newUser = GetConnectorObjectFromUid(connector,
                    ObjectClass.ACCOUNT, userUid, optionsBuilder.Build());
                ConnectorAttribute sidAttr =
                    newUser.GetAttributeByName(ActiveDirectoryConnector.ATT_OBJECT_SID);
                Byte[] sidBytes = (Byte[])ConnectorAttributeUtil.GetSingleValue(sidAttr);
                SecurityIdentifier newUserSid = new SecurityIdentifier(sidBytes, 0);

                // check permissions
                DirectoryInfo dirInfo = new DirectoryInfo(homeDir);
                DirectorySecurity dirSec = dirInfo.GetAccessControl();
                AuthorizationRuleCollection rules = dirSec.GetAccessRules(true, true, typeof(SecurityIdentifier));
                bool foundCorrectRule = false;
                foreach (AuthorizationRule rule in rules)
                {
                    if (rule is FileSystemAccessRule)
                    {
                        FileSystemAccessRule fsaRule = (FileSystemAccessRule)rule;
                        if (fsaRule.IdentityReference.Equals(newUserSid))
                        {
                            if ((fsaRule.AccessControlType.Equals(AccessControlType.Allow)) &&
                                (fsaRule.FileSystemRights.Equals(FileSystemRights.FullControl)) &&
                                (fsaRule.InheritanceFlags.Equals(InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit)) &&
                                (fsaRule.IsInherited.Equals(false)))
                            {
                                foundCorrectRule = true;
                            }

                        }
                    }
                }

                // remove the directory (before assertion may fail)
                Directory.Delete(homeDir);

                // check that we found the proper permission record
                Assert.IsTrue(foundCorrectRule);
            }
            finally
            {
                if (userUid != null)
                {
                    DeleteAndVerifyObject(connector, ObjectClass.ACCOUNT, userUid, false, false);
                }
            }
        }