Sunday, March 31, 2013

Displaying Subsites as per the Access


Hi,

Last week I got a new task i.e. in the web part it should display all the sub sites under the site collection.
If user has an access to the sub site, then it should display only Site Name, description and
If user hasn't got access to the site, then it should display only Site Name, description along with ‘Request To Join’ as below

If user clicks ‘Request To Join’ button, email has to be triggered to User group ‘Key Contacts’ members and maiBody,subject should be fetched from ‘EmailConfigurations’ list.
In that list, there will be column name as ‘Community Site Request To Join’
Mail Body, Mail Subject details should be fetched from the row as below
Below is the code that has been written to achieve this functionality
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data;
using System.Globalization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;
using System.Diagnostics;
using System.Text;
using System.Collections;
using System.Configuration;
using System.Data;
using System.IO;
using System.Web;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.Collections.Specialized;
 namespace DataListSample.VisualWebPart1
{
    public partial class VisualWebPart1UserControl : UserControl
    {
        #region  Variables
        PagedDataSource PageDataSource= new PagedDataSource();
        private DataTable dTableAllSites;
        private DataTable dTableMatchingSites;
        #endregion       

        #region Private Properties
        private int CurrentPage
        {
            get
            {
                object objPage = ViewState["_CurrentPage"];
                int _CurrentPage = 0;
                if (objPage == null)
                {
                    _CurrentPage = 0;
                }
                else
                {
                    _CurrentPage = (int)objPage;
                }
                return _CurrentPage;
            }
            set { ViewState["_CurrentPage"] = value; }
        }

        private int firstIndex
        {
            get
            {

                int _FirstIndex = 0;
                if (ViewState["_FirstIndex"] == null)
                {
                    _FirstIndex = 0;
                }
                else
                {
                    _FirstIndex = Convert.ToInt32(ViewState["_FirstIndex"]);
                }
                return _FirstIndex;
            }
            set { ViewState["_FirstIndex"] = value; }
        }

        private int lastIndex
        {
            get
            {

                int _LastIndex = 0;
                if (ViewState["_LastIndex"] == null)
                {
                    _LastIndex = 0;
                }
                else
                {
                    _LastIndex = Convert.ToInt32(ViewState["_LastIndex"]);
                }
                return _LastIndex;
            }
            set { ViewState["_LastIndex"] = value; }
        }
       

        #region Private Methods
        /// <summary>
        /// Build DataTable to bind Main Items List
        /// </summary>
        /// <returns>DataTable</returns>
        private DataTable GetTable()
        {
            dTableAllSites = new DataTable();
            dTableAllSites.Locale = CultureInfo.InvariantCulture;
            dTableAllSites.Columns.Add("SiteName"typeof(string));
            dTableAllSites.Columns.Add("Description"typeof(string));
            dTableAllSites.Columns.Add("Url"typeof(string));
            dTableAllSites.Columns.Add("RequestAccess"typeof(bool));
            return dTableAllSites;
        }

        private DataTable GetTableForSearch()
        {
            dTableMatchingSites = new DataTable();
            dTableMatchingSites.Locale = CultureInfo.InvariantCulture;
            dTableMatchingSites.Columns.Add("SiteName"typeof(string));
            dTableMatchingSites.Columns.Add("Description"typeof(string));
            dTableMatchingSites.Columns.Add("Url"typeof(string));
            dTableMatchingSites.Columns.Add("RequestAccess"typeof(bool));
            return dTableMatchingSites;
        }
    #endregion

        /// <summary>
        /// Binding Main Items List
        /// </summary>
        private void BindItemsList()
        {
            dTableAllSites = GetSites();

            dListItems.DataSource = dTableAllSites;
            dListItems.DataBind();


            PageDataSource.DataSource = dTableAllSites.DefaultView;
            PageDataSource.AllowPaging = true;
            PageDataSource.PageSize = 10;
            PageDataSource.CurrentPageIndex = CurrentPage;
            ViewState["TotalPages"] = PageDataSource.PageCount;

            this.lblPageInfo.Text = (CurrentPage + 1) + " | " + PageDataSource.PageCount;
            this.lbtnPrevious.Enabled = !PageDataSource.IsFirstPage;
            this.lbtnNext.Enabled = !PageDataSource.IsLastPage;


            this.dListItems.DataSource = PageDataSource;
            this.dListItems.DataBind();
            this.doPaging();
        }

        /// <summary>
        /// Binding Paging List
        /// </summary>
        private void doPaging()
        {
            DataTable dtPaging = new DataTable();
            dtPaging.Columns.Add("PageIndex");
            dtPaging.Columns.Add("PageText");

            firstIndex = CurrentPage - 5;

            if (CurrentPage > 5)
            {
                lastIndex = CurrentPage + 5;
            }
            else
            {
                lastIndex = 10;
            }
            if (lastIndex > Convert.ToInt32(ViewState["TotalPages"]))
            {
                lastIndex = Convert.ToInt32(ViewState["TotalPages"]);
                firstIndex = lastIndex - 10;
            }

            if (firstIndex < 0)
            {
                firstIndex = 0;
            }

            for (int i = firstIndex; i < lastIndex; i++)
            {
                DataRow dr = dtPaging.NewRow();
                dr[0] = i;
                dr[1] = i + 1;
                dtPaging.Rows.Add(dr);
            }

            this.dlPaging.DataSource = dtPaging;
            this.dlPaging.DataBind();
        }     


      

        private DataTable GetSites()
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {               
                using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                {
                    using (SPWeb oWebsite = site.OpenWeb())
                    {  
                        dTableAllSites = GetTable();

                        foreach (SPWeb subSite in oWebsite.Webs)
                        {
                            DataRow dtRow = null;

                            dtRow = dTableAllSites.NewRow();
                            if (subSite.Title != null)
                            {
                                dtRow["SiteName"] = Convert.ToString(subSite.Title);
                            }
                            if (subSite.Description != null)
                            {
                                dtRow["Description"] = Convert.ToString(subSite.Description);
                            }
                            if (subSite.Url != null)
                            {
                                dtRow["Url"] = Convert.ToString(subSite.Url);
                            }
                            if (subSite.DoesUserHavePermissions(SPContext.Current.Web.CurrentUser.LoginName,SPBasePermissions.Open) == true)
                            {
                                dtRow["RequestAccess"] = false;
                            }
                            else
                            {
                                dtRow["RequestAccess"] = true;
                            }
                            dTableAllSites.Rows.Add(dtRow);
                        }
                    }
                }
            });

            dTableAllSites.AcceptChanges();

            return dTableAllSites;

        }

        private DataTable GetMatchingSites()
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
               

                using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                {
                    using (SPWeb oWebsite = site.OpenWeb())
                    {
                        dTableMatchingSites = GetTableForSearch();

                        foreach (SPWeb subSite in oWebsite.Webs)
                        {
                            DataRow dtRow = null;
                                                       
                            if ((subSite.Title.ToLower()).Contains(txtSites.Text.ToLower()))
                            {
                                dtRow = dTableMatchingSites.NewRow();

                                dtRow["SiteName"] = Convert.ToString(subSite.Title);
                                dtRow["Description"] = Convert.ToString(subSite.Description);
                                dtRow["Url"] = Convert.ToString(subSite.Url);
                                if (subSite.DoesUserHavePermissions(SPContext.Current.Web.CurrentUser.LoginName,SPBasePermissions.Open) == true)
                                {
                                    dtRow["RequestAccess"] = false;
                                }
                                else
                                {
                                    dtRow["RequestAccess"] = true;
                                }
                                dTableMatchingSites.Rows.Add(dtRow);
                            }                           
                        }

                    }
                }
            });

            dTableMatchingSites.AcceptChanges();

            return dTableMatchingSites;
        }
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {


            if (!IsPostBack)
            {
                BindItemsList();


            }

        }

        protected void ImgSearch_Click(object sender, ImageClickEventArgs e)
        {
            dTableMatchingSites = GetMatchingSites();
            dListItems.DataSource = dTableMatchingSites;
            dListItems.DataBind();
        }             

        protected void lbtnNext_Click(object sender, EventArgs e)
        {
            CurrentPage += 1;
            this.BindItemsList();
        }

        protected void lbtnPrevious_Click(object sender, EventArgs e)
        {
            CurrentPage -= 1;
            this.BindItemsList();
        }
        protected void lbtnRequestToJoin_Click(object sender, EventArgs e)
        {
            using (SPSite site = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPGroup grp = web.SiteGroups["KeyContacts"];
                    {
                        foreach (SPUser user in grp.Users)
                        {
                            SPList objlist = web.Lists["EmailConfigurations"];
                           
                            foreach (SPListItem item in objlist.Items)
                            {
                                
                                if (item["ComponentName"].ToString() == "Community Site Request To Join")
                                {
                                StringDictionary headers = new StringDictionary();
                                headers.Add("To", user.Email);
                                headers.Add("subject", item["EmailSubject"].ToString());                              

                                System.Text.StringBuilder strMessage = new System.Text.StringBuilder();                               
                                strMessage.Append(item["EmailBody"].ToString());
                                SPUtility.SendEmail(web, headers, strMessage.ToString());
                                }
                            }
                        }
                    }
                }
            }

        }     

      

    }
}


Testing
Coming to testing part,before testing below steps have been followed to view the result
1.       User id needs to be added as site collection administrator
2.       User id needs to be added in the ‘Owner’ group of the site collection
3.       In all the subsites ‘Stop inheriting permissions’ have been removed all groups have been removed by ‘Remove permissions’
4.       In some subsites User id has been added by providing ‘Full Control’
5.       User id has been removed as administrator of the site collection and web part has been added to site collection page



Sunday, March 17, 2013

Search Results to Excel WebPart


Hi,

There was a requirement i.e. when user searches something by entering the keyword, he will be getting the search results.
He should be able to export those search results to excel. Front end was something as below
Approach:
After entering the keyword in the search field, his entered keyword will sit as Query String (k=)as below
And there will be a page called OSSSearchResults.aspx, where search results will be displayed to the user as below
There is SharePoint object KeywordQuery where we can retrieve the search results through Query String  (k=)
if we don’t specify the particular fields that we want to retrieve as below
Then it will retrieve some default properties like WorkID, Site Name, Path etc
But if we want to retrieve the particular fields, then we have specify the properties as below

   objkeywordquery.SelectProperties.Add("Title");
            objkeywordquery.SelectProperties.Add("Path");
            objkeywordquery.SelectProperties.Add("Description");
            objkeywordquery.SelectProperties.Add("Size");
            objkeywordquery.SelectProperties.Add("Write");
            objkeywordquery.SelectProperties.Add("Author");
Below is the whole code that has been written to retrieve the search results

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

using System.Collections;

using System.Configuration;
using Microsoft.Office.Server;
using Microsoft.Office.Server.Search;
using Microsoft.Office.Server.Search.Query;
using Microsoft.Office.Server.Search.Administration;

using System.Data;
using Microsoft.SharePoint;


namespace SearchResultsToExcel.VisualWebPart1
{
    public partial class VisualWebPart1UserControl : UserControl
    {
       
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

            }
        }




        /// <summary>
        /// get query result by user
        /// </summary>
        /// <param name="siteCollectionConfig"></param>
        /// <param name="ssa"></param>
        /// <param name="strQuery"></param>
        /// <returns></returns>
        public DataTable getResult(string siteCollectionConfig, string ssa, string strQuery)
        {

            SPSite site = SPContext.Current.Site;
            KeywordQuery objkeywordquery = new KeywordQuery(site);
            objkeywordquery.QueryText = strQuery;
            objkeywordquery.SelectProperties.Add("Title");
            objkeywordquery.SelectProperties.Add("Path");
            objkeywordquery.SelectProperties.Add("Description");
            objkeywordquery.SelectProperties.Add("Size");
            objkeywordquery.SelectProperties.Add("Write");
            objkeywordquery.SelectProperties.Add("Author");


            objkeywordquery.ResultsProvider = SearchProvider.Default;
            objkeywordquery.ResultTypes = ResultType.RelevantResults;

            ResultTableCollection queryResults = objkeywordquery.Execute();
            ResultTable queryResultsTable = queryResults[ResultType.RelevantResults];

            DataTable queryDataTable = new DataTable();

            queryDataTable.Load(queryResultsTable, LoadOption.OverwriteChanges);

            return queryDataTable;


        }

        public void printXls(DataTable dt)
        {
            System.Web.UI.WebControls.DataGrid dgExport = null;
            System.Web.HttpContext curContext = System.Web.HttpContext.Current;
            System.IO.StringWriter strWriter = null;
            System.Web.UI.HtmlTextWriter htmlWriter = null;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    string temp = dt.Rows[i][j].ToString();
                    bool flag = false;
                    while (temp.IndexOf("\n") != -1)
                    {
                        temp = temp.Replace("\n""  ");
                        flag = true;
                    }
                    if (flag)
                        dt.Rows[i][j] = temp;
                }
            }
            if (dt != null)
            {
                curContext.Response.ContentType = "application/vnd.ms-excel";
                curContext.Response.ContentEncoding = System.Text.Encoding.Default;
                curContext.Response.Charset = "gb2312";
                curContext.Response.Write("<meta http-equiv=Content-Type content=text/html;charset=gb2312>");
                curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");

                curContext.Response.AppendHeader("content-disposition""attachment;filename=\"" + System.Web.HttpUtility.UrlEncode("temp.xls", System.Text.Encoding.UTF8));
                strWriter = new System.IO.StringWriter();
                htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);


                dgExport = new System.Web.UI.WebControls.DataGrid();
                dgExport.DataSource = dt.DefaultView;
                dgExport.AllowPaging = false;
                dgExport.DataBind();


                dgExport.RenderControl(htmlWriter);
                curContext.Response.Write(strWriter.ToString());
                curContext.Response.End();
            }
        }


        protected void btnExportToExcel_Click(object sender, EventArgs e)
        {
            DataTable dt = getResult("""SearchQuerySSA", Request.QueryString.Get("k").ToString());          

            System.Data.DataColumn newColumn = new System.Data.DataColumn("Creator"typeof(System.String));
            dt.Columns.Add(newColumn);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
              

                if (dt.Rows[i]["Author"] != DBNull.Value)
                {
                   
                    dt.Rows[i]["Creator"] = ((string[])dt.Rows[i]["Author"])[0];                


                }

            }


            dt.AcceptChanges();
            printXls(dt);


        }

    }
}


Issues
Of course definitely there will be so many issue while developing.
Major issue was Author values were not coming in the excel sheet, through debug mode it has been noticed that Author values were coming in the format System.string[]/DBNull.Value
So through for loop i changed those values to string format as below, added one more column to the data table and got the values

dt.Rows[i]["Creator"] = ((string[])dt.Rows[i]["Author"])[0];  

Result
Finally I got the result as below
Deployment
First I added this web part to one of the aspx page in the site.
I opened that page through SharePoint designer.
I copied the Register Tag, web part zone tag of this web part that were available on this page as below

 So that when user enters keyword, based upon the entered keyword, web part can get this through Request string and get the Search Results to export Excel