Thursday, April 22, 2010

Directory Browser using Asp.Net

Demo:
Notes - Functionality:
  1. RootDirectory default to web application physical directory, using RootDirecotry property you can change it to any destination if you want
  2. Directory browser lists all the child directories starting from RootDiectory as a treeview
  3. When you click on any listed directory in the treeview it does a postback and show the directory full path in the text box at the top
  4. At the initial state text box get the value of root direcotry
Notes - Implementation:
  1. I have implemented direcotory browser as a custom web control. Inheriting WebControl  class and INamingContainer interface.
  2. Default property of this custom web control is DirecotryBrowser
  3. Default property of the directory browser is RootDirecotry
  4. SelectedDirectoryName is the output property that you can consume
  5. In the initializaton phase, control calls CreateControlHeirarchy method to create its controls
  6. Inside CreateControlHeirarchy it calls a method call AddChildDirectories which accepts two parameters, TreeNode and DirectoryInfo
  7. AddChildDirectories method lists all the child directories inside a given directory and then its call itslef recursively to list direcotries of child directories of the given directory
  8. Finally RenderBeginTag, and RenderEndTag wrap the control with <div> tag as my design team always prefer to have div around custom controls over default <span> tag (you would inherit Panel to get rid of this problem but I didnt)
Directory browser : asp.net 4.0
    [DefaultProperty("RootDirectory")]
    public class DirectoryBrowserField : WebField
    {
        #region Events
 
        public event EventHandler SelectedDirectoryChanged;
 
        #endregion
 
        #region Attributes
 
        TextBox txtDirectoryName = new TextBox();
        TreeView treeView = new TreeView();
        PlaceHolder contentPlaceHodler = new PlaceHolder();
        string baseDirecotry = string.Empty;
 
        #endregion
 
        #region Properties
 
        [DefaultValue("")]
        [Bindable(true)]
        public string RootDirectory { getset; }
 
        [DefaultValue("ActiveTextBoxCssClass")]
        [Bindable(true)]
        public string TextBoxCssClass { getset; }
 
        [DefaultValue("ActiveTreeViewCssClass")]
        [Bindable(true)]
        public string TreeViewCssClass { getset; }
 
        [DefaultValue("")]
        [Bindable(true)]
        public string SelectedDirectoryName { getset; }
 
        [DefaultValue(false)]
        [Bindable(true)]
        public bool ShowFullPath { getset; }
 
        #endregion
        
        #region Constructors
 
        public DirectoryBrowserField()
        {
            this.Initialize();
        }
 
        #endregion
 
        #region Methods
 
        private void Initialize()
        {
            this.baseDirecotry = HttpContext.Current.Server.MapPath("~\\");
            this.SelectedDirectoryName = this.RootDirectory = 
                HttpContext.Current.Request.PhysicalApplicationPath;
            this.TextBoxCssClass = "TextBox";
            this.TreeViewCssClass = "TreeView";
            this.CssClass = this.GetType().Name;
            this.ShowFullPath = false;
        }
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            if(!this.ChildControlsCreated)
                this.CreateControlHeirarchy();
        }
        public void CreateControlHeirarchy()
        {
            if(!this.RootDirectory.Contains(":\\"))
            {
                if (this.RootDirectory.StartsWith("~/"))
                    this.RootDirectory = 
                        this.RootDirectory.Replace("~/""~\\").Replace("/""\\");
                if (this.RootDirectory.StartsWith("/") || this.RootDirectory.StartsWith("\\"))
                    this.RootDirectory = 
                        string.Format("~{0}"this.RootDirectory.Replace("/""\\"));
                if (this.RootDirectory.StartsWith("~\\"))
                    this.RootDirectory = HttpContext.Current.Server.MapPath(this.RootDirectory);
            }
            if (Directory.Exists(this.RootDirectory))
            {
                this.txtDirectoryName.CssClass = this.TextBoxCssClass;
                this.SelectedDirectoryName = this.RootDirectory;
                this.txtDirectoryName.Text = this.ResolveDirecotry();
                this.contentPlaceHodler.Controls.Add(this.txtDirectoryName);
                treeView.CssClass = this.TreeViewCssClass;
                Panel panel = 
                    new Panel() { CssClass = string.Format("{0}Wrapper"this.TreeViewCssClass) };
                DirectoryInfo root =new DirectoryInfo(this.RootDirectory);
                TreeNode node = 
                    new TreeNode(string.Format(".\\{0}", root.Name), this.RootDirectory);
                treeView.Nodes.Add(node);
                this.AddChildDirectories(node, root);
                foreach (TreeNode n in node.ChildNodes) n.Collapse();
                treeView.SelectedNodeChanged += new EventHandler(SelectedNodeChanged);
                panel.Controls.Add(treeView);
                this.contentPlaceHodler.Controls.Add(panel);
                this.Controls.Add(contentPlaceHodler);
                this.ChildControlsCreated = true;
            }
        }
        private void SelectedNodeChanged(object sender, EventArgs e)
        {
            this.SelectedDirectoryName = this.treeView.SelectedNode.Value;
            this.txtDirectoryName.Text = this.ResolveDirecotry();
            if (this.SelectedDirectoryChanged != nullthis.SelectedDirectoryChanged(this, e);
        }
        private void AddChildDirectories(TreeNode node, DirectoryInfo direcotry)
        {
            foreach (DirectoryInfo child in direcotry.GetDirectories())
            {
                TreeNode childNode = new TreeNode(child.Name, child.FullName);
                node.ChildNodes.Add(childNode);
                if (child.GetDirectories().Count() > 0)
                    this.AddChildDirectories(childNode, child);
            }
        }
        private string ResolveDirecotry()
        {
            if (!this.ShowFullPath)
                return string.Format(".\\{0}",
                    this.SelectedDirectoryName.Replace(this.baseDirecotry, string.Empty));
            return this.RootDirectory;
        }
        protected override void RenderContents(HtmlTextWriter writer)
        {
            this.RenderFieldLabel(writer);
            StringBuilder sb = new StringBuilder();
            HtmlTextWriter htw = new HtmlTextWriter(new StringWriter(sb));
            contentPlaceHodler.RenderControl(htw);
            base.RenderFieldControl(writer,sb.ToString());
            this.RenderFieldValidator(writer);
        }
 
        #endregion
    }

Next steps
  1. Add a test page to your web project
  2. Add Register your control <%@ Register Assembly="Y" Namespace="X" TagPrefix="active" %>
  3. Utilise your control 
  4. <active:DirectoryBrowser runat="server" ID="dbSample" />
Using Direcotry Browser
        protected void Page_Load(object sender, EventArgs e)
        {
            this.dbfBrowse.SelectedDirectoryChanged += new EventHandler(dbfBrowse_SelectedDirectoryChanged);
        }
 
        void dbfBrowse_SelectedDirectoryChanged(object sender, EventArgs e)
        {
            DirectoryInfo d = new DirectoryInfo(this.dbfBrowse.SelectedDirectoryName);
            {
                foreach (FileInfo f in d.GetFiles())
                {
                    string ext = f.Extension.ToLower();
                    if (ext.Equals("txt") || ext.Equals("doc") || ext.Equals("pdf"))
                        lbxFiles.Items.Add(new ListItem(Path.GetFileName(f.Name), f.Name));
                }
            }
        }

Asp.net Forums

No comments:

Azure Storage Account Types

Defferent Types of Blobs Block blobs store text and binary data. Block blobs are made up of blocks of data that can be managed individually...