/// <summary>
        /// Performs a search on the current connection using the given query string (NOTE: Only users currently work)
        /// </summary>
        /// <param name="query">The query string</param>
        /// <param name="objectType">What objects to search for (defaults to User)</param>
        /// <returns>IEnumerable of the AD items found</returns>
        public IEnumerable <Principal> Find(string query, ADObjectType objectType = ADObjectType.User)
        {
            List <Principal> results = new List <Principal>();

            //Get an 'entry' for the directory we want
            DirectoryEntry entry = new DirectoryEntry(String.Format("LDAP://{0}", _Name),
                                                      _userid,
                                                      _password);

            //Create a 'searcher'
            DirectorySearcher searcher = new DirectorySearcher(entry);

            searcher.Filter = String.Format("(&(objectClass=user)(|(cn={0})(sAMAccountName={0})))", query);

            searcher.PropertiesToLoad.Clear();
            searcher.PropertiesToLoad.Add("cn");
            searcher.PageSize = 250;

            //For each search result...
            foreach (SearchResult result in searcher.FindAll())
            {
                Principal item = GetPrincipal(result);

                if (item != null)
                {
                    //Add a UserPrincipal object to the result list for this ID
                    results.Add(item);
                }
            }

            return(results);
        }
Exemplo n.º 2
0
        private static Dictionary <string, int> GetAllPortalObjects(ADObjectType objType)
        {
            var resultNodes = GetAllPortalObjectsByADObjectTypeAndPath(objType, "/Root/IMS");
            //var startPath = "/Root/IMS";
            //var types = (objType == ADObjectType.AllContainers)
            //    ? new[] { Common.GetNodeType(ADObjectType.OrgUnit).Name, Common.GetNodeType(ADObjectType.Container).Name, Common.GetNodeType(ADObjectType.Domain).Name }
            //    : new[] { Common.GetNodeType(objType).Name };
            //var settings = new QuerySettings { EnableAutofilters = FilterStatus.Disabled, EnableLifespanFilter = FilterStatus.Disabled };
            //var result = ContentQuery.Query(SafeQueries.InTreeAndTypeIs, settings, startPath, types);

            var nodeList = new List <Node>();

            foreach (var node in resultNodes)
            {
                try
                {
                    if (!string.IsNullOrEmpty(node.GetProperty <string>("SyncGuid")))
                    {
                        nodeList.Add(node);
                    }
                }
                catch (Exception ex)
                {
                    AdLog.LogError("Error caching nodes" + Environment.NewLine + "NodeId: " + node.Id + Environment.NewLine + "Node path: " + node.Path);
                    AdLog.LogException(ex);
                    throw ex;       // rethrow, do not allow adsync to run. if there is something wrong with the syncguid property things can go wrong (content unintentionally deleted, etc.)
                }
            }

            var guidIdList = nodeList.Select(node => new { Guid = node.GetProperty <string>("SyncGuid").ToLower(), ID = node.Id });

            return(guidIdList.ToDictionary(a => a.Guid, a => a.ID));
        }
Exemplo n.º 3
0
        private static Dictionary <string, int> GetAllPortalObjects(ADObjectType objType)
        {
            var typeText = string.Empty;

            if (objType == ADObjectType.AllContainers)
            {
                typeText = string.Concat(
                    "(TypeIs:", Common.GetNodeType(ADObjectType.OrgUnit).Name,
                    " OR TypeIs:", Common.GetNodeType(ADObjectType.Container).Name,
                    " OR TypeIs:", Common.GetNodeType(ADObjectType.Domain).Name, ")");
            }
            else
            {
                typeText = string.Concat("TypeIs:", Common.GetNodeType(objType).Name);
            }

            var queryText = string.Concat(typeText, " AND InTree:/Root/IMS");

            var settings = new QuerySettings {
                EnableAutofilters = false, EnableLifespanFilter = false
            };
            var query  = ContentQuery.CreateQuery(queryText, settings);
            var result = query.Execute();

            var guidIdList = (from node in result.Nodes
                              where !string.IsNullOrEmpty(node.GetProperty <string>("SyncGuid"))
                              select new { Guid = node.GetProperty <string>("SyncGuid").ToLower(), ID = node.Id });

            return(guidIdList.ToDictionary(a => a.Guid, a => a.ID));
        }
Exemplo n.º 4
0
        // returns synchronized portal nodes
        private IEnumerable <Node> GetAllPortalObjects(ADObjectType objType, SyncTree syncTree)
        {
            var typeText = string.Empty;

            if (objType == ADObjectType.AllContainers)
            {
                typeText = string.Concat(
                    "(TypeIs:", Common.GetNodeType(ADObjectType.OrgUnit).Name,
                    " OR TypeIs:", Common.GetNodeType(ADObjectType.Container).Name,
                    " OR TypeIs:", Common.GetNodeType(ADObjectType.Domain).Name, ")");
            }
            else
            {
                typeText = string.Concat("TypeIs:", Common.GetNodeType(objType).Name);
            }

            var startPath = string.Concat('"', syncTree.PortalPath.TrimEnd(new char[] { '/' }), '"');
            var queryText = string.Concat(typeText, " AND InTree:", startPath);

            var settings = new QuerySettings {
                EnableAutofilters = false, EnableLifespanFilter = false
            };
            var query  = ContentQuery.CreateQuery(queryText, settings);
            var result = query.Execute();

            return(result.Nodes);
        }
Exemplo n.º 5
0
        // sync objects from AD to portal
        private void SyncObjectsFromAD(SyncTree syncTree,
                                       ADObjectType objType,
                                       SearchResultCollection allADObjects,
                                       Action <DirectoryEntry, string, Guid, SyncTree> CreateNewObject,
                                       Action <DirectoryEntry, Node, SyncTree> UpdateProperties)
        {
            foreach (SearchResult result in allADObjects)
            {
                try
                {
                    string nodeADpath = result.Path;

                    if (syncTree.IsADPathExcluded(nodeADpath))
                    {
                        continue;
                    }

                    AdLog.LogOuterADObject("Syncing", result.Path);

                    var guid = Common.GetADResultGuid(result, _config.GuidProp);

                    if (!guid.HasValue)
                    {
                        // no AD guid present for object
                        AdLog.LogErrorADObject("No AD GUID present", result.Path);
                        continue;
                    }

                    // új objektumok (ou, user, group) felvétele, átmozgatások
                    // - ha létezik az adott guid-ú objektum -> path ellenőrzés, átmozgatás
                    // - ha nem létezik, létrehozás

                    string nodePortalParentPath = syncTree.GetPortalParentPath(nodeADpath);
                    if (!Node.Exists(nodePortalParentPath))
                    {
                        // adpath: OU=OtherOrg,OU=ExampleOrg,DC=Nativ,DC=local
                        // portalParentPath: "/Root/IMS/NATIV/ExampleOrg"
                        EnsurePortalPath(syncTree, syncTree.GetADParentObjectPath(result.Path), RepositoryPath.GetParentPath(nodePortalParentPath));
                    }

                    SyncOneADObject(result, null,
                                    (Guid)guid,
                                    objType,
                                    nodePortalParentPath,
                                    CreateNewObject,
                                    UpdateProperties,
                                    syncTree);
                }
                catch (Exception ex)
                {
                    // syncing of one object of the current tree failed
                    AdLog.LogException(ex);
                }
            }
        }
Exemplo n.º 6
0
        private static IEnumerable <Node> GetAllPortalObjectsByADObjectTypeAndPath(ADObjectType objType, string startPath)
        {
            var types = (objType == ADObjectType.AllContainers)
                ? new[] { Common.GetNodeType(ADObjectType.OrgUnit).Name, Common.GetNodeType(ADObjectType.Container).Name, Common.GetNodeType(ADObjectType.Domain).Name }
                : new[] { Common.GetNodeType(objType).Name };
            var settings = new QuerySettings {
                EnableAutofilters = FilterStatus.Disabled, EnableLifespanFilter = FilterStatus.Disabled
            };
            var result = ContentQuery.Query(SafeQueries.InTreeAndTypeIs, settings, startPath, types);

            return(result.Nodes);
        }
        public IEnumerable <Principal> Find(ADCriteria criteria = null, ADObjectType objectType = ADObjectType.User)
        {
            List <Principal> results = new List <Principal>();
            ADCriteria       query;

            //Get an 'entry' for the directory we want
            DirectoryEntry entry = new DirectoryEntry(String.Format("LDAP://{0}", _Name),
                                                      _userid,
                                                      _password);

            //Create a 'searcher'
            DirectorySearcher searcher = new DirectorySearcher(entry);

            if (criteria == null)
            {
                criteria = new NullCriteria();
            }

            if (objectType == ADObjectType.User)
            {
                query = criteria.And(new BaseCriteria("objectClass", "user"));
            }
            else if (objectType == ADObjectType.Group)
            {
                query = criteria.And(new BaseCriteria("objectClass", "group"));
            }
            else
            {
                query = criteria;
            }

            searcher.Filter = query.ToString();
            searcher.PropertiesToLoad.Clear();
            searcher.PropertiesToLoad.Add("cn");
            searcher.PageSize = 250;

            //For each search result...
            foreach (SearchResult result in searcher.FindAll())
            {
                Principal item = GetPrincipal(result);

                if (item != null)
                {
                    //Add a UserPrincipal object to the result list for this ID
                    results.Add(item);
                }
            }


            return(results);
        }
Exemplo n.º 8
0
        /// <summary>
        /// True if the object exists.
        /// </summary>
        /// <param name="samAccountName">The SAM Account Name.</param>
        /// <param name="type">The type.</param>
        /// <param name="locations">The locations where the object was found. (If exists).</param>
        /// <returns></returns>
        public bool AdObjectExists(string samAccountName, ADObjectType type, out IEnumerable <string> locations)
        {
            locations = new Collection <string>();

            /*
             * string[] locationsArray;
             * ADWSClient client = new ADWSClient();
             * bool exists = client.ExistsADObjectInGC(samAccountName, type, out locationsArray);
             * if (locationsArray != null)
             * {
             *  locations = new Collection<string>(locationsArray);
             * }
             * return exists;*/
            return(true);
        }
Exemplo n.º 9
0
 private async void CreateADObjectInDB(string objectid, ADObjectType adType, string name, string distinguishedname, string domain, string tier)
 {
     try
     {
         await DBConnection.Query(@"
             CREATE (o {objectid:'" + objectid + "', domain:'" + domain + "', distinguishedname:'" + distinguishedname + "', name:'" + name +
                                  @"', " + DBCustomNodeProperty + @": true})
             WITH o
             CALL apoc.create.setLabels(o, ['Base', '" + adType.ToString() + "', 'Tier" + tier + @"']) YIELD node
             RETURN NULL
         ");
     }
     catch
     {
         throw;
     }
 }
Exemplo n.º 10
0
        public ADObject(string objectid, ADObjectType type, string cn, string name, string distinguishedname, string tier, pages.OUStructurePage oUStructurePage)
        {
            Objectid             = objectid;
            CN                   = cn;
            Name                 = name;
            Distinguishedname    = distinguishedname;
            Tier                 = tier;
            Type                 = type;
            Children             = new Dictionary <string, ADObject>();
            this.oUStructurePage = oUStructurePage;

            TierUpCommand   = new RelayCommand(TierUp);
            TierDownCommand = new RelayCommand(TierDown);

            switch (type)
            {
            case ADObjectType.Domain:
                Iconpath = "/resources/images/ad-icons/domain1.png";
                break;

            case ADObjectType.OU:
                Iconpath = "/resources/images/ad-icons/ou.png";
                break;

            case ADObjectType.Group:
                Iconpath = "/resources/images/ad-icons/group.png";
                break;

            case ADObjectType.User:
                Iconpath = "/resources/images/ad-icons/user.png";
                break;

            case ADObjectType.Computer:
                Iconpath = "/resources/images/ad-icons/computer.png";
                break;

            case ADObjectType.GPO:
                Iconpath = "/resources/images/ad-icons/gpo.png";
                break;

            default:
                Iconpath = "/resources/images/ad-icons/domain2.png";
                break;
            }
        }
Exemplo n.º 11
0
 /// <summary>
 /// True if the object exists.
 /// </summary>
 /// <param name="samAccountName">The SAM Account Name.</param>
 /// <param name="type">The type.</param>
 /// <param name="locations">The locations where the object was found. (If exists).</param>
 /// <returns></returns>
 public bool AdObjectExists(string samAccountName, ADObjectType type, out IEnumerable <string> locations)
 {
     locations = new Collection <string>();
     switch (type)
     {
     case ADObjectType.Computer:
         return((string.Compare(samAccountName, StubADHelperData.NonUniqueDesktopComputerName1, true, CultureInfo.CurrentCulture) == 0) ||
                (string.Compare(samAccountName, StubADHelperData.NonUniqueOtherDesktopComputerName1, true, CultureInfo.CurrentCulture) == 0) ||
                (string.Compare(samAccountName, StubADHelperData.NonUniqueDesktopComputerName2, true, CultureInfo.CurrentCulture) == 0) ||
                (string.Compare(samAccountName, StubADHelperData.NonUniqueOtherDesktopComputerName2, true, CultureInfo.CurrentCulture) == 0) ||
                (string.Compare(samAccountName, StubADHelperData.NonUniqueMobileComputerName1, true, CultureInfo.CurrentCulture) == 0) ||
                (string.Compare(samAccountName, StubADHelperData.NonUniqueOtherMobileComputerName1, true, CultureInfo.CurrentCulture) == 0) ||
                (string.Compare(samAccountName, StubADHelperData.NonUniqueMobileComputerName2, true, CultureInfo.CurrentCulture) == 0) ||
                (string.Compare(samAccountName, StubADHelperData.NonUniqueOtherMobileComputerName2, true, CultureInfo.CurrentCulture) == 0) ||
                (string.Compare(samAccountName, StubADHelperData.NonUniqueServerName, true, CultureInfo.CurrentCulture) == 0));
     }
     return(false);
 }
Exemplo n.º 12
0
        public static string GetADObjectPrefix(ADObjectType adObjectType)
        {
            switch (adObjectType)
            {
            case ADObjectType.Container:
            case ADObjectType.User:
            case ADObjectType.Group:
                return("CN=");

            case ADObjectType.OrgUnit:
                return("OU=");

            case ADObjectType.Domain:
                return("DC=");

            default:
                return(null);
            }
        }
Exemplo n.º 13
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                this.adObjectType = (ADObjectType)this.Session["ADObjectType"];
                switch (this.adObjectType)
                {
                case ADObjectType.UsersAndGroups: this.lblTopDescription.Text = "Choose Users and/or Groups:"; break;

                case ADObjectType.UsersOnly: this.lblTopDescription.Text = "Choose Users:"; break;

                case ADObjectType.OneUserOnly: this.lblTopDescription.Text = "Choose 1 User:"******"Active Directory Search";
                this.Description = this.Text;
                this.Title       = this.Text;
                this.txtInput.Focus();
            }
            else
            {
                if (this.Session["selectedADObjects"] != null)
                {
                    this.txtInput.Text = String.Empty;
                    foreach (ADObject ado in (List <ADObject>) this.Session["selectedADObjects"])
                    {
                        this.txtInput.Text += ado.Name + "; ";
                    }
                    this.checkNames();
                }
                if (this.Session["selectedADObjectsFromList"] != null)
                {
                    foreach (ADObject ado in (List <ADObject>) this.Session["selectedADObjectsFromList"])
                    {
                        this.txtInput.Text += ado.Name + "; ";
                    }
                    this.checkNames();
                }
            }
            this.btnBrowse.Enabled = this.Application["Active Directory List"] != null && ((DataView)this.Application["Active Directory List"]).Table.Rows.Count > 0;
        }
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!Page.IsPostBack)
     {
         this.adObjectType = (ADObjectType)this.Session["ADObjectType"];
         switch (this.adObjectType)
         {
             case ADObjectType.UsersAndGroups: this.lblTopDescription.Text = "Choose Users and/or Groups:"; break;
             case ADObjectType.UsersOnly: this.lblTopDescription.Text = "Choose Users:"; break;
             case ADObjectType.OneUserOnly: this.lblTopDescription.Text = "Choose 1 User:"******"Active Directory Search";
         this.Description = this.Text;
         this.Title = this.Text;
         this.txtInput.Focus();
     }
     else
     {
         if (this.Session["selectedADObjects"] != null)
         {
             this.txtInput.Text = String.Empty;
             foreach (ADObject ado in (List<ADObject>)this.Session["selectedADObjects"])
             {
                 this.txtInput.Text += ado.Name + "; ";
             }
             this.checkNames();
         }
         if (this.Session["selectedADObjectsFromList"] != null)
         {
             foreach (ADObject ado in (List<ADObject>)this.Session["selectedADObjectsFromList"])
             {
                 this.txtInput.Text += ado.Name + "; ";
             }
             this.checkNames();
         }
     }
     this.btnBrowse.Enabled = this.Application["Active Directory List"] != null && ((DataView)this.Application["Active Directory List"]).Table.Rows.Count > 0;
 }
Exemplo n.º 15
0
        // delete portal objects that have no corresponding synchronized objects in AD
        private void DeleteObjectsFromAD(SyncTree syncTree,
                                         ADObjectType objType,
                                         SearchResultCollection allADObjects,
                                         Action <Node> DeletePortalObject)
        {
            try
            {
                AdLog.LogOuter("Querying all portal objects...");
                var portalNodes = GetAllPortalObjects(objType, syncTree);
                AdLog.LogOuter("Checking if portal objects exist under synchronized path in AD...");
                foreach (Node node in portalNodes)
                {
                    try
                    {
                        // check if object exists under synchronized path in AD
                        var guid = Common.GetPortalObjectGuid(node);
                        if ((!guid.HasValue) || (!ADObjectPathSynced((Guid)guid, allADObjects, node)))
                        {
                            if (!guid.HasValue)
                            {
                                AdLog.Log(string.Format("No guid set for portal object: {0} ", node.Path));
                            }

                            // deleted from AD or not under synchronized path any more
                            DeletePortalObject(node);
                        }
                    }
                    catch (Exception ex)
                    {
                        AdLog.LogException(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                AdLog.LogException(ex);
            }
        }
Exemplo n.º 16
0
        private static string GetContentTypeName(ADObjectType type)
        {
            switch (type)
            {
            case ADObjectType.User:
                return("User");

            case ADObjectType.Group:
                return("Group");

            case ADObjectType.OrgUnit:
            case ADObjectType.Organization:
                return("OrganizationalUnit");

            case ADObjectType.Domain:
                return("Domain");

            case ADObjectType.Container:
                return("ADFolder");

            default:
                throw new NotSupportedException("Unknown content type token: " + type);
            }
        }
Exemplo n.º 17
0
        public static async Task <IEnumerable <Content> > QueryContentByTypeAndPath(ADObjectType objType, string startPath, string[] select = null, int skip = 0, int top = 0)
        {
            try
            {
                var           types    = GetContentTypeNames(objType);
                QuerySettings settings = null;
                if (skip > 0 || top > 0)
                {
                    settings = new QuerySettings
                    {
                        Skip = skip,
                        Top  = top
                    };
                }

                return(await Content.QueryForAdminAsync("+InTree:'" + startPath + "' +TypeIs:(" + string.Join(" ", types) + ") .SORT:Path", select, settings : settings));
            }
            catch (Exception ex)
            {
                AdLog.LogException(ex);
            }

            return(new Content[0]);
        }
Exemplo n.º 18
0
        // gets the portal NodeType corresponding to the AD object type
        public static NodeType GetNodeType(ADObjectType adObjectType)
        {
            switch (adObjectType)
            {
            case ADObjectType.User:
                return(NodeType.GetByName(typeof(User).Name));

            case ADObjectType.Group:
                return(NodeType.GetByName(typeof(Group).Name));

            case ADObjectType.OrgUnit:
            case ADObjectType.Organization:
                return(NodeType.GetByName(typeof(OrganizationalUnit).Name));

            case ADObjectType.Domain:
                return(NodeType.GetByName(typeof(Domain).Name));

            case ADObjectType.Container:
                return(NodeType.GetByName("ADFolder"));

            default:
                return(null);
            }
        }
Exemplo n.º 19
0
        /* ==================================================================================== AD -> portal : Main algorithms */
        // sync one object
        // két helyről hívhatjuk:
        // - SyncObjectsFromAD --> innen SearchResult objektumot kapunk
        // - SyncObjectsFromAD/EnsurePath --> innen Entryt kapunk
        //      - utóbbiból helyes működésnél csak létre kell hozni új objektumot, de ha már létezik az objektum, akkor
        //        moveoljuk, ne keletkezzen két azonos GUID-ú objektum a portálon
        private void SyncOneADObject(SearchResult result, DirectoryEntry ADentry,
            Guid guid,
            ADObjectType objType,
            string nodePortalParentPath,
            Action<DirectoryEntry, string, Guid, SyncTree> CreateNewObject,
            Action<DirectoryEntry, Node, SyncTree> UpdateProperties,
            SyncTree syncTree)
        {
            //bool validResult;
            //var node = GetNodeByGuid(guid, objType, out validResult);
            Node node = null;
            string guidStr = guid.ToString();
            switch (objType)
            {
                case ADObjectType.AllContainers:
                    node = (_portalContainers.ContainsKey(guidStr)) ? Node.LoadNode(_portalContainers[guidStr]) : null;
                    break;
                case ADObjectType.User:
                    node = (_portalUsers.ContainsKey(guidStr)) ? Node.LoadNode(_portalUsers[guidStr]) : null;
                    break;
                case ADObjectType.Group:
                    node = (_portalGroups.ContainsKey(guidStr)) ? Node.LoadNode(_portalGroups[guidStr]) : null;
                    break;
                default:
                    break;
            }
            if (node != null)
            {
                // existing portal object
                try
                {
                    bool isNodeSynced = false;

                    // check path, move object if necessary
                    if (RepositoryPath.GetParentPath(node.Path) != nodePortalParentPath)
                    {
                        AdLog.LogADObject(string.Format("Moving object from {0} to {1}", node.Path, nodePortalParentPath), result.Path);
                        Node.Move(node.Path, nodePortalParentPath);

                        // reload node for further processing (set properties)
                        node = Node.LoadNode(node.Id);
                        isNodeSynced = true;
                    }

                    if (ADentry != null)
                    {
                        // ensurepath-ból jön, mindenképp szinkronizáljuk
                        UpdateProperties(ADentry, node, syncTree);
                        AdLog.LogADObject(String.Format("Saving synced portal object: {0}", node.Path), ADentry.Path);
                        Common.UpdateLastSync(node, null);
                        //node.Save(); - update lastsync already saves node
                    }
                    else
                    {
                        // syncobjectsből jövünk, csak resultunk van (entrynk nincs)

                        // set properties and lastsync date - csak akkor szinkronizálunk, ha lastmod > x 
                        // (ha az objektum át lett mozgatva, a lastmod is változik AD-ben)
                        if (_config.AlwaysSyncObjects || Common.IsPortalObjectInvalid(node, result, _config.NovellSupport))
                        {
                            using (var entry = result.GetDirectoryEntry())
                            {
                                UpdateProperties(entry, node, syncTree);
                                isNodeSynced = true;
                            }
                        }

                        if (isNodeSynced)
                        {
                            AdLog.LogADObject(String.Format("Saving synced portal object: {0}", node.Path), result.Path);
                            Common.UpdateLastSync(node, null);
                            //node.Save(); - update lastsync already saves node
                        }
                    }
                }
                catch (Exception ex)
                {
                    AdLog.LogException(ex);
                    // log: adott objektum szinkronizálása nem sikerült
                    if (result != null)
                        AdLog.LogErrorADObject("Syncing of AD object not successful.", result.Path);
                }
            }
            else
            {
                if (ADentry != null)
                {
                    // ensurepath-ból jövünk
                    CreateNewObject(ADentry, nodePortalParentPath, guid, syncTree);
                }
                else
                {
                    // syncobjectsből jövünk, csak resultunk van
                    // new portal object
                    using (var entry = result.GetDirectoryEntry())
                    {
                        CreateNewObject(entry, nodePortalParentPath, guid, syncTree);
                    }
                }
            }
        }
Exemplo n.º 20
0
        private static Dictionary<string, int> GetAllPortalObjects(ADObjectType objType)
        {
            var typeText = string.Empty;
            if (objType == ADObjectType.AllContainers)
            {
                typeText = string.Concat(
                    "(TypeIs:", Common.GetNodeType(ADObjectType.OrgUnit).Name,
                    " OR TypeIs:", Common.GetNodeType(ADObjectType.Container).Name,
                    " OR TypeIs:", Common.GetNodeType(ADObjectType.Domain).Name, ")");
            }
            else
            {
                typeText = string.Concat("TypeIs:", Common.GetNodeType(objType).Name);
            }

            var queryText = string.Concat(typeText, " AND InTree:/Root/IMS");

            var settings = new QuerySettings { EnableAutofilters = false, EnableLifespanFilter = false };
            var query = ContentQuery.CreateQuery(queryText, settings);
            var result = query.Execute();

            var guidIdList = (from node in result.Nodes
                              where !string.IsNullOrEmpty(node.GetProperty<string>("SyncGuid"))
                              select new {Guid = node.GetProperty<string>("SyncGuid").ToLower(), ID = node.Id});

            return guidIdList.ToDictionary(a => a.Guid, a => a.ID);
        }
Exemplo n.º 21
0
        // returns synchronized portal nodes
        private IEnumerable<Node> GetAllPortalObjects(ADObjectType objType, SyncTree syncTree)
        {
            var typeText = string.Empty;
            if (objType == ADObjectType.AllContainers)
            {
                typeText = string.Concat(
                    "(TypeIs:", Common.GetNodeType(ADObjectType.OrgUnit).Name, 
                    " OR TypeIs:", Common.GetNodeType(ADObjectType.Container).Name, 
                    " OR TypeIs:", Common.GetNodeType(ADObjectType.Domain).Name, ")");
            }
            else
            {
                typeText = string.Concat("TypeIs:", Common.GetNodeType(objType).Name);
            }

            var startPath = string.Concat('"', syncTree.PortalPath.TrimEnd(new char[] { '/' }), '"');
            var queryText = string.Concat(typeText, " AND InTree:", startPath);

            var settings = new QuerySettings {EnableAutofilters = false, EnableLifespanFilter = false};
            var query = ContentQuery.CreateQuery(queryText, settings);
            var result = query.Execute();
            return result.Nodes;
        }
Exemplo n.º 22
0
 // gets the portal NodeType corresponding to the AD object type
 public static NodeType GetNodeType(ADObjectType adObjectType)
 {
     switch (adObjectType)
     {
         case ADObjectType.User:
             return NodeType.GetByName(typeof(User).Name);
         case ADObjectType.Group:
             return NodeType.GetByName(typeof(Group).Name);
         case ADObjectType.OrgUnit:
         case ADObjectType.Organization:
             return NodeType.GetByName(typeof(OrganizationalUnit).Name);
         case ADObjectType.Domain:
             return NodeType.GetByName(typeof(Domain).Name);
         case ADObjectType.Container:
             return NodeType.GetByName("ADFolder");
         default:
             return null;
     }
 }
Exemplo n.º 23
0
 public static string GetADObjectPrefix(ADObjectType adObjectType)
 {
     switch (adObjectType)
     {
         case ADObjectType.Container:
         case ADObjectType.User:
         case ADObjectType.Group:
             return "CN=";
         case ADObjectType.OrgUnit:
             return "OU=";
         case ADObjectType.Domain:
             return "DC=";
         default:
             return null;
     }
 }
Exemplo n.º 24
0
        internal static ADObject GetADObject(IADOperator adOperator, SearchResult searchResult)
        {
            ADObject     adObject;
            ADObjectType adObjectType = GetADObjectType(searchResult);

            switch (adObjectType)
            {
            case ADObjectType.User:
                adObject = new UserObject(adOperator, searchResult);
                break;

            case ADObjectType.Contact:
                adObject = new ContactObject(adOperator, searchResult);
                break;

            case ADObjectType.Computer:
                adObject = new ComputerObject(adOperator, searchResult);
                break;

            case ADObjectType.Container:
                adObject = new ContainerObject(adOperator, searchResult);
                break;

            case ADObjectType.Group:
                adObject = new GroupObject(adOperator, searchResult);
                break;

            case ADObjectType.InetOrgPerson:
                adObject = new InetOrgPersonObject(adOperator, searchResult);
                break;

            case ADObjectType.MSMQQueueAlias:
                adObject = new MSMQQueueAliasObject(adOperator, searchResult);
                break;

            case ADObjectType.MsImaging_PSPs:
                adObject = new MsImaging_PSPsObject(adOperator, searchResult);
                break;

            case ADObjectType.OrganizationalUnit:
                adObject = new OrganizationalUnitObject(adOperator, searchResult);
                break;

            case ADObjectType.Printer:
                adObject = new PrinterObject(adOperator, searchResult);
                break;

            case ADObjectType.SharedFolder:
                adObject = new SharedFolderObject(adOperator, searchResult);
                break;

            case ADObjectType.Domain:
                adObject = new DomainObject(adOperator, searchResult);
                break;

            case ADObjectType.PasswordSettings:
                adObject = new PasswordSettingsObject(adOperator, searchResult);
                break;

            default:
                adObject = new UnknownObject(adOperator, searchResult);
                break;
            }
            return(adObject);
        }
        public IEnumerable<Principal> Find(ADCriteria criteria=null, ADObjectType objectType = ADObjectType.User)
        {
            List<Principal> results = new List<Principal>();
            ADCriteria query;

            //Get an 'entry' for the directory we want
            DirectoryEntry entry = new DirectoryEntry(String.Format("LDAP://{0}", _Name),
                                                        _userid,
                                                        _password);

            //Create a 'searcher'
            DirectorySearcher searcher = new DirectorySearcher(entry);

            if (criteria == null)
            {
                criteria = new NullCriteria();
            }

            if (objectType== ADObjectType.User)
            {
                query=criteria.And(new BaseCriteria("objectClass","user"));
            }
            else if (objectType == ADObjectType.Group)
            {
                query=criteria.And(new BaseCriteria("objectClass","group"));
            }
            else
            {
                query=criteria;
            }

            searcher.Filter = query.ToString();
            searcher.PropertiesToLoad.Clear();
            searcher.PropertiesToLoad.Add("cn");
            searcher.PageSize = 250;

            //For each search result...
            foreach (SearchResult result in searcher.FindAll())
            {
                Principal item=GetPrincipal(result);

                if (item != null)
                {
                    //Add a UserPrincipal object to the result list for this ID
                    results.Add(item);
                }
            }

            return results;
        }
Exemplo n.º 26
0
        /* ==================================================================================== AD -> portal : Main algorithms */
        // sync one object
        // két helyről hívhatjuk:
        // - SyncObjectsFromAD --> innen SearchResult objektumot kapunk
        // - SyncObjectsFromAD/EnsurePath --> innen Entryt kapunk
        //      - utóbbiból helyes működésnél csak létre kell hozni új objektumot, de ha már létezik az objektum, akkor
        //        moveoljuk, ne keletkezzen két azonos GUID-ú objektum a portálon
        private void SyncOneADObject(SearchResult result, DirectoryEntry ADentry,
                                     Guid guid,
                                     ADObjectType objType,
                                     string nodePortalParentPath,
                                     Action <DirectoryEntry, string, Guid, SyncTree> CreateNewObject,
                                     Action <DirectoryEntry, Node, SyncTree> UpdateProperties,
                                     SyncTree syncTree)
        {
            //bool validResult;
            //var node = GetNodeByGuid(guid, objType, out validResult);
            Node   node    = null;
            string guidStr = guid.ToString();

            switch (objType)
            {
            case ADObjectType.AllContainers:
                node = (_portalContainers.ContainsKey(guidStr)) ? Node.LoadNode(_portalContainers[guidStr]) : null;
                break;

            case ADObjectType.User:
                node = (_portalUsers.ContainsKey(guidStr)) ? Node.LoadNode(_portalUsers[guidStr]) : null;
                break;

            case ADObjectType.Group:
                node = (_portalGroups.ContainsKey(guidStr)) ? Node.LoadNode(_portalGroups[guidStr]) : null;
                break;

            default:
                break;
            }
            if (node != null)
            {
                // existing portal object
                try
                {
                    bool isNodeSynced = false;

                    // check path, move object if necessary
                    if (RepositoryPath.GetParentPath(node.Path) != nodePortalParentPath)
                    {
                        AdLog.LogADObject(string.Format("Moving object from {0} to {1}", node.Path, nodePortalParentPath), result.Path);
                        Node.Move(node.Path, nodePortalParentPath);

                        // reload node for further processing (set properties)
                        node         = Node.LoadNode(node.Id);
                        isNodeSynced = true;
                    }

                    if (ADentry != null)
                    {
                        // ensurepath-ból jön, mindenképp szinkronizáljuk
                        UpdateProperties(ADentry, node, syncTree);
                        AdLog.LogADObject(String.Format("Saving synced portal object: {0}", node.Path), ADentry.Path);
                        Common.UpdateLastSync(node, null);
                        //node.Save(); - update lastsync already saves node
                    }
                    else
                    {
                        // syncobjectsből jövünk, csak resultunk van (entrynk nincs)

                        // set properties and lastsync date - csak akkor szinkronizálunk, ha lastmod > x
                        // (ha az objektum át lett mozgatva, a lastmod is változik AD-ben)
                        if (_config.AlwaysSyncObjects || Common.IsPortalObjectInvalid(node, result, _config.NovellSupport))
                        {
                            using (var entry = result.GetDirectoryEntry())
                            {
                                UpdateProperties(entry, node, syncTree);
                                isNodeSynced = true;
                            }
                        }

                        if (isNodeSynced)
                        {
                            AdLog.LogADObject(String.Format("Saving synced portal object: {0}", node.Path), result.Path);
                            Common.UpdateLastSync(node, null);
                            //node.Save(); - update lastsync already saves node
                        }
                    }
                }
                catch (Exception ex)
                {
                    AdLog.LogException(ex);
                    // log: adott objektum szinkronizálása nem sikerült
                    if (result != null)
                    {
                        AdLog.LogErrorADObject("Syncing of AD object not successful.", result.Path);
                    }
                }
            }
            else
            {
                if (ADentry != null)
                {
                    // ensurepath-ból jövünk
                    CreateNewObject(ADentry, nodePortalParentPath, guid, syncTree);
                }
                else
                {
                    // syncobjectsből jövünk, csak resultunk van
                    // new portal object
                    using (var entry = result.GetDirectoryEntry())
                    {
                        CreateNewObject(entry, nodePortalParentPath, guid, syncTree);
                    }
                }
            }
        }
Exemplo n.º 27
0
        public static void SetContentValue(Content content, SyncProperty portalProp, string value, ADObjectType type)
        {
            var propValue = value.MaximizeLength(portalProp.MaxLength);

            if (portalProp.Name == "Name")
            {
                content.Name = propValue;

                // in case of AD users the login name should be the same as the content name
                if (type == ADObjectType.User)
                {
                    content["LoginName"] = propValue;
                }
            }
            else
            {
                content[portalProp.Name] = propValue;
            }
        }
Exemplo n.º 28
0
 public static async Task <IEnumerable <Content> > QueryAllContent(ADObjectType objType, SyncTree syncTree, bool allFields = false)
 {
     return(await QueryContentByTypeAndPath(objType, syncTree.PortalPath.TrimEnd('/'), allFields?null : Common.Fields));
 }
Exemplo n.º 29
0
 // returns synchronized portal nodes
 private IEnumerable <Node> GetAllPortalObjects(ADObjectType objType, SyncTree syncTree)
 {
     return(GetAllPortalObjectsByADObjectTypeAndPath(objType, syncTree.PortalPath.TrimEnd('/')));
 }
Exemplo n.º 30
0
        // sync objects from AD to portal
        private void SyncObjectsFromAD(SyncTree syncTree,
            ADObjectType objType,
            SearchResultCollection allADObjects,
            Action<DirectoryEntry, string, Guid, SyncTree> CreateNewObject,
            Action<DirectoryEntry, Node, SyncTree> UpdateProperties)
        {
            foreach (SearchResult result in allADObjects)
            {
                try
                {
                    string nodeADpath = result.Path;

                    if (syncTree.IsADPathExcluded(nodeADpath))
                        continue;

                    AdLog.LogOuterADObject("Syncing", result.Path);

                    var guid = Common.GetADResultGuid(result, _config.GuidProp);

                    if (!guid.HasValue)
                    {
                        // no AD guid present for object
                        AdLog.LogErrorADObject("No AD GUID present", result.Path);
                        continue;
                    }

                    // új objektumok (ou, user, group) felvétele, átmozgatások
                    // - ha létezik az adott guid-ú objektum -> path ellenőrzés, átmozgatás
                    // - ha nem létezik, létrehozás

                    string nodePortalParentPath = syncTree.GetPortalParentPath(nodeADpath);
                    if (!Node.Exists(nodePortalParentPath))
                    {
                        // adpath: OU=OtherOrg,OU=ExampleOrg,DC=Nativ,DC=local
                        // portalParentPath: "/Root/IMS/NATIV/ExampleOrg"
                        EnsurePortalPath(syncTree, syncTree.GetADParentObjectPath(result.Path), RepositoryPath.GetParentPath(nodePortalParentPath));
                    }

                    SyncOneADObject(result, null,
                        (Guid)guid,
                        objType,
                        nodePortalParentPath,
                        CreateNewObject,
                        UpdateProperties,
                        syncTree);
                }
                catch (Exception ex)
                {
                    // syncing of one object of the current tree failed
                    AdLog.LogException(ex);
                }
            }
        }
Exemplo n.º 31
0
        // delete portal objects that have no corresponding synchronized objects in AD
        private void DeleteObjectsFromAD(SyncTree syncTree,
            ADObjectType objType,
            SearchResultCollection allADObjects,
            Action<Node> DeletePortalObject)
        {
            try
            {
                AdLog.LogOuter("Querying all portal objects...");
                var portalNodes = GetAllPortalObjects(objType, syncTree);
                AdLog.LogOuter("Checking if portal objects exist under synchronized path in AD...");
                foreach (Node node in portalNodes)
                {
                    try
                    {
                        // check if object exists under synchronized path in AD
                        var guid = Common.GetPortalObjectGuid(node);
                        if ((!guid.HasValue) || (!ADObjectPathSynced((Guid)guid, allADObjects, node)))
                        {
                            if (!guid.HasValue)
                                AdLog.Log(string.Format("No guid set for portal object: {0} ", node.Path));

                            // deleted from AD or not under synchronized path any more
                            DeletePortalObject(node);
                        }
                    }
                    catch (Exception ex)
                    {
                        AdLog.LogException(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                AdLog.LogException(ex);
            }
        }
        /// <summary>
        /// Performs a search on the current connection using the given query string (NOTE: Only users currently work)
        /// </summary>
        /// <param name="query">The query string</param>
        /// <param name="objectType">What objects to search for (defaults to User)</param>
        /// <returns>IEnumerable of the AD items found</returns>
        public IEnumerable<Principal> Find(string query, ADObjectType objectType = ADObjectType.User)
        {
            List<Principal> results = new List<Principal>();

            //Get an 'entry' for the directory we want
            DirectoryEntry entry = new DirectoryEntry(String.Format("LDAP://{0}", _Name),
                                                        _userid,
                                                        _password);

            //Create a 'searcher'
            DirectorySearcher searcher = new DirectorySearcher(entry);
            searcher.Filter = String.Format("(&(objectClass=user)(|(cn={0})(sAMAccountName={0})))", query);

            searcher.PropertiesToLoad.Clear();
            searcher.PropertiesToLoad.Add("cn");
            searcher.PageSize = 250;

            //For each search result...
            foreach (SearchResult result in searcher.FindAll())
            {
                Principal item = GetPrincipal(result);

                if (item != null)
                {
                    //Add a UserPrincipal object to the result list for this ID
                    results.Add(item);
                }
            }

            return results;
        }
Exemplo n.º 33
0
        internal static ADObjectType GetADObjectType(SearchResult searchResult)
        {
            ADObjectType adObjectType = ADObjectType.Unknow;

            if (searchResult != null)
            {
                var resultPropertyValueCollection = searchResult.Properties[AttributeNames.ObjectClass];
                for (int index = 0; index < resultPropertyValueCollection.Count; index++)
                {
                    switch (resultPropertyValueCollection[index].ToString())
                    {
                    case UserAttributeValues.User:
                        adObjectType = ADObjectType.User;
                        break;

                    case ContactAttributeValues.Contact:
                        adObjectType = ADObjectType.Contact;
                        break;

                    case ComputerAttributeValues.Computer:
                        adObjectType = ADObjectType.Computer;
                        break;

                    case ContainerAttributeValues.Container:
                        adObjectType = ADObjectType.Container;
                        break;

                    case GroupAttributeValues.Group:
                        adObjectType = ADObjectType.Group;
                        break;

                    case InetOrgPersonAttributeValues.InetOrgPerson:
                        adObjectType = ADObjectType.InetOrgPerson;
                        break;

                    case MSMQQueueAliasAttributeValues.MSMQQueueAlias:
                        adObjectType = ADObjectType.MSMQQueueAlias;
                        break;

                    case MsImaging_PSPsAttributeValues.MsImaging_PSPs:
                        adObjectType = ADObjectType.MsImaging_PSPs;
                        break;

                    case OrganizationalUnitAttributeValues.OrganizationalUnit:
                        adObjectType = ADObjectType.OrganizationalUnit;
                        break;

                    case PrinterAttributeValues.Printer:
                        adObjectType = ADObjectType.Printer;
                        break;

                    case SharedFolderAttributeValues.SharedFolder:
                        adObjectType = ADObjectType.SharedFolder;
                        break;

                    case DomainAttributeValues.Domain:
                        adObjectType = ADObjectType.Domain;
                        break;

                    case PasswordSettingsAttributeValues.MsDS_PasswordSettings:
                        adObjectType = ADObjectType.PasswordSettings;
                        break;

                    default:
                        break;
                    }
                }
            }
            return(adObjectType);
        }
Exemplo n.º 34
0
 private static IEnumerable <string> GetContentTypeNames(ADObjectType type)
 {
     return((type == ADObjectType.AllContainers)
         ? new[] { GetContentTypeName(ADObjectType.OrgUnit), GetContentTypeName(ADObjectType.Container), GetContentTypeName(ADObjectType.Domain) }
         : new[] { GetContentTypeName(type) });
 }