The webpart is developed to display the site collections where the current logged in user having the access by using the search keyword query.
using Microsoft.Office.Server.Search.Administration;
using Microsoft.Office.Server.Search.Query;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;
using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Linq;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint.Administration;
using System.Collections;
using System.Linq;
namespace EnterpriseSiteUser.ControlTemplates.EnterpriseSiteUser
{
public partial class EnterpriseSiteUserControl : UserControl
{
#region Properties
protected Button btnSearch;
protected TextBox txtSearchBox;
protected Label lblResults;
public string SearchScope = "All Sites";
public string strManagedPath;
public static ArrayList arrManagedPath;
public static Dictionary<string, string> dictionary;
#endregion
#region Event handlers
/// <summary>
/// Page_Load
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)
{
//Set cursor focus on search textbox
txtSearchBox.Focus();
//design all site filter categories on the search right side panel
GetSites();
//get managed path name from query string
strManagedPath = Convert.ToString(Request.QueryString["ManagePath"]);
if (!IsPostBack)
{
//check if Manage path from query string is exist on the 'Managedpath' field in SiteImages library
arrManagedPath = GetSiteManagePath();
if (!string.IsNullOrEmpty(strManagedPath))
{
//Build search query based on the 'search keyword' and 'ManagedPath'
GetListOfWebsFromSearch(txtSearchBox.Text.Trim(), GetManagePathFromPicLib(strManagedPath));
}
else
{
//Build search query based on the 'search keyword' and 'ManagedPath'
GetListOfWebsFromSearch(txtSearchBox.Text.Trim(), "");
}
}
if (!string.IsNullOrEmpty(Convert.ToString(Request.QueryString["name"])))
{
//Dispaly category of the site in the search title
lblsiteName.Text = Convert.ToString(Request.QueryString["name"]);
}
else
{
//Dispaly category of the site in the search title
lblsiteName.Text = "All Sites";
}
}
/// <summary>
/// triggers when user types the keyword in search box
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void imgbtnSearch_Click(object sender, ImageClickEventArgs e)
{
try
{
if (string.IsNullOrEmpty(txtSearchBox.Text))
{
//build the search query from the keyword and managedpath values
GetListOfWebsFromSearch("", GetManagePathFromPicLib(strManagedPath));
}
else
{
//build the search query from the keyword and managedpath values
GetListOfWebsFromSearch(txtSearchBox.Text, GetManagePathFromPicLib(strManagedPath));
}
}
catch (Exception ex)
{
// log exception to ULS
LoggingService.LogError(Constants.EnterpriseSiteUser_WEBPARTS, ex);
}
}
#endregion
#region Private Methods
/// <summary>
/// Getting collection of sites where the logged in user is having the access.
/// </summary>
private void GetListOfWebsFromSearch(string keywordQueryText, string ManagedPath)
{
try
{
//Data table to collect all search results
DataTable retResults = new DataTable();
//get service application proxy from current site context
var ssaProxy = (SearchServiceApplicationProxy)SearchServiceApplicationProxy.GetProxy(SPServiceContext.GetContext(SPContext.Current.Site));
{
//Build the keyword query
using (KeywordQuery keywordQuery = new KeywordQuery(ssaProxy))
{
//set number of items retreiving from search results
keywordQuery.RowLimit = 500;
//show all site collections including root site collection
//if keywordQuery.TrimDuplicates = true, this will retrun only root site collection of the web application
keywordQuery.TrimDuplicates = false;
keywordQuery.ResultsProvider = SearchProvider.Default;
keywordQuery.KeywordInclusion = KeywordInclusion.AllKeywords;
keywordQuery.StartRow = 0;
keywordQuery.EnablePhonetic = true;
keywordQuery.EnableStemming = true;
//return columns from the search results
keywordQuery.SelectProperties.Add("Path");
keywordQuery.SelectProperties.Add("Title");
keywordQuery.SelectProperties.Add("contentclass");
keywordQuery.HiddenConstraints = "Scope:" + "\"" + SearchScope + "\"";
keywordQuery.ResultTypes = ResultType.RelevantResults;
//check if keyword is not entered
if (string.IsNullOrEmpty(keywordQueryText))
{
//build the search query with out keyword typed on the search textbox
keywordQuery.QueryText = "contentclass:STS_SITE " + GetsiteExcludedUrls() + " " + ManagedPath;
}
else
{
//build the search query with keyword typed on the search textbox
keywordQuery.QueryText = "contentclass:STS_SITE " + GetsiteExcludedUrls() + " " + "*" + keywordQueryText + "* " + ManagedPath;
}
ResultTableCollection searchResults;
try
{
//execute search query
SearchExecutor searchExecutor = new SearchExecutor();
searchResults = searchExecutor.ExecuteQuery(keywordQuery);
}
catch (Exception)
{
return;
}
//get search results from 'TableType' datatable
var results = searchResults.Filter("TableType", KnownTableTypes.RelevantResults);
if (results != null && results.Count() == 1)
{
//Load search results into the datatable
retResults.Load(results.First(), LoadOption.OverwriteChanges);
}
//remove root site collection urls
string rootsiteUrls = ExcludeRootsites();
if (!string.IsNullOrEmpty(rootsiteUrls))
{
//split the root ste collection urls
string[] rootsitesCol = rootsiteUrls.Split(';');
foreach (string rootsite in rootsitesCol)
{
if (!string.IsNullOrEmpty(rootsite))
{
//get the rows when 'path' value exist in the data table
var Rows = retResults.AsEnumerable().Where(r => r.Field<string>("path") != "" + rootsite.TrimEnd('/') + "");
if (Rows.Count() > 0)
{
//remove the root site collections from final results data table
retResults = Rows.CopyToDataTable();
}
}
}
//remove root site collection urls from data table
dlSiteUsers.DataSource = retResults;
dlSiteUsers.DataBind();
}
else
{
//bind datatable with datalist
dlSiteUsers.DataSource = retResults;
dlSiteUsers.DataBind();
}
if (retResults.Rows.Count == 0)
{
//show message when no site collection found
lblSearchmsg.Text = "No Sites Found!";
}
else
{
lblSearchmsg.Text = string.Empty;
}
}
}
}
catch (Exception ex)
{
// log exception to ULS
LoggingService.LogError(Constants.EnterpriseSiteUser_WEBPARTS, ex);
}
}
#endregion
#region Public Methods
/// <summary>
/// get image url from the site images library based on the site category selected from right side panel
/// </summary>
/// <param name="siteImage"></param>
/// <returns></returns>
public string SetSiteImg(string siteUrl)
{
string strSiteImage = string.Empty;
string managedPath = string.Empty;
try
{
//check managed path is available in the 'Site Images' list
if (arrManagedPath != null && arrManagedPath.Count > 0)
{
foreach (string strpath in arrManagedPath)
{
if (siteUrl.Contains("/" + strpath + "/"))
{
managedPath = strpath;
}
}
if (dictionary.ContainsKey(managedPath))
{
strSiteImage = dictionary[managedPath];
}
else
{
strSiteImage = dictionary["other"];
}
}
return strSiteImage;
}
catch (Exception ex)
{
return strSiteImage;
// log exception to ULS
LoggingService.LogError(Constants.EnterpriseSiteUser_WEBPARTS, ex);
}
}
/// <summary>
/// get managed path name from 'SiteImages' library
/// </summary>
/// <param name="managePath"></param>
/// <returns></returns>
public string GetManagePathFromPicLib(string managePath)
{
string managePathQuery = string.Empty;
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(SPContext.Current.Site.Url))
{
using (SPWeb web = site.RootWeb)
{
web.AllowUnsafeUpdates = true;
if (web != null)
{
SPList picLib = web.Lists.TryGetList("SiteImages");
if (picLib != null)
{
SPQuery query = new SPQuery();
query.Query = "<Where><Eq><FieldRef Name='ManagedPath' /><Value Type='Text'>" + managePath + "</Value></Eq></Where>";
query.RowLimit = 1;
SPListItemCollection picColl = picLib.GetItems(query);
if (picColl != null && picColl.Count == 1)
{
SPListItem item = picColl[0];
if (item != null)
{
StringBuilder sbSiteUrl = new StringBuilder();
SPFieldMultiChoiceValue choices = new SPFieldMultiChoiceValue(Convert.ToString(item["SiteUrl"]));
if (choices != null && choices.Count > 0)
{
for (int i = 0; i < choices.Count; i++)
{
sbSiteUrl.Append("path:");
sbSiteUrl.Append(choices[i]);
sbSiteUrl.Append("*");
sbSiteUrl.Append(" ");
}
managePathQuery = Convert.ToString(sbSiteUrl);
}
}
}
}
}
web.AllowUnsafeUpdates = false;
}
}
});
return managePathQuery;
}
catch (Exception ex)
{
return managePathQuery;
// log exception to ULS
LoggingService.LogError(Constants.EnterpriseSiteUser_WEBPARTS, ex);
}
}
/// <summary>
/// Stored all predefined managed path and Image url in array list and dictionary
/// </summary>
/// <param name="siteUrl"></param>
/// <returns></returns>
public ArrayList GetSiteManagePath()
{
ArrayList arrManagedPath = new ArrayList();
dictionary = new Dictionary<string, string>();
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(SPContext.Current.Site.Url))
{
using (SPWeb web = site.RootWeb)
{
web.AllowUnsafeUpdates = true;
if (web != null)
{
SPList picLib = web.Lists.TryGetList("SiteImages");
if (picLib != null)
{
//get managed path values from 'ManagedPath' choice field
SPFieldChoice managedPathField = (SPFieldChoice)picLib.Fields["ManagedPath"];
//List<string> fieldList = new List<string>();
if (managedPathField != null && managedPathField.Choices.Count > 0)
{
foreach (string fld in managedPathField.Choices)
{
arrManagedPath.Add(fld);
//if (siteUrl.Contains("/" + fld + "/"))
//{
// siteManagedPath = fld;
//}
}
}
dictionary.Clear();
foreach (SPListItem item in picLib.Items)
{
dictionary.Add(Convert.ToString(item["ManagedPath"]), Convert.ToString(item["EncodedAbsThumbnailUrl"]));
}
}
}
web.AllowUnsafeUpdates = false;
}
}
});
return arrManagedPath;
}
catch (Exception ex)
{
return arrManagedPath;
// log exception to ULS
LoggingService.LogError(Constants.EnterpriseSiteUser_WEBPARTS, ex);
}
}
/// <summary>
/// get all excluded site collection urls
/// </summary>
/// <param name="siteUrl"></param>
/// <returns></returns>
public string GetsiteExcludedUrls()
{
StringBuilder siteExcludedUrls = new StringBuilder();
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(SPContext.Current.Site.Url))
{
using (SPWeb web = site.RootWeb)
{
web.AllowUnsafeUpdates = true;
if (web != null)
{
SPList exclusionList = web.Lists.TryGetList("Sites Exclusion List");
//get items if 'OperatorText' is equal to 'Contains'
SPQuery query = new SPQuery();
query.Query = "<Where><Eq><FieldRef Name='OperatorText'/><Value Type='Chioce'>Contains</Value></Eq></Where>";
SPListItemCollection exclusionCol = exclusionList.GetItems(query);
if (exclusionCol != null && exclusionCol.Count > 0)
{
//store all excluded urls in the string
foreach (SPListItem item in exclusionCol)
{
siteExcludedUrls.Append(item["OperatorSyntex"].ToString());
siteExcludedUrls.Append("path:");
siteExcludedUrls.Append(item["Title"].ToString());
siteExcludedUrls.Append(" ");
}
}
}
web.AllowUnsafeUpdates = false;
}
}
});
return siteExcludedUrls.ToString();
}
catch (Exception ex)
{
return siteExcludedUrls.ToString();
// log exception to ULS
LoggingService.LogError(Constants.EnterpriseSiteUser_WEBPARTS, ex);
}
}
/// <summary>
/// get site categories in the right side panel of the search page
/// </summary>
public void GetSites()
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(SPContext.Current.Site.Url))
{
using (SPWeb web = site.RootWeb)
{
web.AllowUnsafeUpdates = true;
if (web != null)
{
SPList picLib = web.Lists.TryGetList("SiteImages");
if (picLib != null)
{
//query to get all items
SPQuery query = new SPQuery();
query.Query = "<Where><Neq><FieldRef Name='SiteOrder' /><Value Type='Number'>10000</Value></Neq></Where><OrderBy><FieldRef Name='SiteOrder' Ascending='TRUE' /></OrderBy>";
//query.Query = "<OrderBy><FieldRef Name='SiteOrder' Ascending='TRUE' /></OrderBy>";
SPListItemCollection picColl = picLib.GetItems(query);
if (picColl != null && picColl.Count > 0)
{
string thisPageURL = string.Empty;
if (System.Web.HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("?") > 0)
{
//get current page url without querystring
thisPageURL = System.Web.HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, System.Web.HttpContext.Current.Request.Url.AbsoluteUri.LastIndexOf("?"));
}
else
{
//get current page url with querystring
thisPageURL = System.Web.HttpContext.Current.Request.Url.AbsoluteUri;
}
foreach (SPListItem item in picColl)
{
HtmlGenericControl anchor = new HtmlGenericControl();
anchor.ID = "a" + item.ID;
anchor.TagName = "a";
if (Convert.ToInt32(item["SiteOrder"]) == 0)
{
anchor.Attributes["href"] = thisPageURL + "?name=" + Convert.ToString(item["SiteTitle"]);
}
else
{
anchor.Attributes["href"] = thisPageURL + "?ManagePath=" + Convert.ToString(item["ManagedPath"]) + "&name=" + Convert.ToString(item["SiteTitle"]);
}
pnlsiteImgContainer.Controls.Add(anchor);
//Design all site categories on search panel
HtmlGenericControl div = new HtmlGenericControl();
div.ID = "div" + item.ID;
div.TagName = "div";
div.Attributes["class"] = "hot-commandbutton-blue-normal";
anchor.Controls.Add(div);
ImageButton siteImg = new ImageButton();
siteImg.ID = "img" + item.ID;
siteImg.ImageUrl = Convert.ToString(item["EncodedAbsThumbnailUrl"]);
div.Controls.Add(siteImg);
HtmlGenericControl spanTitle = new HtmlGenericControl();
spanTitle.ID = "spn" + item.ID;
spanTitle.TagName = "span";
spanTitle.InnerText = Convert.ToString(item["SiteTitle"]);
spanTitle.Attributes["class"] = "hot-commandbutton-blue-normal-title";
div.Controls.Add(spanTitle);
}
}
}
}
web.AllowUnsafeUpdates = false;
}
}
});
}
catch (Exception ex)
{
// log exception to ULS
LoggingService.LogError(Constants.EnterpriseSiteUser_WEBPARTS, ex);
}
}
/// <summary>
/// Exclude root site colections from search results
/// </summary>
/// <returns></returns>
public string ExcludeRootsites()
{
StringBuilder rootsiteUrls = new StringBuilder();
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(SPContext.Current.Site.Url))
{
using (SPWeb web = site.RootWeb)
{
web.AllowUnsafeUpdates = true;
if (web != null)
{
SPList exclusionList = web.Lists.TryGetList("Sites Exclusion List");
//get items from 'Site exclusion list' when OperatorText field is equal to 'Not Equal'
SPQuery query = new SPQuery();
query.Query = "<Where><Eq><FieldRef Name='OperatorText'/><Value Type='Chioce'>Not Equal</Value></Eq></Where>";
SPListItemCollection exclusionCol = exclusionList.GetItems(query);
if (exclusionCol != null && exclusionCol.Count > 0)
{
foreach (SPListItem item in exclusionCol)
{
//store root site collection urls in the string bulider
rootsiteUrls.Append(item["Title"].ToString());
rootsiteUrls.Append(";");
}
}
}
web.AllowUnsafeUpdates = false;
}
}
});
return rootsiteUrls.ToString();
}
catch (Exception ex)
{
return rootsiteUrls.ToString();
// log exception to ULS
LoggingService.LogError(Constants.EnterpriseSiteUser_WEBPARTS, ex);
}
}
#endregion
}
}
No comments:
Post a Comment