Ejemplo n.º 1
0
        public bool ValidateByAd(string userId, string password)
        {
            //For pass AD verify use next line of this code
            // return true;
            bool validateResult = false;

            if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(password))
            {
                return(false);
            }

            string lowerUserId = userId.ToLower();//將使用者帳號全轉為小寫

#if DEBUG
            //dev debug 測試 因本機電腦 沒有加入 domain 只用此方式
            using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "whq"))
            {
                //validate the credentials
                validateResult = pc.ValidateCredentials(userId, password);
                return(validateResult);
            }
#else
            bool           find = false;
            DirectoryEntry gc   = new DirectoryEntry("GC:", lowerUserId, password);

            DirectoryEntries directoryEntries = gc.Children;
            if (directoryEntries != null && directoryEntries.GetEnumerator() != null)
            {
                IEnumerator enumer = directoryEntries.GetEnumerator();
                if (enumer.MoveNext())
                {
                    gc   = (DirectoryEntry)enumer.Current;
                    find = true;
                }
            }

            if (find)
            {
                DirectorySearcher searcher = new DirectorySearcher
                {
                    SearchRoot = gc,
                    Filter     = string.Format("(&(objectClass=user)(sAMAccountName={0}))", lowerUserId)
                };
                SearchResult result = searcher.FindOne();
                if (result != null)
                {
                    validateResult = true;
                }
            }

            return(validateResult);
#endif
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Gets the collection of all groups on the local machine.
        /// </summary>
        /// <returns>The list of all groups.</returns>
        public virtual List <DirectoryEntry> GetAllGroupAccounts()
        {
            // Create a new directory entry
            // instance to the local machine.
            DirectoryEntry localMachine = new DirectoryEntry(
                "WinNT://" + _context.Name + ",computer");

            // Create a new list collection instance
            // of directory entries.
            List <DirectoryEntry> list = new List <DirectoryEntry>();

            // Get all the currrent accounts on the local machine.
            DirectoryEntries groups = localMachine.Children;

            // Get the enumerator of the account collection.
            System.Collections.IEnumerator col = groups.GetEnumerator();

            // For each account found.
            while (col.MoveNext())
            {
                // If the current schema class is 'group' then add
                // the entry to the collection, that is, if the current
                // account is of type 'group' then add to collection.
                if (((DirectoryEntry)col.Current).SchemaClassName.ToLower() == "group")
                {
                    list.Add((DirectoryEntry)col.Current);
                }
            }

            // Close the entry to the local machine.
            localMachine.Close();

            // Return the collection of groups.
            return(list);
        }
Ejemplo n.º 3
0
        protected static bool IsImageDirectory(string path)
        {
            bool hasImages = false;

            if (Directory.Exists(path))
            {
                var files = new DirectoryEntries(path, "*");
                using (var e = files.GetEnumerator())
                {
                    while (e.MoveNext())
                    {
                        var data = e.Current;
                        if (data.cFileName == "." || data.cFileName == "..")
                        {
                            continue;
                        }
                        string filepath = System.IO.Path.Combine(path, data.cFileName);
                        bool   isfolder = ((data.dwFileAttributes & FileAttributes.Directory) == FileAttributes.Directory);
                        string ext      = System.IO.Path.GetExtension(filepath);
                        if (!isfolder && IsImageFileExtension(ext))
                        {
                            hasImages = true;
                            break;
                        }
                    }
                }
            }
            return(hasImages);
        }
        public static VirtualWebDir FindLocalWebSite(string virtualDir)
        {
            DirectoryEntry site      = new DirectoryEntry(LocalWebPath);
            string         className = site.SchemaClassName.ToString();

            if ((className.EndsWith("Server", StringComparison.OrdinalIgnoreCase)) || (className.EndsWith("VirtualDir", StringComparison.OrdinalIgnoreCase)))
            {
                DirectoryEntries vdirs = site.Children;
                IEnumerator      ie    = vdirs.GetEnumerator();
                while (ie.MoveNext())
                {
                    DirectoryEntry de = ie.Current as DirectoryEntry;
                    if (de != null)
                    {
                        string sn = Path.GetFileName(de.Path);
                        if (string.Compare(virtualDir, sn, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            string dir = null;
                            PropertyValueCollection pv = de.Properties["Path"];
                            if (pv != null)
                            {
                                if (pv.Value != null)
                                {
                                    dir = pv.Value.ToString();
                                    VirtualWebDir vd = new VirtualWebDir(de.Path, dir);
                                    return(vd);
                                }
                            }
                        }
                    }
                }
            }
            return(null);
        }
        public static IList <VirtualWebDir> GetVirtualDirectories(string metabasePath)
        {
            List <VirtualWebDir> list = new List <VirtualWebDir>();
            DirectoryEntry       site = new DirectoryEntry(metabasePath);
            string className          = site.SchemaClassName.ToString();

            if ((className.EndsWith("Server", StringComparison.OrdinalIgnoreCase)) || (className.EndsWith("VirtualDir", StringComparison.OrdinalIgnoreCase)))
            {
                DirectoryEntries vdirs = site.Children;
                IEnumerator      ie    = vdirs.GetEnumerator();
                while (ie.MoveNext())
                {
                    DirectoryEntry de = ie.Current as DirectoryEntry;
                    if (de != null)
                    {
                        string dir = null;
                        PropertyValueCollection pv = de.Properties["Path"];
                        if (pv != null)
                        {
                            if (pv.Value != null)
                            {
                                dir = pv.Value.ToString();
                                VirtualWebDir vd = new VirtualWebDir(de.Path, dir);
                                list.Add(vd);
                            }
                        }
                    }
                }
            }
            return(list);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Enumerate children ADSI objects
        /// </summary>
        /// <param name="metabasePath"></param>
        static void EnumerateChildren(string metabasePath)
        {
            //  metabasePath is of the form "IIS://<servername>/<path>"
            //    for example "IIS://localhost/W3SVC/1/Root/MyVDir"
            //    or "IIS://localhost/W3SVC/AppPools/MyAppPool"
            Trace.WriteLine("\nEnumerating children for " + metabasePath);

            try
            {
                DirectoryEntry   entry    = new DirectoryEntry(metabasePath);
                DirectoryEntries children = entry.Children;

                System.Collections.IEnumerator enumerator = children.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    DirectoryEntry de = enumerator.Current as DirectoryEntry;
                    if (de != null)
                    {
                        Trace.WriteLine("\t" + de.Name);
                    }
                    de.Close();
                }
                entry.Close();

                Trace.WriteLine("-->Done.");
            }
            catch (Exception Ex)
            {
                Trace.WriteLine("Failed in EnumerateChildren with the following exception: " + Ex.Message);
            }
        }
        public static IEnumerator GetSites(string metabasePath)
        {
            DirectoryEntry site      = new DirectoryEntry(metabasePath);
            string         className = site.SchemaClassName.ToString();

            if ((className.EndsWith("Server", StringComparison.OrdinalIgnoreCase)) || (className.EndsWith("VirtualDir", StringComparison.OrdinalIgnoreCase)))
            {
                DirectoryEntries vdirs = site.Children;
                return(vdirs.GetEnumerator());
            }
            return(null);
        }
Ejemplo n.º 8
0
        protected override void Populate()
        {
            try
            {
                if (_pages == null)
                {
                    DirectoryEntries files = new DirectoryEntries(this.Path, "*");
                    var pages = new List <BblPage>();
                    using (FastDirectoryEnumerator fde = (FastDirectoryEnumerator)files.GetEnumerator())
                    {
                        while (fde.MoveNext())
                        {
                            _cancelPopulateTask.Token.ThrowIfCancellationRequested();

                            var data = fde.Current;
                            if ((data.dwFileAttributes & FileAttributes.Directory) == FileAttributes.Directory)
                            {
                                continue;
                            }
                            string path = System.IO.Path.Combine(Path, data.cFileName);
                            string ext  = System.IO.Path.GetExtension(path);
                            if (IsImageFileExtension(ext))
                            {
                                BblPage page = new BblPage(this);
                                page.Filename       = data.cFileName;
                                page.Path           = System.IO.Path.Combine(Path, data.cFileName);
                                page.Size           = data.Length;
                                page.CreationTime   = data.CreationTime;
                                page.LastAccessTime = data.LastAccessTime;
                                page.LastWriteTime  = data.LastWriteTime;


                                lock (_lock) { pages.Add(page); }
                            }
                        }
                    }
                    if (pages.Count == 0)
                    {
                        return;
                    }
                    pages.Sort();
                    lock (_lock) { _pages = new ObservableCollection <BblPage>(pages); }
                }
            }
            catch { UnPopulate(); }
        }
Ejemplo n.º 9
0
        // We will iterate over all principals under ctxBase, returning only those which are in the list of types and which
        // satisfy ALL the matching properties.
        internal SAMQuerySet(
            List <string> schemaTypes,
            DirectoryEntries entries,
            DirectoryEntry ctxBase,
            int sizeLimit,
            SAMStoreCtx storeCtx,
            SAMMatcher samMatcher)
        {
            GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMQuerySet", "SAMQuerySet: creating for path={0}, sizelimit={1}", ctxBase.Path, sizeLimit);

            _schemaTypes = schemaTypes;
            _entries     = entries;
            _sizeLimit   = sizeLimit;   // -1 == no limit
            _storeCtx    = storeCtx;
            _ctxBase     = ctxBase;
            _matcher     = samMatcher;

            _enumerator = _entries.GetEnumerator();
        }
Ejemplo n.º 10
0
        List <ADinfo> ReadChilds(string ID)
        {
            List <ADinfo>  Childs = new List <ADinfo>();
            DirectoryEntry AD;

            if (ID == "")
            {
                AD = new DirectoryEntry();
            }
            else
            {
                AD = new DirectoryEntry("LDAP://<GUID=" + ID + ">");
            }
            DirectoryEntries D = AD.Children;

            /*создаем курсор для чтения потомков*/

            System.Collections.IEnumerator Reed = D.GetEnumerator();

            /*обьявляем что будем использовать структуру*/

            ADinfo Param;

            /*Двигаем курсор на следующего потомка*/

            while (Reed.MoveNext())

            {
                /*получаем данные о ветке*/

                DirectoryEntry Info = Reed.Current as DirectoryEntry;

                Param.Name = Info.Name;            //сохраняем имя

                Param.GUID = Info.Guid.ToString(); //сохраняем номер

                /*сохраняем данные в список*/

                Childs.Add(Param);
            }

            return(Childs);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Get all the virtual applications on the iis host.
        /// </summary>
        /// <param name="iisHostPath">The iis host path.</param>
        /// <returns>Collection of entries with virtual applications.</returns>
        /// <example>
        /// iisHostPath : [servername]/[service]/[websiteID]/[Root] : localhost/W3SVC/1/Root
        /// </example>
        /// <remarks>
        /// <para>iisHostPath : [servername]/[service]/[websiteID]/[Root] : localhost/W3SVC/1/Root</para>
        /// </remarks>
        public virtual List <DirectoryEntry> GetAllVirtualApplications(string iisHostPath)
        {
            // Validate the inputs.
            if (String.IsNullOrEmpty(iisHostPath))
            {
                throw new System.ArgumentNullException("IIS path can not be null.",
                                                       new System.Exception("A valid IIS path should be specified."));
            }

            // Create a new directory entry
            // instance to the iis machine.
            DirectoryEntry localMachine = new DirectoryEntry(
                "IIS://" + iisHostPath);

            // Create a new list collection instance
            // of directory entries.
            List <DirectoryEntry> list = new List <DirectoryEntry>();

            // Get all the application pools.
            DirectoryEntries pools = localMachine.Children;

            // Get the enumerator of the account collection.
            System.Collections.IEnumerator col = pools.GetEnumerator();

            // For each account found.
            while (col.MoveNext())
            {
                // If the current schema class is 'IIsApplicationPool' then add
                // the entry to the collection, that is, if the current
                // account is of type 'IIsApplicationPool' then add to collection.
                if (((DirectoryEntry)col.Current).SchemaClassName.ToLower() == "IIsWebVirtualDir".ToLower())
                {
                    list.Add((DirectoryEntry)col.Current);
                }
            }

            // Close the entry to the local machine.
            localMachine.Close();

            // Return the collection of users.
            return(list);
        }
        /// <summary>
        /// Path property is the physical file path
        /// </summary>
        /// <param name="metabasePath"></param>
        /// <param name="vDirName"></param>
        /// <returns></returns>
        public static DirectoryEntry GetVDir(string metabasePath, string vDirName)
        {
            DirectoryEntry site      = new DirectoryEntry(metabasePath);
            string         className = site.SchemaClassName.ToString();

            if ((className.EndsWith("Server", StringComparison.OrdinalIgnoreCase)) || (className.EndsWith("VirtualDir", StringComparison.OrdinalIgnoreCase)))
            {
                string           path  = string.Format(CultureInfo.InvariantCulture, "{0}/{1}", metabasePath, vDirName);
                DirectoryEntries vdirs = site.Children;
                IEnumerator      ie    = vdirs.GetEnumerator();
                while (ie.MoveNext())
                {
                    DirectoryEntry de = ie.Current as DirectoryEntry;
                    if (de != null)
                    {
                        if (string.Compare(path, de.Path, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            return(de);
                        }
                    }
                }
            }
            return(null);
        }
Ejemplo n.º 13
0
 public IEnumerator GetEnumerator()
 {
     return(_directoryEntries.GetEnumerator());
 }
Ejemplo n.º 14
0
 public System.Collections.IEnumerator GetEnumerator()
 {
     return(_directoryEntries.GetEnumerator());
 }
Ejemplo n.º 15
0
        protected void EnumerateChildren()
        {
            DirectoryEntries files = new DirectoryEntries(this.Path, "*");

            if (Path == "D:\\pix\\mixes weekly\\Nouveau dossier")
            {
            }
            bool img = false;

            using (FastDirectoryEnumerator e = (FastDirectoryEnumerator)files.GetEnumerator())
            {
                while (e.MoveNext())
                {
                    var data = e.Current;
                    if (data.cFileName == "." || data.cFileName == "..")
                    {
                        continue;
                    }
                    string path = System.IO.Path.Combine(Path, data.cFileName);

                    bool   isfolder = ((data.dwFileAttributes & FileAttributes.Directory) == FileAttributes.Directory);
                    string ext      = System.IO.Path.GetExtension(path);
                    if (isfolder)
                    {
                        if (IsBblBookDirectoryExtension(ext))
                        {
                            AddChild(new BblBookDirectory(Root, this, data));
                        }
                        else
                        {
                            AddChild(new BblLibraryNode(Root, this, data));
                        }
                    }
                    else
                    {
                        if (!img && IsImageFileExtension(ext))
                        {
                            var lastWrite = data.LastWriteTime;
                            LastWriteTime = lastWrite;
                            if (!IsBook)
                            {
                                Root.AddPromotable(this);
                            }
                            img        = true;
                            FirstImage = path;
                        }
                        else if (IsArchiveFileExtension(ext))
                        {
                            AddChild(new BblBookArchive(Root, this, data));
                        }
                        else if (IsPDF(ext))
                        {
                            AddChild(new BblBookPdf(Root, this, data));
                        }
                    }
                }
            }
            if (!IsBook && IsFolder && (_children == null || _children.Count == 0))
            {
            }
        }
 public static VirtualWebDir FindLocalWebSiteByName(Form owner, string webName, out bool iisError)
 {
     iisError = false;
     using (ShowMessage frm = new ShowMessage(owner, "Checking web site name..."))
     {
         DirectoryEntry site      = new DirectoryEntry(LocalWebPath);
         string         className = string.Empty;
         try
         {
             className = site.SchemaClassName.ToString();
         }
         catch (Exception err)
         {
             StringBuilder sb = new StringBuilder();
             while (err != null)
             {
                 sb.Append("Error finding web site via Active Directory. Please install 'IIS6 Metabase compatibility' if it is not installed.\r\nError message:");
                 sb.Append(err.Message);
                 sb.Append("\r\nStack trace:");
                 if (!string.IsNullOrEmpty(err.StackTrace))
                 {
                     sb.Append(err.StackTrace);
                 }
                 sb.Append("===============\r\n");
                 err = err.InnerException;
             }
             MessageBox.Show(sb.ToString(), "Find web site", MessageBoxButtons.OK, MessageBoxIcon.Error);
             iisError = true;
             return(null);
         }
         if ((className.EndsWith("Server", StringComparison.OrdinalIgnoreCase)) || (className.EndsWith("VirtualDir", StringComparison.OrdinalIgnoreCase)))
         {
             DirectoryEntries vdirs = site.Children;
             IEnumerator      ie    = vdirs.GetEnumerator();
             while (ie.MoveNext())
             {
                 DirectoryEntry de = ie.Current as DirectoryEntry;
                 if (de != null)
                 {
                     if (string.Compare(de.Name, webName, StringComparison.OrdinalIgnoreCase) == 0)
                     {
                         string dir = null;
                         PropertyValueCollection pv = de.Properties["Path"];
                         if (pv != null)
                         {
                             if (pv.Value != null)
                             {
                                 dir = pv.Value.ToString();
                                 VirtualWebDir vd = new VirtualWebDir(de.Path, dir);
                                 return(vd);
                             }
                         }
                         else
                         {
                         }
                     }
                 }
             }
         }
     }
     return(null);
 }