Search This Blog

Thursday, October 8, 2015

Treeview Visual Webpart For SharePoint 2010 & 2013 Document Libraries.


Here,  we have a custom tree view web part for SharePoint 2010 document libraries which is having the option to select the views in custom properties. Here we have only two views, one is for show only folder structure(will not show any files over there in that folder) and user based filtration of the document library(Only shows the folders or files which is created by the currently logged user). These above two custom properties can be set by the admin by checking the "Only Folder Structures" and "Related Login User" check boxes and the document library name can be put over there in the "Document Library Name" section in Custom settings of web part property window. Below images are showing the exact structure of the tree view with property section. This is a thoroughly tested and its working fine for my project.
Created Platform: Visual studio 2010, Sharepoint 2010 Foundation/Standard/Enterprise Versions.

Note:This is created based on the code from some other sites, but i have modified the codes as per my requirement.








Here is the code,

The ascx page contains the following code.

<asp:Label ID="lbl" runat="server" Text=""></asp:Label>
<div style="width:20%;text-align:left;">
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
<asp:UpdatePanel ID="updPnlMyDocsTreeView" runat="server">
    <ContentTemplate>
         <asp:TreeView ID="tvDocumentLibrary" runat="server" ShowExpandCollapse="true" ShowLines="true"
        ExpandDepth="1" NodeStyle-HorizontalPadding="3">
        </asp:TreeView>
    </ContentTemplate>
</asp:UpdatePanel>
</div>

 The code behind page contains the following.

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;

namespace MyDocsTreeView.MyDocsTreeView
{
    public partial class MyDocsTreeViewUserControl : UserControl
    {
        string documentLibrary = string.Empty;
        bool IsCurrentLoginUser;
        bool IsOnlyFoldersNeedShow;
        string _strCurrentUser = string.Empty;
        SPSite spSite = SPContext.Current.Site;
        SPWeb spWeb;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // Retriving the document library name from the custom web part property //
                RetrieveDocLibName();
            }
        }
        #region -- CUSTOM METHODS --

        private void RetrieveDocLibName()
        {
            try
            {
                MyDocsTreeView parent = (MyDocsTreeView)this.Parent;
                if (documentLibrary != null)
                {
                    documentLibrary = parent.DocumentLibrary;
                    IsCurrentLoginUser = parent._IsLoginUser;
                    IsOnlyFoldersNeedShow = parent._IsOnlyFolders;
                    SPSite site = SPContext.Current.Site;
                    spWeb = site.OpenWeb();
                    tvDocumentLibrary.Nodes.Clear();

                    // Creating an object of the document library //
                    SPDocumentLibrary spDocumentLibrary = (SPDocumentLibrary)spWeb.Lists[documentLibrary.Trim()];

                    // Creating an object of the root folder of the document library //
                    SPFolder spFolder = spDocumentLibrary.RootFolder;

                    // Creating the parent node of the tree view //
                    //TreeNode treeNodeRoot = new TreeNode(spFolder.Name.Trim(), spFolder.Name.Trim(), @"/_layouts/images/folder.gif", spFolder.ServerRelativeUrl.Trim(), "_blank");
                    TreeNode treeNodeRoot = new TreeNode(spFolder.Name.Trim(), spFolder.Name.Trim(), @"/_layouts/images/folder.gif");

                    // Calling the custom method to get all the folders //
                    GetAllFilesFolders(spFolder, treeNodeRoot, IsCurrentLoginUser, IsOnlyFoldersNeedShow);

                    // Adding the tree nodes to the tree view control //
                    tvDocumentLibrary.Nodes.Add(treeNodeRoot);
                }
                else
                {
                    lbl.Text = "Please mention a document library.";
                }
            }
            catch (Exception ex)
            {
                Label1.Text = ex.ToString();
            }

        }

        /// <summary>
        /// This custom menthod is used to get all the files and folders
        /// </summary>
        /// <param name="spFolder"></param>
        /// <param name="parentNode"></param>
        protected void GetAllFilesFolders(SPFolder spFolder, TreeNode parentNode, bool IsCheckCurrentUser, bool IsOnlyFoldersNeedShow)
        {
            SPQuery spQuery = new SPQuery();
            spQuery.Folder = spFolder;
            string strCurrentUserName = spWeb.CurrentUser.Name.ToString();
            if (IsOnlyFoldersNeedShow != true)
            {
                if (IsCheckCurrentUser == true)
                {
                    spQuery.Query = "<Where><Eq><FieldRef Name='Author' /><Value Type='User'>" + strCurrentUserName.ToString() + "</Value></Eq></Where><OrderBy><FieldRef Name='ID' Ascending='False' /></OrderBy>";
                    SPListItemCollection spListItemCollection = spWeb.Lists[spFolder.ParentListId].GetItems(spQuery);

                    foreach (SPListItem spListItem in spListItemCollection)
                    {
                        // Checking whether the item is a file or a folder //
                        if (spListItem.Folder != null)
                        {
                            SPSite site = SPContext.Current.Site;
                            spWeb = site.OpenWeb();

                            // Creating the node for the folder //
                            //TreeNode treeNodeChildFolder = new TreeNode(spListItem.Folder.Name.Trim(), Convert.ToString(spListItem.ID).Trim(), @"/_layouts/images/folder.gif", spListItem.Folder.ServerRelativeUrl.Trim(), "_blank");
                            TreeNode treeNodeChildFolder = new TreeNode(spListItem.Folder.Name.Trim(), Convert.ToString(spListItem.ID).Trim(), @"/_layouts/images/folder.gif");
                            parentNode.ChildNodes.Add(treeNodeChildFolder);

                            // Calling the custom method to get all the subfolder and files within the folder //
                            GetAllFilesFolders(spListItem.Folder, treeNodeChildFolder, true, false);
                        }
                        else
                        {
                            // Creating and object of the file //
                            SPFile spFile = spListItem.File;

                            // Setting the display URL of the file //
                            //string displayURL = SPContext.Current.Site.Url.Trim() + @"/" + spFile.Url.Trim();
                            string displayURL = spWeb.Url.Trim() + @"/" + spFile.Url.Trim();
                            // Setting the icon URL of the file //
                            string iconURL = spFile.IconUrl.Trim();
                            int y = iconURL.LastIndexOf("/") + 1;
                            iconURL = @"/_layouts/images/" + iconURL.Substring(y, iconURL.Length - y);

                            // Creating the node of the file //
                            TreeNode treeNodeChildFile = new TreeNode(spFile.Name.Trim(), spFile.Name.Trim(), iconURL.Trim(), displayURL.Trim(), "_blank");
                            parentNode.ChildNodes.Add(treeNodeChildFile);
                        }
                    }
                }
                else
                {
                    SPListItemCollection spListItemCollection = spWeb.Lists[spFolder.ParentListId].GetItems(spQuery);

                    foreach (SPListItem spListItem in spListItemCollection)
                    {
                        // Checking whether the item is a file or a folder //
                        if (spListItem.Folder != null)
                        {
                            // Creating the node for the folder //
                            //TreeNode treeNodeChildFolder = new TreeNode(spListItem.Folder.Name.Trim(), Convert.ToString(spListItem.ID).Trim(), @"/_layouts/images/folder.gif", spListItem.Folder.ServerRelativeUrl.Trim(), "_blank");
                            TreeNode treeNodeChildFolder = new TreeNode(spListItem.Folder.Name.Trim(), Convert.ToString(spListItem.ID).Trim(), @"/_layouts/images/folder.gif");
                            parentNode.ChildNodes.Add(treeNodeChildFolder);

                            // Calling the custom method to get all the subfolder and files within the folder //
                            GetAllFilesFolders(spListItem.Folder, treeNodeChildFolder, false, false);
                        }
                        else
                        {
                            // Creating and object of the file //
                            SPFile spFile = spListItem.File;

                            // Setting the display URL of the file //
                            string displayURL = spWeb.Url.Trim() + @"/" + spFile.Url.Trim();

                            // Setting the icon URL of the file //
                            string iconURL = spFile.IconUrl.Trim();
                            int y = iconURL.LastIndexOf("/") + 1;
                            iconURL = @"/_layouts/images/" + iconURL.Substring(y, iconURL.Length - y);

                            // Creating the node of the file //
                            TreeNode treeNodeChildFile = new TreeNode(spFile.Name.Trim(), spFile.Name.Trim(), iconURL.Trim(), displayURL.Trim(), "_blank");
                            parentNode.ChildNodes.Add(treeNodeChildFile);
                        }
                    }
                }
            }
            else // This section will be show only folder view...
            {
                if (IsCheckCurrentUser == true)
                {
                    spQuery.Query = "<Where><Eq><FieldRef Name='Author' /><Value Type='User'>" + strCurrentUserName.ToString() + "</Value></Eq></Where><OrderBy><FieldRef Name='ID' Ascending='False' /></OrderBy>";
                    SPListItemCollection spListItemCollection = spWeb.Lists[spFolder.ParentListId].GetItems(spQuery);

                    foreach (SPListItem spListItem in spListItemCollection)
                    {
                        // Checking whether the item is a file or a folder //
                        if (spListItem.Folder != null)
                        {
                            SPSite site = SPContext.Current.Site;
                            spWeb = site.OpenWeb();

                            // Creating the node for the folder //
                            //TreeNode treeNodeChildFolder = new TreeNode(spListItem.Folder.Name.Trim(), Convert.ToString(spListItem.ID).Trim(), @"/_layouts/images/folder.gif", spListItem.Folder.ServerRelativeUrl.Trim(), "_blank");
                            TreeNode treeNodeChildFolder = new TreeNode(spListItem.Folder.Name.Trim(), Convert.ToString(spListItem.ID).Trim(), @"/_layouts/images/folder.gif");
                            parentNode.ChildNodes.Add(treeNodeChildFolder);

                            // Calling the custom method to get all the subfolder and files within the folder //
                            GetAllFilesFolders(spListItem.Folder, treeNodeChildFolder, true, false);
                        }

                    }
                }
                else
                {
                    SPListItemCollection spListItemCollection = spWeb.Lists[spFolder.ParentListId].GetItems(spQuery);

                    foreach (SPListItem spListItem in spListItemCollection)
                    {
                        // Checking whether the item is a file or a folder //
                        if (spListItem.Folder != null)
                        {
                            // Creating the node for the folder //
                            //TreeNode treeNodeChildFolder = new TreeNode(spListItem.Folder.Name.Trim(), Convert.ToString(spListItem.ID).Trim(), @"/_layouts/images/folder.gif", spListItem.Folder.ServerRelativeUrl.Trim(), "_blank");
                            TreeNode treeNodeChildFolder = new TreeNode(spListItem.Folder.Name.Trim(), Convert.ToString(spListItem.ID).Trim(), @"/_layouts/images/folder.gif");
                            parentNode.ChildNodes.Add(treeNodeChildFolder);

                            // Calling the custom method to get all the subfolder and files within the folder //
                            GetAllFilesFolders(spListItem.Folder, treeNodeChildFolder, false, true);
                        }
                    }
                }
            }
        }
        #endregion
    }
}

The .cs page will contain the following code

using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace MyDocsTreeView.MyDocsTreeView
{
    [ToolboxItemAttribute(false)]
    public class MyDocsTreeView : WebPart
    {
        // Visual Studio might automatically update this path when you change the Visual Web Part project item.
        private const string _ascxPath = @"~/_CONTROLTEMPLATES/MyDocsTreeView/MyDocsTreeView/MyDocsTreeViewUserControl.ascx";
        /// <summary>
        /// 
        /// </summary>
        public MyDocsTreeView()
        {

        }
        /// <summary>
        /// 
        /// </summary>
        protected override void CreateChildControls()
        {
            Control control = Page.LoadControl(_ascxPath);
            Controls.Add(control);
        }

        /// <summary>
        /// To make custom settings in the webpart properties pane
        /// </summary>
        public string _DocumentLibrary;
        [Category("Custom Settings"),
        Personalizable(PersonalizationScope.Shared),
        WebBrowsable(true),

        WebDisplayName("Document Library Name"),
        WebDescription("Please specify the document library name")]
        public string DocumentLibrary
        {
            get { return _DocumentLibrary; }
            set { _DocumentLibrary = value; }
        }

        /// <summary>
        /// This custom property is for showing the tree view structure as only folder/ or with Folders/Files 
        /// </summary>
        public Boolean _IsOnlyFolders;
        [Category("Custom Settings"),
        Personalizable(PersonalizationScope.Shared),
        WebBrowsable(true),
        WebDisplayName("Only Folder structures"),
        WebDescription("Please check whether need only Folder structure or with files")]
        public Boolean IsOnlyFolders
        {
            get { return _IsOnlyFolders; }
            set { _IsOnlyFolders = value; }
        }

        /// <summary>
        /// This propery is to show the documents in the tree view according to the currently
        /// logged user.
        /// </summary>
        public Boolean _IsLoginUser;
        [Category("Custom Settings"),
        Personalizable(PersonalizationScope.Shared),
        WebBrowsable(true),
        WebDisplayName("Related Login user"),
        WebDescription("Please specify the documents related to current login user")]
        public Boolean IsLoginUser
        {
            get { return _IsLoginUser; }
            set { _IsLoginUser = value; }
        }
    }
}


No comments:

Post a Comment