Using the Search API with Sharepoint Foundation 2010 - 0 results - sharepoint

I am a sharepoint newbee and am having trouble getting any search results to return using the search API in Sharepoint 2010 Foundation.
Here are the steps I have taken so far.
The Service Sharepoint Foundation Search v4 is running and logged in as Local Service
Under Team Site - Site Settings - Search and Offline Availability, Indexing Site Content is enabled.
Running the PowerShell script Get-SPSearchServiceInstance returns
TypeName : SharePoint Foundation Search
Description : Search index file on the search server
Id : 91e01ce1-016e-44e0-a938-035d37613b70
Server : SPServer Name=V-SP2010
Service : SPSearchService Name=SPSearch4
IndexLocation : C:\Program Files\Common Files\Microsoft Shared\Web Server Exten
sions\14\Data\Applications
ProxyType : Default
Status : Online
When I do a search using the search textbox on the team site I get a results as I would expect.
Now, when I try to duplicate the search results using the Search API I either receive an error or 0 results.
Here is some sample code:
using Microsoft.SharePoint.Search.Query;
using (var site = new SPSite(_sharepointUrl, token))
{
//
FullTextSqlQuery fullTextSqlQuery = new FullTextSqlQuery(site)
{
QueryText = String.Format("SELECT Title, SiteName, Path FROM Scope() WHERE \"scope\"='All Sites' AND CONTAINS('\"{0}\"')", searchPhrase),
//QueryText = String.Format("SELECT Title, SiteName, Path FROM Scope()", searchPhrase),
TrimDuplicates = true,
StartRow = 0,
RowLimit = 200,
ResultTypes = ResultType.RelevantResults
//IgnoreAllNoiseQuery = false
};
ResultTableCollection resultTableCollection = fullTextSqlQuery.Execute();
ResultTable result = resultTableCollection[ResultType.RelevantResults];
DataTable tbl = new DataTable();
tbl.Load(result, LoadOption.OverwriteChanges);
}
When the scope is set to All Sites I retrieve an error about the search scope not being available. Other search just return 0 results.
Any ideas about what I am doing wrong?

This is the workaround we came up with.
We did not get the foundation search to work as we had hoped. We will review it again once the RTM version of Sharepoint Foundation is released.
We installed Search Server Express 2010 beta. This allowed us to use the office server namespaces and the corresponding classes. This worked as expected and we were able to programmatically search against Sharepoint Foundation.

I also never got results by using FullTextSqlQuery on Foundation Search but perhaps you can use KeywordQuery:
SPSite thisSite = SPControl.GetContextSite(Context);
Microsoft.SharePoint.Search.Query.KeywordQuery kwQuery = new Microsoft.SharePoint.Search.Query.KeywordQuery(thisSite);
kwQuery.RowLimit = 1000;
kwQuery.QueryText = "searchString";
kwQuery.HiddenConstraints = "site:\"http://devXX:800/test/docs\"";
kwQuery.ResultTypes = ResultType.RelevantResults;
ResultTableCollection results = kwQuery.Execute();
ResultTable relevantResults = results[ResultType.RelevantResults];
dt.Load(relevantResults, LoadOption.OverwriteChanges);

Related

SharePoint 2013 Activity Event in Newsfeed

I need to add custom notifications to the personal Newsfeed on people's MySites. I found several tutorials and code examples for SharePoint 2010 on the net and tried to do the same with SharePoint 2013. They're all about creating ActivityEvents with the ActivityManager.
Here's the code I tried:
var targetSite = new SPSite("URL to MySite webapp");
SPServiceContext context = SPServiceContext.GetContext(targetSite);
var userProfileManager = new UserProfileManager(context);
var ownerProfile = userProfileManager.GetUserProfile("domain\\user1");
var publisherProfile = userProfileManager.GetUserProfile("domain\\user2");
var activityManager = new ActivityManager(ownerProfile, context);
Entity publisher = new MinimalPerson(publisherProfile).CreateEntity(activityManager);
Entity owner = new MinimalPerson(ownerProfile).CreateEntity(activityManager);
ActivityEvent activityEvent = ActivityEvent.CreateActivityEvent(activityManager, 17, owner, publisher);
activityEvent.Name = "StatusMessage";
activityEvent.ItemPrivacy = (int)Privacy.Public;
activityEvent.Owner = owner;
activityEvent.Publisher = publisher;
activityEvent.Value = "HELLOOOO";
activityEvent.Commit();
ActivityFeedGatherer.BatchWriteActivityEvents(new List<ActivityEvent> { activityEvent }, 0, 1);
The Id 17 in the CreateActivityEvent function is for the StatusMessage activity type, which is layouted like {Publisher} says: {Value} in the ressource files, so I provide the Value property of my ActivityEvent.
The code runs without any exception and in the User Profile Service Application_ProfileDB database I can see the right entries appear in the ActivityEventsConsolidated table.
But the activity is not visible in the activity feed, neither on the Owner's one, nor on the Publisher's one, even though these people follow each other. I ran the Activity Feed Job in the CA manually to update the activity feed.
Also, I tried to do the same with custom ActivityTypes with own ressource files, same result: The entry in the ActivityEventsConsolidated table (or ActivityEventsPublished if Owner=Publisher) appear, but no entries on the MySite.
Can anyone help?
I found the solution for this problem myself.
In Central Administration, Setup MySites, you have to enable the Enable SharePoint 2010 activity migration setting in the Newsfeed section in order to support SP1010 legacy activities in SP2013.

SharePoint CSOM

Want to be build an application (using SharePoint CSOM) to fetch all the Users and SharePoint Groups from a SharePoint Farm. The Users and Groups are required to be fetched from all the Site Collections which may be present on the farm. Having gone thru the documentation it appears that the Site class https://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.site_methods(v=office.14).aspx represents only a 'single' SiteCollection. This is great. However, before the application can create the Site objects for each SiteCollection the app need to determine all the SiteCollections present on the farm. Is there a class / method to retrieve all the SiteCollection on a SharPoint farm?
if the search is enabled, there is a way to do this by using search results:
KeywordQuery query = new KeywordQuery(site);
query.QueryText = string.Format("Path:{0} AND ContentClass:STS_Site", webAppURL);
query.RowLimit = 500;//max row limit is 500 for KeywordQuery
query.ResultsProvider = SearchProvider.Default;
query.EnableStemming = true;
query.TrimDuplicates = false;
query.AuthenticationType = QueryAuthenticationType.PluggableAuthenticatedQuery;
query.KeywordInclusion = KeywordInclusion.AllKeywords;
SearchExecutor executor = new SearchExecutor();
ResultTableCollection resultTableCollection = executor.ExecuteQuery(query);
var resultTables = resultTableCollection.Filter("TableType", KnownTableTypes.RelevantResults);
var resultTable = resultTables.FirstOrDefault();
Source: https://sharepoint.stackexchange.com/questions/133073/get-all-site-collections-with-csom
(By the way, with SharePoint Online it is easier, you can use SPOSitePropertiesEnumerable class.
SharePoint CSOM, retrieving site collections. Limited to 300?)

How to use Sharepoint Server Search (KeywordQuery class) to search through a sharepoint list?

We have a requirement where users are to be allowed to search a list called "Reports" from the front-end, and advanced search, such as author:"John Smith" or filetype:docx, is to be supported.
We decided that this can be achieved using Sharepoint Server Search API (using the Keyword Query Language). Also, since it is possible that all users don't have access to all items in the list, we decided to go with the approach to use a web method with elevated privileges to query the list.
This is my attempt so far...
public string GetSearchResults(string listname, string searchQuery)
{
SPUser superUser = SPContext.Current.Web.AllUsers[#"SHAREPOINT\SYSTEM"];
using (SPSite site = new SPSite(SPContext.Current.Web.Url, superUser.UserToken))
{
KeywordQuery keywordQuery = new KeywordQuery(site);
keywordQuery.QueryText = searchQuery;
//where should listname be specified?
SearchExecutor searchExecutor = new SearchExecutor();
ResultTableCollection resultTableCollection = searchExecutor.ExecuteQuery(keywordQuery);
var resultTables = resultTableCollection.Filter("TableType", KnownTableTypes.RelevantResults);
ResultTable resultTable = resultTables.FirstOrDefault();
DataTable dataTable = resultTable.Table;
}
//how to parse result to filter only items in given list?
}
...but what I don't understand is how to restrict search to only a given list or how to parse the search result to retrieve items of the list matching the search query.
I'm new to Sharepoint search, so any pointers would help.
This is possible either to give list path or list guid in query text
keywordQuery.QueryText = "Path:/Sales/Lists/Prospects/ (contentclass:STS_ListItem OR IsDocument:True) -ContentClass=urn:content-class:SPSPeople ";

Creating new site collection in Office 365 from an APP

I have a requirement to create a new site collection from within an App in Office 365 programmatically. What I mean by a new site collection, is that after creation, it should appear on the list of site collections under the Admin --> Sharepoint tab of Office 365. I tried using a similar code below within a sharepoint hosted app that i had created,
//create sp context and get root
var clientContext = new SP.ClientContext.get_current();
var rootWeb = clientContext.site.rootWeb();
this.clientContext.load(rootWeb);
this.clientContext.executeQUery();
//set web info
var webInfo = new SP.WebCreationInformation();
webInfo.set_webTemplate('YourTemplateName');
webInfo.set_description('Your site description');
webInfo.set_title('Your site tittle');
webInfo.set_url(siteUrl);
webInfo.set_language(yourLangCode);
this.rootWeb.get_webs().add(webInfo);
this.rootWeb.update();
// save site and set callbacks
this.clientContext.load(this.rootWeb);
this.clientContext.executeQueryAsync(
Function.createDelegate(this, this.OnSiteCreationSuccess),
Function.createDelegate(this, this.Error));
However this just creates a sub site under the site collection that hosts my App.
Any suggestions on how i could implement this would be greatly appreciated.
It can be done with SharePoint Object Model 2013, the functions you need are inside the assembly: Microsoft.Online.SharePoint.Client.Tenant.dll, which is located at C:\Program Files\SharePoint Client Components\Assemblies after you install the SharePoint Client Object model 2013.
There's not much doc on this, but SharePoint Online Management Shell has the command to create the site collection, so I think it can be done with C# and figured it out. The code snippet shows how to do it.
using System;
using Microsoft.Online.SharePoint.TenantAdministration;
using Microsoft.SharePoint.Client;
using System.Security;
namespace SharePoint123
{
class Program
{
static void Main(string[] args)
{
//please change the value of user name, password, and admin portal URL
string username = "xxxx#xxxx.onmicrosoft.com";
String pwd = "xxxx";
ClientContext context = new ClientContext("https://xxxx-admin.sharepoint.com");
SecureString password = new SecureString();
foreach (char c in pwd.ToCharArray())
{
password.AppendChar(c);
}
context.Credentials = new SharePointOnlineCredentials(username, password);
Tenant t = new Tenant(context);
context.ExecuteQuery();//login into SharePoint online
//code to create a new site collection
var newsite = new SiteCreationProperties()
{
Url = "https://xxxxx.sharepoint.com/sites/createdbyProgram1",
Owner = "xxxxx#xxxxx.onmicrosoft.com",
Template = "STS#0", //using the team site template, check the MSDN if you want to use other template
StorageMaximumLevel = 100,
UserCodeMaximumLevel = 100,
UserCodeWarningLevel = 100,
StorageWarningLevel = 300,
Title = "CreatedbyPrgram",
CompatibilityLevel = 15, //15 means Shapoint online 2013, 14 means Sharepoint online 2010
};
t.CreateSite(newsite);
context.ExecuteQuery();
//end
}
}
}

Displaying Managed Property in Search Results - FAST Search for Sharepoint 2010

We are working with Fast Search for Sharepoint 2010 and had some backend setup done with creating some managed properties e.g. BestBetDescription, keywords etc.
From the front-end part we are creating an application what will fetch all these properties and display in a grid.
However while querying the backend we are NOT getting these managed properties (BestBetDescription) along with other properties such as Title, URL etc.
Following is my source code:
settingsProxy = SPFarm.Local.ServiceProxies.GetValue<SearchQueryAndSiteSettingsServiceProxy>();
searchProxy = settingsProxy.ApplicationProxies.GetValue<SearchServiceApplicationProxy>("FAST Query SSA");
keywordQuery = new KeywordQuery(searchProxy);
keywordQuery.EnableFQL = true;
keywordQuery.QueryText = p;
keywordQuery.ResultsProvider = SearchProvider.FASTSearch;
keywordQuery.ResultTypes = ResultType.RelevantResults;
ResultTableCollection resultsTableCollection = keywordQuery.Execute();
ResultTable searchResultsTable = resultsTableCollection[ResultType.RelevantResults];
DataTable resultsDataTable = new DataTable();
resultsDataTable.TableName = "Results";
resultsDataTable.Load(searchResultsTable, LoadOption.OverwriteChanges);
return resultsDataTable;
The results are returned and I cannot see the Managed properties which we create in the resultDataTable.
Is there any property I missed or is this a backend issue ?
Thanks.
Hi if you are creating your custom Metadata Property then u should use this option to be selected
please check below link
http://screencast.com/t/SQdlarjhx4F
You can find this option in :
central admin:- services :- fast search :- Metadata Property :- your property
I was missing a property KeywordQuery.SelectProperties
So the code looks something like this
String[] arrSearchProperties = new String[] { "Title", "body", "url" };
KeywordQuery.SelectProperties(arrSearchProperties);
This will fetch you all the Managed Properties defined by you.

Resources