Basic requirement is to filter the search results based on target audience on SharePoint document repository. If current user belongs to one perticular group and if that group doesn't have permission on perticular folder from document library then that user will not be able to see documents from that perticular folder.
Here is the code:
using Microsoft.Office.Server.Search.Query;
using System.Collections.Generic;
using System.ComponentModel;
Button cmdSearch;
TextBox txtQueryText;
Label lblQueryResult;
SPWeb web = null;
int SearchCnt = 0;
protected override void CreateChildControls()
{
// Create and add the controls that compose the
// user interface of the Web Part.
Controls.Clear();
txtQueryText = new TextBox();
this.Controls.Add(txtQueryText);
cmdSearch = new Button();
cmdSearch.Text = "Start Search";
cmdSearch.Click += new EventHandler(cmdSearch_Click);
this.Controls.Add(cmdSearch);
}
void cmdSearch_Click(object sender, EventArgs e)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPSite site = SPContext.Current.Site;
web = site.OpenWeb();
web.AllowUnsafeUpdates = true;
SPList list = web.Lists[_ListName];
SPView view = list.Views["All Documents"];
SPQuery query = new SPQuery(view);
query.ViewAttributes += " Scope=\"Recursive\"";
//Retrieve the items based on Query
SPListItemCollection items = list.GetItems(query);
foreach (SPListItem item in items)
{
SPRoleDefinitionBindingCollection usersRoles = web.AllRolesForCurrentUser;
// Validate if user has rights
if (item.Name.Contains(txtQueryText.Text))
{
foreach (SPRoleDefinition roleDefinition in usersRoles)
{
SPRoleDefinitionBindingCollection col = item.AllRolesForCurrentUser;
foreach (SPRoleDefinition role in col)
{
if (role == roleDefinition)
{
SearchCnt++;
HyperLink name = new HyperLink();
name.Text = "
" + item.Name + "
";
name.Font.Size = 10;
name.NavigateUrl = web.Url + "/" + item.Url;
HyperLink url = new HyperLink();
url.Text = web.Url + "/" + item.Url + "
";
url.NavigateUrl = web.Url + "/" + item.Url;
url.ForeColor = System.Drawing.Color.Green;
this.Controls.Add(name);
this.Controls.Add(url);
}
break;
}
}
}
}
if (SearchCnt == 0)
{
lblQueryResult = new Label();
lblQueryResult.Text = "
" + "No search results found!";
this.Controls.Add(lblQueryResult);
}
});
catch (ArgumentException ex)
{
}
}
No comments:
Post a Comment