Sunday 5 January 2014

Tree View Web Part for a Document Library

TREEVIEW VISUAL WEBPART FOR DOCUMENT LIBRARIES.


One of my client had a requirement to create a Tree view webPart as there were a number of documents and Folder in there Document Library.The option to select the views should be defined in custom properties which are  following
1)show only folder structure(will not show any files over there in that folder)
2)Show All files and Folder

These above two custom properties along with the Document Library Name can be set by the admin by checking the "Only Folder Structures" and DocumentLibrary Name section in Custom settings of web part property window. 

In order to Implement it,I created two classes.
ToolPart and the WebPart Classes.
Code as shown below.

1.Class TreeViewToolPart 

using System;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;
namespace TreeViewWebPart
{
    class TreeViewToolPart : ToolPart
    {
        #region constant
        public const string d_documentLibraryLabel = "Document Library";
        public const string d_isFolderLabel = "Show folders only";
        #endregion
        #region Controls
        DropDownList dropdownList;
        CheckBox isFolderCheckBox;
        #endregion
        #region overriden methods
        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            //Create Label
            Label label = new Label();
            label.ID = "label";
            label.Text = d_documentLibraryLabel;
            //Create dropdown
            dropdownList = new DropDownList();
            dropdownList.ID = "dropdownList";
            //Getting the lists of the current web, and adding them in the dropdown-list.
            SPListCollection docLibraryColl = SPContext.Current.Web.GetListsOfType(SPBaseType.DocumentLibrary);
            foreach (SPList list in docLibraryColl)
            {
                dropdownList.Items.Add(list.Title);
            }
            //Add label and dropdown
            Controls.Add(label);
            Controls.Add(dropdownList);

            label = new Label();
            label.ID = "isFolderOnly";
            label.Text = "</br>" + d_isFolderLabel;
            //Create CheckBox
            isFolderCheckBox = new CheckBox();
            isFolderCheckBox.ID = "isFolderCheckBox";
            Controls.Add(label);
            Controls.Add(isFolderCheckBox);
            TreeViewWebPart treeView = (TreeViewWebPart)this.ParentToolPane.SelectedWebPart;
            //Assingning thr values to the toolpart
            if (treeView != null)
            {
                this.dropdownList.SelectedValue = treeView.DocumentLibraryName;
                this.isFolderCheckBox.Checked = treeView.IsFolderOnly;
            }
        }
        #endregion
        /// <summary>
        /// Apply the Changes in the WebPart
        /// Assign the SelectedValue as DocumentLibrary Name
        /// </summary>
        public override void ApplyChanges()
        {
            TreeViewWebPart treeView = (TreeViewWebPart)this.ParentToolPane.SelectedWebPart;
            treeView.DocumentLibraryName = dropdownList.SelectedValue;
            treeView.IsFolderOnly = isFolderCheckBox.Checked;
        }
    }
}

2.WebPart Class

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


namespace TreeViewWebPart
{
    [ToolboxItemAttribute(false)]
    public partial class TreeViewWebPart : Microsoft.SharePoint.WebPartPages.WebPart
    {
        //[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Assert, UnmanagedCode = true)]
        TreeView treeView;
        TreeNode rootNode;
        #region member variable
        private string m_ToolPartTitle = "Tree View Settings";
        private string m_libraryName = String.Empty;
        private Boolean m_isFolderOnly = false;
        #endregion
        #region constructor
        public TreeViewWebPart()
        {
        }
        #endregion
        #region properties
        /// <summary>
        /// DocumentLibarary Name of Which the items has to appear
        /// </summary>
        [WebBrowsable(true)]
        [Personalizable(PersonalizationScope.Shared)]
        public string DocumentLibraryName
        {
            get
            {
                return m_libraryName;
            }
            set
            {
                m_libraryName = value;
            }
        }
        /// <summary>
        /// IsFolder property which signifies only folder to be shown while loading
        /// </summary>
        [WebBrowsable(true)]
        [Personalizable(PersonalizationScope.Shared)]
        public Boolean IsFolderOnly
        {
            get
            {
                return m_isFolderOnly;
            }
            set
            {
                m_isFolderOnly = value;
            }
        }
        #endregion properties
        /// <summary>
        /// Oveeriden GetToolParts method
        /// Adding the customToolPart for the Webaprt
        /// </summary>
        /// <returns></returns>
        public override ToolPart[] GetToolParts()
        {
            ToolPart[] toolParts = new ToolPart[2];
            WebPartToolPart standardToolParts = new WebPartToolPart();
            TreeViewToolPart customToolParts = new TreeViewToolPart();
            customToolParts.Title = m_ToolPartTitle;
            toolParts[0] = standardToolParts;
            toolParts[1] = customToolParts;
            return toolParts;
        }
        /// <summary>
        /// Overriden OnInit
        /// </summary>
        /// <param name="e"></param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            InitializeControl();
        }
        /// <summary>
        /// Overriden Page Load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        /// <summary>
        ///Overriden Render Contents
        /// </summary>
        /// <param name="writer"></param>
        protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)
        {
            base.RenderContents(writer);
        }
        /// <summary>
        /// Overriden Create Child Control
        /// Creating a TreeView and adding items to it
        /// </summary>
        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            GetToolParts();
            //Get the current site
            SPSite currentSite = SPContext.Current.Site;
            using (SPWeb currentWeb = currentSite.OpenWeb())
            {
                //Set the tree view properties
                treeView = new System.Web.UI.WebControls.TreeView();
                treeView.ShowLines = true; // show lines
                treeView.ExpandDepth = 1; // expand first level 
                //Sanity check that DocumentLibraryName is set
                if (!string.IsNullOrEmpty(DocumentLibraryName))
                {
                    SPList list = SPContext.Current.Web.Lists[DocumentLibraryName];
                    // build the tree and adding the Document Library as the Root Node
                    rootNode = new System.Web.UI.WebControls.TreeNode(list.Title, "", "", list.RootFolder.ServerRelativeUrl.ToString(), "");
                    // Loop down the tree
                    GetAllFilesFolders(list.RootFolder, rootNode, true, IsFolderOnly);
                    // Add the root node to tree view
                    treeView.Nodes.Add(rootNode);
                }
                this.Controls.Add(treeView);
            }
            base.CreateChildControls();
        }
        /// <summary>
        /// Gets All the File Folders Details recursively and add it to the tree
        /// </summary>
        /// <param name="spFolder"></param>
        /// <param name="parentNode"></param>
        /// <param name="IsCheckCurrentUser"></param>
        /// <param name="IsOnlyFoldersNeedShow"></param>
        protected void GetAllFilesFolders(SPFolder spFolder, TreeNode parentNode, bool isCurrentUser, bool isFolderOnly)
        {
            SPWeb spWeb = SPContext.Current.Web;
            SPQuery spQuery = new SPQuery();
            spQuery.Folder = spFolder;
            string strCurrentUserName = spWeb.CurrentUser.Name.ToString();
            //Display files and folders as isFolder is set to false
            if (isFolderOnly != true)
            {
                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");
                        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);
                    }
                }
            }
            //Display only folders as isFolder is set to true
            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");
                        //Adding folder to the node
                        parentNode.ChildNodes.Add(treeNodeChildFolder);
                        // Calling the custom method to get all the subfolder and files within the folder //
                        GetAllFilesFolders(spListItem.Folder, treeNodeChildFolder, false, true);
                    }
                }
            }
        }
    }
}


Hope this helps and save your time. :-)

Table View from Content Query Web Part.

The Content Query web Part displays results in bullet lists by default.

There are times when we have to display results in Blocks or in a table.I too had the same requirement and after struggling for few days implemented it with following steps.


There are two xsl files which should be modified for it.
  1. ItemStyle.Xsl
  2. ContentQuerymain.xsl
There are 3 Changes in ContentQuerymain which  are as following

Step1Add this parameters where OuterTemplate.CallItemTemplate is called.
 <xsl:with-param name="LastRow" select="$LastRow" />
The final op is shown below
<xsl:call-template name="OuterTemplate.CallItemTemplate">
                    <xsl:with-param name="CurPosition" select="$CurPosition" />
                      <xsl:with-param name="LastRow" select="$LastRow" />
                </xsl:call-template>

Step2

Add this parameterto OuterTemplate.CallItemTemplate in order to receive the new parameter value. 

<xsl:param name="LastRow" />

Final op is as shown below


 <xsl:template name="OuterTemplate.CallItemTemplate">
    <xsl:param name="CurPosition" />
    <xsl:param name="LastRow" />

Step 3

Now,add the following block to the OuterTemplate.CallItemTemplate template just before the otherwise block at line position in order to call our customized template

<xsl:when test="@Style='BlockTemplate'">
  <xsl:apply-templates select="." mode="itemstyle">
    <xsl:with-param name="CurPos" select="$CurPosition" />
    <xsl:with-param name="LastRow" select="$LastRow" />
  </xsl:apply-templates>
</xsl:when>

Step4 

In ItemStyle.xsl. add this Template

<!--AddressList Template which displays data in a table-->

  <xsl:template name="BlockTemplate" match="Row[@Style='BlockTemplate']" mode="itemstyle">

    <xsl:param name="CurPos" />

    <xsl:param name="LastRow" />


    <xsl:variable name="DisplayTitle">

      <xsl:call-template name="OuterTemplate.GetTitle">

        <xsl:with-param name="Title" select="@Title"/>

        <xsl:with-param name="UrlColumnName" select="'LinkUrl'"/>

      </xsl:call-template>

    </xsl:variable>


    <xsl:if test="$CurPos = 1 ">

      <xsl:text disable-output-escaping="yes">&lt;div&gt;&lt;table&gt;</xsl:text>

    </xsl:if>

    <xsl:if test="$CurPos mod 2 = 1">

      <xsl:text disable-output-escaping="yes">&lt;tr&gt;</xsl:text>

    </xsl:if>



    <td width="50%" valign="top">

      <table width="100%" border="1" class="BlockTemplatetable">

        <tr height="27px" valign="top">

          <!--Columns from which values are fetched ,add columnnames as per your requirement-->

          <td>

            <span>

              <xsl:value-of select="@Title"/>

              <br/>

              <xsl:value-of select="@EmailAdress"/>

              <br/>

            </span>

          </td>

        </tr>

      </table>

    </td>

    <xsl:if test="$CurPos mod 2 = 0">

      <xsl:text disable-output-escaping="yes">&lt;/tr&gt;</xsl:text>

    </xsl:if>

    <xsl:if test="$CurPos = $LastRow ">

      <xsl:text disable-output-escaping="yes">&lt;/table&gt;&lt;/div&gt;</xsl:text>

    </xsl:if>

  </xsl:template>



Hope this posts save your lots of time and you are able to implement it successfully.Thanks :-)