Posts Tagged ‘Client Object Model’

SP 2013: Searching in SharePoint 2013 using the REST new API’s

December 26th, 2012 by Tobias Zimmergren

Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

Search has always been a great way to create custom solutions that aggregate and finds information in SharePoint. With SharePoint 2013, the search capabilities are heavily invested in and we see a lot of new ways to perform our searches. In this post I’ll show a simple example of how you can utilize the REST Search API’s in SharePoint 2013 to perform a search.

REST Search in SharePoint 2013

So in order to get started, we’ll need to have an ASPX Page containing some simple markup and a javascript file where we’ll put our functions to be executed. The approach mentioned in this post is also compatible with SharePoint Apps, should you decide to develop an App that relys on Search. In my example I’ve created a custom Page which loads my jQuery and JavaScript files, and I’m deploying those files using a Module to the SiteAssets library.

Preview of the simple solution

image

Creating a Search Application using REST Search Api’s

Let’s examine how you can construct your search queries using REST formatting and by simply changing the URL to take in the proper query strings.

Formatting the Url

By formatting the Url properly you can retrieve search results pretty easily using REST.

Query with querytext

If you simply want to return all results with no limits or filters from a search, shoot out this formatted url:

http://tozit.dev/_api/search/query?querytext=’Awesome’

will yield the following result:

image_thumb[1]

Essentially we’re getting a bunch of XML returned from the query which we then have to parse and handle somehow. We can then use the result of this query in our application in whatever fashion we want. Let’s see what a very simple application could look like, utilizing the SharePoint 2013 rest search api’s.

ASP.NET Markup Snippet

As we can see in the following code snippet, we’re simply loading a few jQuery and JavaScript files that we require and we define a Search Box and a Button for controlling our little Search application.

<!-- Load jQuery 1.8.3 -->
<script type="text/javascript" src="/SiteAssets/ScriptArtifacts/jquery-1.8.3.min.js"></script>

<!-- Load our custom Rest Search script file -->
<script type="text/javascript" src="/SiteAssets/ScriptArtifacts/RestSearch.js"></script>

<!-- Add a Text Box to use as a search box -->
<input type="text" value="Awesome" id="searchBox" />

<!-- Add a button that will execute the search -->
<input type="button" value="Search" onclick="executeSearch()" />

<div id="searchResults"></div>

JavaScript logic (RestSearch.js)

I’ve added a file to the project called RestSearch.js, which is a custom javascript file containing the following code which will perform an ajax request to SharePoint using the Search API’s:

// in reality we should put this inside our own namespace, but this is just a sample.
var context;
var web;
var user;

// Called from the ASPX Page
function executeSearch()
{
    var query = $("#searchBox").val();

    SPSearchResults =
    {
        element: '',
        url: '',

        init: function(element) 
        {
            SPSearchResults.element = element;
            SPSearchResults.url = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?querytext='" + query + "'";
        },

        load: function() 
        {
            $.ajax(
                {
                    url: SPSearchResults.url,
                    method: "GET",
                    headers:
                    {
                            "accept": "application/json;odata=verbose",
                    },
                    success: SPSearchResults.onSuccess,
                    error: SPSearchResults.onError
                }
            );
        },

        onSuccess: function (data)
        {
            var results = data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results;

            var html = "<div class='results'>";
            for (var i = 0; i < results.length; i++)
            {
                var d = new Date(results[i].Cells.results[8].Value);
                var currentDate = d.getFullYear() + "-" + d.getMonth() + "-" + d.getDate() + " " + d.getHours() + ":" + d.getMinutes();

                html += "<div class='result-row' style='padding-bottom:5px; border-bottom: 1px solid #c0c0c0;'>";
                var clickableLink = "<a href='" + results[i].Cells.results[6].Value + "'>" + results[i].Cells.results[3].Value + "</a><br/><span>Type: " + results[i].Cells.results[17].Value  + "</span><br/><span>Modified: " + currentDate + "</span>";
                html += clickableLink;
                html += "</div>";
            }

            html += "</div>";
            $("#searchResults").html(html);
        },

        onError: function (err) {
            $("#searchResults").html("<h3>An error occured</h3><br/>" + JSON.stringify(err));
        }
    };

    // Call our Init-function
    SPSearchResults.init($('#searchResults'));

    // Call our Load-function which will post the actual query
    SPSearchResults.load();
}

The aforementioned script shows some simple javascript that will call the Search REST API (the "_api/…" part of the query) and then return the results in our html markup. Simple as that.

Summary

By utilizing the REST Search API we can very quickly and easily create an application that searches in SharePoint 2013.

This can be implemened in SharePoint Apps, Sandboxed Solutions or Farm Solutions. Whatever is your preference and requirements, the Search API’s should be easy enough to play around with.

Enjoy.

Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

So just a simple tip in case anyone bumps into the same issue as I had a while back. Going from Beta to RTM, some things changed in the way you retrieve values using REST in the SharePoint 2013 client object model.

Description & Solution

In the older versions of the object model, you could simply use something like this in your REST call:

$.ajax(
    {
        url: SPSearchResults.url,
        method: "GET",
        headers:
        {
                "accept": "application/json",
        },
        success: SPSearchResults.onSuccess,
        error: SPSearchResults.onError
    }
);

As you can see the "headers" is specifying "application/json".

The fix is simply to swap that statement into this:

$.ajax(
    {
        url: SPSearchResults.url,
        method: "GET",
        headers:
        {
                "accept": "application/json;odata=verbose",
        },
        success: SPSearchResults.onSuccess,
        error: SPSearchResults.onError
    }
);

And that’s a wrap.

Summary

I hope this can save someone a few minutes (or more) of debugging for using old example code or ripping up older projects. I’ve found that a lot of examples online, based on the beta of SharePoint 2013, are using the older version of the headers-statement which inevitably will lead to this problem. So with that said, enjoy.

Introduction

As most if not all of you already know, SharePoint 2013 and Office 2013 has been released to preview/beta and is available for download from Microsoft’s download centers. In this article I will briefly introduce some exciting changes that has been made to the SharePoint 2013 Business Connectivity Services framework. I’ve written a bunch of articles on BCS for SharePoint 2010, and now it’s time to continue that track and introduce the new features available in SharePoint 2013.

Please note that this article is written for SharePoint 2013 Preview, and for the final version of SharePoint some details may have changed

  1. SharePoint 2013: Business Connectivity Services – Introduction
  2. SharePoint 2013: Business Connectivity Services – Consuming OData in BCS Using an App External Content Type
  3. SharePoint 2013: Business Connectivity Services – Talking to your external lists using REST
  4. SharePoint 2013: Business Connectivity Services – Client Object Model
  5. SharePoint 2013: Business Connectivity Services – Events and Alerts

SharePoint 2013 – BCS with REST

In this article we’ll be taking a further look on the new Business Connectivity Services changes and additions in SharePoint 2013. I want to take a quick look and introduce how REST (Representational State Transfer) can be used and also how the Client Object Model can be utilized to communicate with your External Lists and BCS Entities.

So without further delays, let’s dig into the fantastic world of BCS and CSA (Client Side Awesomeness).

Important: The project type in this project, as mentioned in the post where we started building our sample, is a SharePoint-hosted app.

Business Connectivity Services and REST

Utilizing REST in BCS in your SharePoint 2013 environments isn’t really that big of a deal. It’s pretty straight forward. The first thing you should do is take a look at the following link which references the MSDN article about getting started with REST in SharePoint 2013.

MSDN Reference: http://tz.nu/QXfooY

So now that we know that REST is all about, we’re going to look at some code that will utilize REST to retrieve some data. In this sample I’ll continue to build on the solution I created in the previous article.

Final result will look like this

When our first snippet of code will be done, it’ll look something like this where our (in this case) App (page) is loaded:

image

So what the code will do is to pull out the images and links for the videos in the Telerik.Tv OData data source that we created in the previous article, and we’ll be doing this using the REST API’s.

In one big snippet, here’s what the REST call looks like in my App.js:

var context;
var web;
var user;

function sharePointReady()
{
    var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/lists/getbytitle('Video')/items";
    jqxhr = $.getJSON(requestUri, null, onSuccessfullJSONCall);
    jqxhr.error(onErrorInJSONCall);
}

function onSuccessfullJSONCall(data) {

    var outputHtml = "";
    var results = data.d.results;
    var counter = 0;
    for (var i = 0; i < results.length; i++) {
        outputHtml += "<img src='" + results[i].ImageUrl + "' class='brick-image' />";
        counter++;

        if (counter >= 4) {
            outputHtml += "<br/>";
            counter = 0;
        }
    }

    $("#message").html(outputHtml);
}

function onErrorInJSONCall(err) {
    $("#message").text("Unawesome Error: " + JSON.stringify(err));
}

As you can see in the aforementioned code snippet, the calls to the REST API’s are pretty straight forward and I’m only making a quick call to fetch the data asynchronously using the $.getJSON() method.

Lets break it down in sections..

Script part 1: sharePointReady() method call

Since our project type (a SharePoint-hosted App) contains a stub for the Default.aspx page and the App.js files – a method called sharePointReady is defined in the App.js file and in the Default.aspx you have the following block which initiates the call to this method upon loading all other required awesome things:

    <!-- The following script runs when the DOM is ready. The inline code uses a SharePoint feature to ensure -->
    <!-- The SharePoint script file sp.js is loaded and will then execute the sharePointReady() function in App.js -->
    <script type="text/javascript">
        $(document).ready(function () {
            SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () { sharePointReady(); });
        });
    </script>

(Optionally, you can put this code-block in the actual App.js file as well if you’d like – it’s up to you)

When SharePoint is done loading all the required stuff that it needs to function (sp.js), this method is executed. In this sample, I’m making a simple JSON call to the REST API using the syntax http://url/_api/lists/getbytitle(‘ListTitle’)/items which will get all list items in the list named Video:

function sharePointReady()
{
    var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/lists/getbytitle('Video')/items";
    jqxhr = $.getJSON(requestUri, null, onSuccessfullJSONCall);
    jqxhr.error(onErrorInJSONCall);
}

Script part 2: On successful JSON callback, the following block is executed

We’re executing the onSuccessfullJSONCall() when our previous call is successful, and it’ll basically just parse the JSON result and push the items out in a simple HTML structure:

function onSuccessfullJSONCall(data) {

    var outputHtml = "";
    var results = data.d.results;
    var counter = 0;
    for (var i = 0; i < results.length; i++) {
        outputHtml += "<img src='" + results[i].ImageUrl + "' class='brick-image' />";
        counter++;

        if (counter >= 4) {
            outputHtml += "<br/>";
            counter = 0;
        }
    }

    $("#message").html(outputHtml);
}

Script part 3: In case of unawesomeness (failure)

In case the request failed, we’ll be handling that somehow in this method. In this case we’ll just be printing out the error message very quickly to the user:

function onErrorInJSONCall(err) {
    $("#message").text("Unawesome Error: " + JSON.stringify(err));
}

Summary

In this article we took a very quick look at how to get that first REST call working with SharePoint 2013 against our External List called “video”. With the returned result in JSON, we’re parsing it out and simply rendering the result in a more reader-friendly manner as pictures in a simple HTML grid.

So that’ll be it for the REST calls for now. It should get you started and set-up for creating a very simple application that utilizes REST for retrieving data from SharePoint.

More details on working with the REST API’s in SharePoint 2013 will follow later, including how to perform cross-domain queries.

Enjoy.

Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

In this article I will guide your through the process of uploading a document to any chosen document library in SharePoint 2010 through the Client Object Model.

This application has a very simple usage scenario:

  1. Type in the URL to your site where you want to upload your file
  2. Choose one of the available Document Libraries
  3. Click Upload a Document and you’ll get a browse-dialog to choose the file

Example:

1) Enter a servername and click Fetch Libraries
2) Select the Document library you want to upload your file to
image

3) Browse for a local file on your filesystem
image

4) Click the magic button (Upload) and you’ll see your document shoot straight into SharePoint from your client machine(s)
image

How to utilize the Client Object Model in SharePoint 2010 to upload files

The most important thing to learn about when it comes to uploading files with the Client OM is to master the FileCreationInformation class that comes with the Client OM.

Take a look at this complete snippet to see how you can upload a file:

private void btnUploadDocument_Click(object sender, EventArgs e)
{
    string library = listBox1.SelectedItem.ToString();
 
    OpenFileDialog openDialog = new OpenFileDialog();
    openDialog.Multiselect = false;
 
    if(openDialog.ShowDialog() == DialogResult.OK)
    {
        SP.ClientContext ctx = new SP.ClientContext(tbSite.Text);
 
        var web = ctx.Web;
 
        var fciNewFileFromComputer = new SP.FileCreationInformation();
        fciNewFileFromComputer.Content = File.ReadAllBytes(openDialog.FileName);
        fciNewFileFromComputer.Url = Path.GetFileName(openDialog.FileName);
 
        SP.List docs = web.Lists.GetByTitle(library);
        SP.File uploadedFile = docs.RootFolder.Files.Add(fciNewFileFromComputer);
 
        ctx.Load(uploadedFile);
        ctx.ExecuteQuery();
 
        // Tell your user that the file is uploaded. Awesomeness has been done!
        MessageBox.Show(openDialog.FileName + " uploaded to " + library);
    }
}

Things to note here is that I’m currently not changing the authentication for this application. That means it’ll be using your Windows/Domain Credentials.

Learn more about the authentication options here:
http://www.zimmergren.net/archive/2009/11/30/sp-2010-getting-started-with-the-client-object-model-in-sharepoint-2010.aspx

Summary, References & Download

With this sample application you can easily upload any file to any of your SharePoint 2010 document libraries by first entering the URL to the site, then selecting your library and finally browsing for a file and click OK.

Easily enough, you can change or extend this project the way you want it to work if you’ve got specific requirements to upload files using the Client OM.

References

  1. Getting Started with the Client Object Model
  2. FileCreationInformation

Download project

You can download this sample project here.

Enjoy this piece of awesomeness :-)

 

Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

Article 3 in the small BCS-series:

1. SP 2010: Getting started with the Business Connectivity Services (BCS)
2. SP 2010: Programmatically work with External Lists (BCS) in SharePoint 2010
3. SP 2010: Programmatically work with External Lists (BCS) using the Client Object Model

In my previous article in the series, I talked about how easy it is to fetch information using the standard SharePoint server API-approach. In this article I will talk about how you can access data in your BCS data source, by utilizing the Client Object Model.

Client Object Model code to read from the external list

Just like I described in my previous article, you now have the awesome ability to work with data in your External Lists (connected to a data source using BCS) – namely, you can use the standard SharePoint APIs.

Since I’ve shown you how you can do this using the Server Object Model, I thought I could take another spin at it and show you the code for doing basically the same with the Client Object Model.

The underlying data

As with my previous article, I’m still using the same data source as I set up in my first article – the "ProductList" table in my SQL Server database called "Zimmergren_DB"

As seen in the SQL Server Management Studio:
image

Let’s fetch the data using a Windows Forms application that utilizes the Client Object Model!

I’ve designed a Windows Forms application to utilize the .NET Client Object model (in contrary to using the Silverlight client object model or JavaScript client object model).

It looks like this:
 image

When you click the fancy button called "Get External Data", it will use the Client Object Model to fetch the records from the external list (from the SQL server) and display them in a DataGridView. Nothing fancy.

The code!

With no further delays or chit-chat, here’s the simple code!

    // Define the Client Context (as defined in your textbox)
    SP.ClientContext context = new SP.ClientContext(tbSite.Text);
    SP.Web site = context.Web; 

    var ProductList = site.Lists.GetByTitle(tbList.Text); 

    SP.CamlQuery camlQueryAwesomeness = new SP.CamlQuery();  

    IQueryable<SP.ListItem> productItems =
                                      ProductList.GetItems(camlQueryAwesomeness); 

    IEnumerable<SP.ListItem> externalList =
                                      context.LoadQuery(productItems);

    // This is where we actually execute the request against the server!
    context.ExecuteQuery(); 

    // Retrieve the products from the product list using some fancy LINQ
    var productListData = from product in externalList
      select new
      {
          // We’re never pointing to the field at the 0-index
          // because it’s used by the BDC Identity itself. Hence our elements start at 1.
          ProductID = product.FieldValues.ElementAt(1).Value.ToString(),
          ProductName = product.FieldValues.ElementAt(2).Value.ToString(),
          ProductDescription = product.FieldValues.ElementAt(3).Value.ToString()
      }; 

    // Simply clear the rows and columns of the GridView
    gvProducts.Rows.Clear();
    gvProducts.Columns.Clear(); 

    // Add the columns we need (ProductID, Name, Description)
    gvProducts.Columns.Add("ProductID", "ProductID");
    gvProducts.Columns.Add("Name", "Product Name");
    gvProducts.Columns.Add("Description", "Product Description");
    foreach (var product in productListData)
    {
        // For each product in the list, add a new row to the GridView
        gvProducts.Rows.Add(
                                 product.ProductID,
                                 product.ProductName,
                                 product.ProductDescription
                                 );
    }

References and recommended reading

  1. Getting Started with the Client Object Model in SharePoint 2010
  2. Getting Started with Business Connectivity Services in SharePoint 2010

Summary & Download

At this point, I’ve showed you three short articles in which I describe how you can set up a Business Connectivity Services data source – then utilize the Server OM or Client OM to fetch information from that external data storage.

Worth to note is that this is still a Beta product, which of course means that it may differ in functionality and performance in comparison with the final (RTM) version of SharePoint 2010.

Download the complete Visual Studio 2010 project here: [ Zimmergren.SP2010.ClientOM.BCS.zip ]

Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

In this article I will talk about how you can get started with using the Client Object Model in SharePoint 2010. This new object model is introduced in SharePoint Foundation 2010, and does not require SharePoint Server 2010 to be installed.

The Client Object Model is a new object model introduced in SharePoint 2010 which is aimed at making things easier for the developer when developing client-side applications for SharePoint 2010.

Three new client APIs

With the Client Object Model, Microsoft has introduced a set of new APIs to work with to ease the daily tasks of developers.

  • .NET Managed Applications (using the .NET CLR)
  • Silverlight Applications
  • ECMAScript (JavaScript, JScript)

The client APIs provide you as a developer with a subset of the Microsoft.SharePoint namespace which is based on the server-side object model.

Naming conventions

As a small side-note I would like to mention that the objects you are comfortable with calling “SPWeb”, “SPSite”, “SPList” and so on are now named “Web”, “Site”, “List”.

So to conclude the naming convention, the “SP” in the objects has been dropped. Easy enough to remember, right?

Good, let’s move on to some actual code samples to get things fired up!

SharePoint 2010 Client Object Model – Creating your first client-side application

With some fundamental knowledge about the Client OM mentioned above, I would like to take this one step further and actually demonstrate how you can utilize the Client OM in order to create your first client-side application and work with data from SharePoint, instead of using the built-in Web Services.

Step 1 – Creating the Visual Studio project

To be able to follow along with this article, the prerequisites are that you have SharePoint 2010 and Visual Studio 2010 installed in a development environment.

  • Launch Visual Studio 2010
  • Create a new project
  • Choose “Windows Application” and apply the following settings to your project:
    • Target Framework: .NET 3.5
    • Build output: AnyCpu (or x64)

As you can see we are specifically targeting .NET 3.5 since this is the version of the framework that SharePoint 2010 is based on.

Also notice that we are changing the build output from x86 (unsupported!) to AnyCpu or x64 in order to be able to compile and run this project properly.

You should now have an empty Windows Application project like so:   
ScreenShot001

 

Step 2 – Adding the Client Object Model references

Next, we need to add references to the Client Object Model in order to be able to work with the client-side APIs from our awesome Windows Application.

  1. Right click the “References” node and choose “Add Reference”  
    ScreenShot002
  2. Choose “Browse
    1. Navigate to this folder:
      C:Program FilesCommon FilesMicrosoft SharedWeb Server Extensions14ISAPI
    2. Select these two files:
      1. Microsoft.SharePoint.Client.dll
      2. Microsoft.SharePoint.Client.Runtime.dll 

         ScreenShot004
  3. Make sure they are included in the references of your project: 
    ScreenShot005
  • Add the following using-statement in your class (note the last line!): 
    ScreenShot008

Alright – that was easy enough. Adding the references shouldn’t be any problems. Moving on the the more interesting part – getting our first client object model application up and running!

Step 3 – Make our Windows Application pull out some data from SharePoint

Now that you’ve created your Windows Application, targeted the correct framework and platform, added the Client object model references – we’re ready to take on some Client Object Model action!

Adding the necessary controls to the form
  • Add the following controls to your Windows Application:
    • A new ListBox control
    • A new Button control
    • A new TextBox control (Set multiline = true, readonly = true etc to make it look like mine if you want..)

ScreenShot006

Adding some code-logic to fetch the lists on a particular site and populate the ListBox
  • Double-click the Button that you’ve created and add the following code logic:

private void btnGetLists_Click(object sender, EventArgs e)
{
    lbLists.Items.Clear(); 

    using (SP.ClientContext ctx = new SP.ClientContext("http://zimmer"))
    {
        var web = ctx.Web; 

        ctx.Load(web);
        ctx.Load(web.Lists); 

        ctx.ExecuteQuery(); 

        foreach (SP.List list in web.Lists)
        {
            lbLists.Items.Add(list.Title);
        }
    }
}

  • Double-click the ListBox that you’ve created and add the following code logic:

private void lbLists_SelectedIndexChanged(object sender, EventArgs e)
        {
            using (SP.ClientContext ctx = new SP.ClientContext("http://zimmer"))
            {
                var list = ctx.Web.Lists.GetByTitle(lbLists.SelectedItem.ToString());

                ctx.Load(list);
                ctx.ExecuteQuery(); 

                string infoAboutList =
                    string.Format("Title: {0}ItemCount: {1}IsHidden: {2}",
                    list.Title + Environment.NewLine,
                    list.ItemCount + Environment.NewLine,
                    list.Hidden.ToString()); 

                textBox1.Text = infoAboutList;
            }
        }

Things to note:

Running the simple application

When you decide to run this awesomely simple application, it will look something like this: 
ScreenShot009

With a few simple lines of code you have created your first Client-side application for SharePoint 2010.
Of course we could elaborate this sample to make it way more complex, but this is a teaser for you to get started with the client object model.

Step 4 – Authentication Options for our application

Quite naturally, the question of how you can authenticate to SharePoint often pops up when I do my SP 2010 training and seminars. With that said, I’ll walk you through the different authentication options you’ve got for your client application.

Basically there are three (3) authentication options you can use when you’re working with the Client Object Model in SharePoint 2010:

  • Anonymous
  • Default
  • FormsAuthentication

ScreenShot010

If you do not choose an authentication method in your code, the application will default to using the client’s Windows Credentials (DefaultCredentials)

Example 1: Using anonymous authentication

ctx.AuthenticationMode = SP.ClientAuthenticationMode.Anonymous;

Example 2: Using Forms Authentication with the Client Object Model

SP.FormsAuthenticationLoginInfo formsLoginInfo = 
new SP.FormsAuthenticationLoginInfo("TobiasZimmergren", "SecretPassword");

ctx.AuthenticationMode = SP.ClientAuthenticationMode.FormsAuthentication;

ctx.FormsAuthenticationLoginInfo = formsLoginInfo;

When you call the Forms Authentication, it will automatically call the Authentication Web Service for you and return the authenticated cookie.

Summary & Downloads

With very little effort, we have created a new Windows Form application that can be run as a client-side application – without the need of SharePoint to be installed on that machine.

Easy enough we have done so without calling any Web Services.

With that said, you should now at least be updated on how you create your first few Client Object Model applications, and be able to start your own project(s) using this new awesome OM.

ENJOY!

Download my sample project

Download my awesome sample project here