Microsoft Cloud Authors: Elizabeth White, Yeshim Deniz, Serafima Al, Janakiram MSV, John Katrick

Related Topics: Microsoft Cloud, Silverlight

Microsoft Cloud: Blog Feed Post

Building a SharePoint Advanced Search Application with Silverlight 4

A couple of years ago, I demonstrated how to build an advanced search application with Silverlight 3

At SharePoint Conference 2011, I showed off a great looking advanced search application using Silverlight 4.  This application queried the Search web service at /_vti_bin/search.asmx to retrieve results and display them directly inside the application.  A couple of years ago, I demonstrated how to build an advanced search application with Silverlight 3.  This application is very similar to that one except that I take it a step further and show you more of the possibilities of what the user interface could look like.

The code you will see today was intended for Office 365 / SharePoint Online but will work quite well with SharePoint 2010 (and to a degree SharePoint 2007).  Everything from the pervious article pretty much applies.  We create a reference to search.asmx, we build an XML input document, and then we make an asynchronous call to the web service.  One thing I will point out is that I have been unsuccessful in getting the ClientAccessPolicy.xml file to work with SharePoint Online.  This means that the application cannot run locally to allow us to debug it.  I’ve posted to the Office 365 forums but have had no luck.  If anyone figures this out, please let me know.

The way we build the input XML document and call the web service is exactly the same as the pervious post.  However, what is different is the actual keyword query we construct.  Let’s take a look at what the interface looks like first.


There is a number of things going on here in this interface.  We first provide the user to do a simple keyword query search.  However, we also give the user the ability to query by File Size, Modified Date, Author, and by Document Only.  To do this, we use the following built-in managed properties respectively FileSize, Write, Author, and IsDocument.  The user can select any combination of the above to get a more specific query.  When the user clicks the SearchButton, our code builds a custom keyword query and sends it to the search web service.  The QueryTextBox displays the query that was constructed by the code.  However, it can also be modified by the user to test out a query manually.  This serves as a great search query testing tool.  After the user searches, the returned XML document is displayed in the large multiline textbox.  Beneath the textbox, I have added a Telerik GridView control.  I had this available to me so I decided to use it.  I think you could just as well have used a DataGrid control to bind the data too.

The code for the Silverlight application is surprisingly simple.  When the user clicks the SearchButton, we begin to construct the keyword query we want to pass to the web service.  To do this, we need a StringBuilder class so be sure and add a reference to System.Text.  We then check each control to see if it has a value.  For example, for SearchTextBox, if it has a value we simply append it to the StringBuilder named searchQuery.

if (!string.IsNullOrEmpty(SearchTextBox.Text))
searchQuery.AppendFormat("{0} ", SearchTextBox.Text);

The FileSize managed property has an operator with values such as >, >=, < and, <=.  These are contained in the ModifiedDateOperatorComboBox.  If there is a value then we append it to searchQuery.

if (FileSizeOperatorComboBox.SelectedItem != null)
searchQuery.AppendFormat("Size{0}\"{1}\" ",

We continue to this for the rest of the controls on the page in the SearchButton click event handling method.  Here is the entire method.

private void SearchButton_Click(object sender, RoutedEventArgs e)
StringBuilder searchQuery = new StringBuilder();

if (!string.IsNullOrEmpty(SearchTextBox.Text))
searchQuery.AppendFormat("{0} ", SearchTextBox.Text);

if (FileSizeOperatorComboBox.SelectedItem != null)
searchQuery.AppendFormat("Size{0}\"{1}\" ",

if (ModifiedDateOperatorComboBox.SelectedItem != null)
searchQuery.AppendFormat("Write{0}\"{1}\" ",

if (!string.IsNullOrEmpty(AuthorTextBox.Text))
searchQuery.AppendFormat("Author:\"{0}\" ", AuthorTextBox.Text);

if (DocumentsOnlyCheckBox.IsChecked.Value)
searchQuery.Append("IsDocument:1 ");

// pass the search query to the method to actually call the search service

The QuerySearchService method makes the actual call to the web service.  Since we’re dealing with Silvelright, we have to call the web service method asynchronously.  We do this by binding an event handling method to the QueryExCompleted event.  Again for more details on how the XML is constructed see my information from the Silverlight 3 post.

private void QuerySearchService(string searchQuery)
QueryServiceSoapClient queryService = new QueryServiceSoapClient();
queryService.QueryExCompleted += new EventHandler<QueryExCompletedEventArgs>(QueryService_QueryExCompleted);

QueryTextBox.Text = searchQuery;
StringBuilder queryXml = new StringBuilder();

queryXml.Append("<QueryPacket xmlns=\"urn:Microsoft.Search.Query\" Revision=\"1000\">");
queryXml.Append("<Query domain=\"QDomain\">");
queryXml.Append("<QueryText language=\"en-US\" type=\"STRING\">");

BusyIndicator.IsBusy = true;

The last line passed the XML input document to the web service method.  Now, it’s just a matter of handling the return results in the event handling method.  The first thing we need to do is get the XML document with the results.  We can always find this in the Result.Nodes[1] object available in QueryExCompletedEventArgs. For convenience, I write this value to a TextBox so that I can view it.

ResultsTextBox.Text = e.Result.Nodes[1].ToString();

However, I want to bind this XML to our nice looking RadGridView.  To do this I must extract the data from the XDocument and expose it in a custom type. Here is where the LINQ to XML comes in.  Normally, I would just use an anonymous type for this, but that doesn’t work in Silverlight.  This means I have to create a new class to hold our search results.  I call this class SearchResult.

public class SearchResult
public string Title { get; set; }
public string Path { get; set; }
public string Author { get; set; }
public string Size { get; set; }
public DateTime? Write { get; set; }
public string SiteName { get; set; }
public string HitHighlightedSummary { get; set; }
public string ContentClass { get; set; }
public bool IsDocument { get; set; }

I then use LINQ to XML to write the value of each property in.  Since nulls are a real possibility, I use .Any() before assigning each value to ensure we don’t get an exception.  To understand the LINQ we use, let’s take a quick look at the result XML document.

<diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
<Results xmlns="">
<RelevantResults diffgr:id="RelevantResults1" msdata:rowOrder="0">
<HitHighlightedSummary>Site Actions &lt;ddd/&gt; This page location is: &lt;ddd/&gt; Home &lt;ddd/&gt; Team Sites &lt;ddd/&gt; Pages &lt;ddd/&gt; default &lt;ddd/&gt; Employee &lt;ddd/&gt; Resources &lt;ddd/&gt; Facilities &lt;ddd/&gt; News &lt;ddd/&gt; I Like It &lt;ddd/&gt; Tags &amp;amp; Notes &lt;ddd/&gt; Libraries &lt;ddd/&gt; Shared Documents &lt;ddd/&gt; Flyers &lt;ddd/&gt; Presentations &lt;ddd/&gt; Proposals &lt;ddd/&gt; &lt;c0&gt;Sales&lt;/c0&gt; Forecasts &lt;ddd/&gt; Lists &lt;ddd/&gt; Calendar &lt;ddd/&gt; Tasks &lt;ddd/&gt; </HitHighlightedSummary>

Each search result is contained inside a ReleventResults node inside of the Results element.  So we look inside there to create our query.

var results = from result in
select new SearchResult
Title = (result.Elements("Title").Any())
? result.Element("Title").Value : string.Empty,
Path = (result.Elements("Path").Any())
? result.Element("Path").Value : string.Empty,
Author = (result.Elements("Author").Any())
? result.Element("Author").Value : string.Empty,
Size = (result.Elements("Size").Any())
? result.Element("Size").Value : string.Empty,
Write = (result.Elements("Write").Any())
? DateTime.Parse(result.Element("Write").Value) : DateTime.MinValue,
SiteName = (result.Elements("SiteName").Any())
? result.Element("SiteName").Value : string.Empty,
HitHighlightedSummary = (result.Elements("HitHighlightedSummary").Any())
? result.Element("HitHighlightedSummary").Value : string.Empty,
ContentClass = (result.Elements("ContentClass").Any())
? result.Element("ContentClass").Value : string.Empty,
IsDocument = (result.Elements("IsDocument").Any())
? bool.Parse(result.Element("IsDocument").Value) : false

We simply assign each property after verifying that it’s not null.  Most values are strings but we did do some casting for DateTime and Boolean values.  The last thing we do is bind to the RadGridView.

ResultsRadGridView.ItemsSource = results;

The next section applies to the Telerik specific content.  If you don’t have those controls available to you, you can skip this section and you can configure the built-in grid in a similar manner.  RadGridView has some column types that allow us to format links and checkboxes in a nice manner.  Telerik has free trials available if you are interested.  Here is what that code looks like.

<telerik:RadGridView HorizontalAlignment="Left" Margin="13,227,0,0" Name="ResultsRadGridView" VerticalAlignment="Top" Width="776" AutoGenerateColumns="False">
<telerik:GridViewDynamicHyperlinkColumn Header="Title" DataMemberBinding="{Binding Title}" NavigateUrlFormatString="{} {0}" NavigateUrlMemberPaths="Path" TargetName="_blank" />
<telerik:GridViewDataColumn Header="Author" DataMemberBinding="{Binding Author}" />
<telerik:GridViewDataColumn Header="Write" DataMemberBinding="{Binding Write}" DataFormatString="{} {0:MMM, dd, yyyy}" />
<telerik:GridViewDataColumn Header="Size" DataMemberBinding="{Binding Size}" />
<telerik:GridViewDataColumn Header="HitHighlightedSummary" DataMemberBinding="{Binding HitHighlightedSummary}" />
<telerik:GridViewDataColumn Header="ContentClass" DataMemberBinding="{Binding ContentClass}" />
<telerik:GridViewHyperlinkColumn Header="SiteName" DataMemberBinding="{Binding SiteName}" TargetName="_blank" />
<telerik:GridViewCheckBoxColumn Header="IsDocument" DataMemberBinding="{Binding IsDocument}" />

That’s all the code that is involved.  I’ve attached the code to this post (minus the Telerik controls).  This code will work on-premises or in the cloud with SharePoint Online.  I just used built-in managed properties in my example, but if you create custom properties of your own you can add those as well.  Try it out and see what you think.  Here is a screenshot of it in action.


Read the original blog entry...

More Stories By Corey Roth

Corey Roth, a SharePoint Server MVP, is an independent consultant specializing in Cloud technologies such as Azure and Office 365. He also specializes in mobile development. Corey serves as the product manager for two cloud-first mobile app platforms: BrewZap and HappenZap.

@ThingsExpo Stories
Cloud-enabled transformation has evolved from cost saving measure to business innovation strategy -- one that combines the cloud with cognitive capabilities to drive market disruption. Learn how you can achieve the insight and agility you need to gain a competitive advantage. Industry-acclaimed CTO and cloud expert, Shankar Kalyana presents. Only the most exceptional IBMers are appointed with the rare distinction of IBM Fellow, the highest technical honor in the company. Shankar has also receive...
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities - ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups.
Poor data quality and analytics drive down business value. In fact, Gartner estimated that the average financial impact of poor data quality on organizations is $9.7 million per year. But bad data is much more than a cost center. By eroding trust in information, analytics and the business decisions based on these, it is a serious impediment to digital transformation.
Predicting the future has never been more challenging - not because of the lack of data but because of the flood of ungoverned and risk laden information. Microsoft states that 2.5 exabytes of data are created every day. Expectations and reliance on data are being pushed to the limits, as demands around hybrid options continue to grow.
The standardization of container runtimes and images has sparked the creation of an almost overwhelming number of new open source projects that build on and otherwise work with these specifications. Of course, there's Kubernetes, which orchestrates and manages collections of containers. It was one of the first and best-known examples of projects that make containers truly useful for production use. However, more recently, the container ecosystem has truly exploded. A service mesh like Istio addr...
As IoT continues to increase momentum, so does the associated risk. Secure Device Lifecycle Management (DLM) is ranked as one of the most important technology areas of IoT. Driving this trend is the realization that secure support for IoT devices provides companies the ability to deliver high-quality, reliable, secure offerings faster, create new revenue streams, and reduce support costs, all while building a competitive advantage in their markets. In this session, we will use customer use cases...
Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.
Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As automation and artificial intelligence (AI) power solution development and delivery, many businesses need to build backend cloud capabilities. Well-poised organizations, marketing smart devices with AI and BlockChain capabilities prepare to refine compliance and regulatory capabilities in 2018. Volumes of health, financial, technical and privacy data, along with tightening compliance requirements by...
DevOpsSummit New York 2018, colocated with CloudEXPO | DXWorldEXPO New York 2018 will be held November 11-13, 2018, in New York City. Digital Transformation (DX) is a major focus with the introduction of DXWorldEXPO within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of bus...
With 10 simultaneous tracks, keynotes, general sessions and targeted breakout classes, @CloudEXPO and DXWorldEXPO are two of the most important technology events of the year. Since its launch over eight years ago, @CloudEXPO and DXWorldEXPO have presented a rock star faculty as well as showcased hundreds of sponsors and exhibitors! In this blog post, we provide 7 tips on how, as part of our world-class faculty, you can deliver one of the most popular sessions at our events. But before reading...
DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, in New York City and will bring together Cloud Computing, FinTech and Blockchain, Digital Transformation, Big Data, Internet of Things, DevOps, AI, Machine Learning and WebRTC to one location.
DXWorldEXPO LLC announced today that ICOHOLDER named "Media Sponsor" of Miami Blockchain Event by FinTechEXPO. ICOHOLDER give you detailed information and help the community to invest in the trusty projects. Miami Blockchain Event by FinTechEXPO has opened its Call for Papers. The two-day event will present 20 top Blockchain experts. All speaking inquiries which covers the following information can be submitted by email to [email protected] Miami Blockchain Event by FinTechEXPO also offers s...
DXWorldEXPO | CloudEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
Digital Transformation and Disruption, Amazon Style - What You Can Learn. Chris Kocher is a co-founder of Grey Heron, a management and strategic marketing consulting firm. He has 25+ years in both strategic and hands-on operating experience helping executives and investors build revenues and shareholder value. He has consulted with over 130 companies on innovating with new business models, product strategies and monetization. Chris has held management positions at HP and Symantec in addition to ...
The best way to leverage your Cloud Expo presence as a sponsor and exhibitor is to plan your news announcements around our events. The press covering Cloud Expo and @ThingsExpo will have access to these releases and will amplify your news announcements. More than two dozen Cloud companies either set deals at our shows or have announced their mergers and acquisitions at Cloud Expo. Product announcements during our show provide your company with the most reach through our targeted audiences.
The IoT Will Grow: In what might be the most obvious prediction of the decade, the IoT will continue to expand next year, with more and more devices coming online every single day. What isn’t so obvious about this prediction: where that growth will occur. The retail, healthcare, and industrial/supply chain industries will likely see the greatest growth. Forrester Research has predicted the IoT will become “the backbone” of customer value as it continues to grow. It is no surprise that retail is ...
Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
DXWorldEXPO LLC announced today that "Miami Blockchain Event by FinTechEXPO" has announced that its Call for Papers is now open. The two-day event will present 20 top Blockchain experts. All speaking inquiries which covers the following information can be submitted by email to [email protected] Financial enterprises in New York City, London, Singapore, and other world financial capitals are embracing a new generation of smart, automated FinTech that eliminates many cumbersome, slow, and expe...
Cloud Expo | DXWorld Expo have announced the conference tracks for Cloud Expo 2018. Cloud Expo will be held June 5-7, 2018, at the Javits Center in New York City, and November 6-8, 2018, at the Santa Clara Convention Center, Santa Clara, CA. Digital Transformation (DX) is a major focus with the introduction of DX Expo within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive ov...