Skip to content

Instantly share code, notes, and snippets.

@chrisobriensp
Last active December 10, 2015 02:48
Show Gist options
  • Save chrisobriensp/4370167 to your computer and use it in GitHub Desktop.
Save chrisobriensp/4370167 to your computer and use it in GitHub Desktop.
Code to use SP2013 search REST API from .NET CSOM.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;
namespace COB.SharePointAutohostedAppWeb.Pages
{
public partial class SearchResults : System.Web.UI.Page
{
SharePointContextToken contextToken;
string accessToken;
Uri sharepointHostWebUrl;
protected void Page_Load(object sender, EventArgs e)
{
string queryText = "timesheets";
TokenHelper.TrustAllCertificates();
string contextTokenString = TokenHelper.GetContextTokenFromRequest(Request);
if (contextTokenString != null)
{
// get context token from TokenHelper..
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, Request.Url.Authority);
// use it to get the access token..
sharepointHostWebUrl = new Uri(Request.QueryString["SPHostUrl"]);
accessToken = TokenHelper.GetAccessToken(contextToken, sharepointHostWebUrl.Authority).AccessToken;
// pass the access token - N.B. if this was a control event (rather than page load), we'd need to persist
// this somewhere it could be accessed in the event handler..
runSearch(accessToken, queryText);
}
}
private void runSearch(string accessToken, string queryText)
{
if (IsPostBack)
{
sharepointHostWebUrl = new Uri(Request.QueryString["SPHostUrl"]);
}
string searchRestUrl = string.Format("/_api/search/query?querytext='{0}'", queryText);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(sharepointHostWebUrl.ToString() + searchRestUrl);
request.Method = "GET";
request.Accept = "application/atom+xml";
request.ContentType = "application/atom+xml;type=entry";
request.Headers.Add("Authorization", "Bearer " + accessToken);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// process response..
XDocument oDataXML = XDocument.Load(response.GetResponseStream(), LoadOptions.None);
XNamespace atom = "http://www.w3.org/2005/Atom";
XNamespace d = "http://schemas.microsoft.com/ado/2007/08/dataservices";
XNamespace m = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";
List<XElement> items = oDataXML.Descendants(d + "query")
.Elements(d + "PrimaryQueryResult")
.Elements(d + "RelevantResults")
.Elements(d + "Table")
.Elements(d + "Rows")
.Elements(d + "element")
.ToList();
// N.B. there might be a more elegant/efficient way of extracting the values from the (slightly awkward) XML than this..
var searchResults = from item in items
select new
{
Title = item.Element(d + "Cells").Descendants(d + "Key").First(a => a.Value == "Title").Parent.Element(d + "Value").Value,
Author = item.Element(d + "Cells").Descendants(d + "Key").First(a => a.Value == "Author").Parent.Element(d + "Value").Value,
HitHighlightedSummary = item.Element(d + "Cells").Descendants(d + "Key").First(a => a.Value == "HitHighlightedSummary").Parent.Element(d + "Value").Value,
Path = item.Element(d + "Cells").Descendants(d + "Key").First(a => a.Value == "Path").Parent.Element(d + "Value").Value
};
// data-bind to ListView..
lvSearchResults.DataSource = searchResults;
lvSearchResults.DataBind();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment