Thursday 29 May 2014

SPSiteDataQuery on Lists

I had a requirement to perform SPSiteDataQuery on Workflow History lists.
I had to query the data for a certain time period.

After struggling for a long time ,I realized that I have to provide field ID instead of the field name.

Kindly find the code snippet below which query last 7 days items from workflow history list and stores it in a Data table.


SPSiteDataQuery workflowHistoryQuery = new SPSiteDataQuery();
workflowHistoryQuery.Lists = "<Lists ServerTemplate='140'  Hidden='TRUE'/>";
workflowHistoryQuery.ViewFields = "<FieldRef Name='Description' Nullable='TRUE'/><FieldRef                Name='List' Nullable='TRUE'/><FieldRef Name='Item' Nullable='TRUE'/><FieldRef Name='Created'        Type='DateTime'/>";
 workflowHistoryQuery.Webs = "<Webs Scope='SiteCollection' />";
string createdDateID = SPBuiltInFieldId.Created.ToString("B");
string endDate = DateTime.Today.AddDays(-7).ToString("yyyy-MM-dd");
workflowHistoryQuery.Query = "<Where><Gt>";
workflowHistoryQuery.Query += "<FieldRef ID=\"" + createdDateID + "\" />";
workflowHistoryQuery.Query += "<Value Type=\"DateTime\">" + endDate + " </Value>";
workflowHistoryQuery.Query += "</Gt></Where>";
DataTable workflowResult = SPContext.Current.Site.RootWeb.GetSiteData(workflowHistoryQuery);



Reference SPSiteDataQuery

Hope it Helps.

Tuesday 6 May 2014

Sharepoint Sub Site BackUp

Here comes my second post related to deployment.

There are times when we have to take Back up of  environment.So what are the possible options for taking Back up.
Sharepoint Central Admin provides us the following two option to take Back up
1)Farm Back up
2)Granular Back up:This can be used if we need to take back up of specific site collection.All we have to do is select the web app and then select the required site collection.Provide the File location where the back up files can be created.
Pretty easy.Isn't it.

Problem comes when we have to take a back up one level down the site collection as well.
How can we take back up of Sub Sites???

Unluckily Sharepoint doesn't provide any UI interface to do it.But that doesn't mean that we can't do it.Thanks to Powershell for making our life easy.

So All we need to do is Run the following powershell command to take back up and restore it.

Export-spweb –identity http://site/subsite -path c:\subsitebkup\subsite.bak

Import-SPWeb –identity http://site/subsite -path c:\subsitebkup\subsite.bak

Friday 25 April 2014

Retrieve WSP from Sharepoint CentralAdmin

I am a sharepoint devloper,but there are times when I have to jump into deployment activity and obviously I have to struggle even to do simple things.So recently my requirement was to get a wsp from one server and deploy it to another server.Sounds very simple but It wasn't for me unless I found the right way to do it.So thanks to powershell which helped me with it.Here is what  I did

So all you you need to do is open the Powershell and run the following command in order to get the WSP file.

$myFarm = Get-SPFarm
$myWSP = $myFarm.Solutions.Item(“mywsp.wsp”).SolutionFile
$myWSP.SaveAs(“C:\wspFolder\mywsp.wsp”)

This simple piece of command will get you the WSP File.and if you don't want to use powershell and love writing code then write following pience of code on a button click or execute it the way  you want it to work.

void getWSP_Click(object sender, EventArgs e)
        {
            SPSolutionCollection allSolutions = SPFarm.Local.Solutions;
            foreach (SPSolution solution in allSolutions)
            {
                SPPersistedFile wsp= solution.SolutionFile;
                if (wsp.Name == "mywsp.wsp")
                {
                    wsp.SaveAs("c:\\wspFolder\\" + solution.Name);
                }
            }
        }

Thanks for Reading and Hope this works for you.

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 :-)

Wednesday 9 October 2013

Tree View Instead of QuickLaunch in Sharepoint

There is a Tree View Option built into SharePoint Online ,In order to Enable it do the following Actions

1.Click on Site Actions -> Site Settings
2. Click on "Tree View" under "Look and Feel"
3. Remove the check from Enable Quick Launch and put the check in Enable Tree View.

Once you navigate back to the root site after confirmation you will see that the tree view instead of quick launch.


Tuesday 18 December 2012

RowNumber for JQgrid


In order to set  rowNumber for JQgrid

  • rownumbers is to be set as true
  • rownumWidth can be set for width  customization of the rowNumber field


By default this column gets added as left most field in grid .Thie following code snippet can be  modified to set the rowNumbers at certain position.
Slice method can be used to achieve it.
if(this.p.rownumbers)
{
this.p.colNames.unshift("");
this.p.colModel.unshit({name:'rn',width:ts.p.rownumWidth,sortable:false,resizable:false,hidedlg:true,search:false,align:'center',fixed:true});
}