Home
April 23
Creating a SharePoint Server 2013 Farm using Windows PowerShell Scripts

At Critical Path Training, we have an ongoing need to build virtual machines (VMs) for our students to use as they work on the lab exercises which are part of our SharePoint 2013 training courses. Until recently, we have been configuring our student VMs using hundreds of manual steps including the creation the service applications using the Farm Configuration Wizard (FCW). We are now switching over to a process for building our VMs where we create and configure the required SharePoint Server 2013 farm using a set of PowerShell scripts. We have found this makes the building of a VM go much faster and it provides the benefit of creating a more stable and predictable environment to write and test our lab exercises.

Since Critical Path Training is an education company, it makes sense for us to give these script away to our students and to anyone else that wants to leverage them or to use them as an education resource to get up to speed on writing PowerShell scripts in a SharePoint 2013 environment. We have posted a zip file to our members site named SP2013FarmBuildoutScripts.zip which you can download using the The SharePoint Server 2013 Farm Build-out scripts (v1.0) link on the Member Downloads page of the CPT website. If you download this zip file, you will find it contains five Windows PowerShell scripts and two Word documents which explain how the scripts work and how you go about running them.

I must acknowledge Gary LaPoint of Aptillon. His book titled Automating Microsoft SharePoint 2010 Administration with Windows PowerShell 2.0 is still the best reading resource available today for getting up to speed on Windows PowerShell scripting and understanding how to use Windows PowerShell in SharePoint 2013 environments as well as SharePoint 2010 environments. Also, thanks to Spencer Harbar and his blog for providing the SharePoint community with the details required to get the User Profile Synchronization Service up and running without driving yourself crazy.

I wrote these PowerShell scripts knowing that many Critical Path Training students would be opening them in an effort to understand how to write the PowerShell code required to automate the creation of a SharePoint 2013 farm. I have intentionally simplified the PowerShell code required to make it easier for students to grasp what is going on upon a first read.

There are a few important assumptions that I used to create these scripts. First, these scripts have been written to serve more as an educational resource and not as much as an example of hardened PowerShell scripts which are ready to run in a production environment. Secondly, the SharePoint 2013 farm created by these scripts will be built on a single server. In other words, there is no logic in these scripts to deal with configuration complexity of a multi-server farm. Finally, these scripts do not automate the installation of SharePoint Server 2013 or any other product. Therefore, you must install all the required software including SQL Server 2012 with SP1, SharePoint Server 2013 and Workflow Manager before you can successfully run these scripts.

These scripts focus exclusively on how to configure a SharePoint farm once the product has already been installed. If you want or need to automate the installation of the SharePoint product, you should refer to Gary’s book I mentioned earlier which provides an approach and demonstrates the PowerShell code for doing so.

February 28
When is a SharePoint-hosted App not a SharePoint-hosted App

Scot Hillier and I recently shipped our new book titled Microsoft SharePoint 2013 App Development. Since the book hit the shelves a few weeks ago, we have gotten some feedback over something I discussed at the end of chapter 1 in the section titled Trapping app lifecycle events. Here is the paragraph in question.

The architecture of app events is based on registering app event handlers in the app manifest that cause the SharePoint host environment to call out to a web service entry point in the remote web. Due to the architecture’s reliance on a server-side entry point, app events are not supported in SharePoint-hosted apps. Therefore, you can only use app events in autohosted apps and provider-hosted apps.

My statement that “app events are not supported in SharePoint-hosted apps” has caused a bit of confusion. Here is the issue. You can create a Visual Studio 2012 project based on the SharePoint-hosted app project type and then configure the project to support app events. For example, imagine you create a simple SharePoint-hosted app named App1 as shown in the following screenshot.

Once you have created the new project, you can inspect the project properties in the standard Visual Studio properties window and you will see the three properties for app events including one named Handle App Installed. So, now comes the $1,000,000 question. Can you enabled the Handle App Installed property in a SharePoint-hosted app project? The answer to this questions is '”yes you can”.

At this point, I am beginning to look like a big fat liar of the pants-on-fire type. You are thinking, “Ted, you told us you cannot support events in a SharePoint-hosted app. What’s up with that.” Well, I still stand behind my statement. Look what happens to your Visual Studio solution when you add support for app events. Visual Studio 2012 automatically adds a ASP.NET project named App1Web to implement a remote web so that it can then adds a WCF entry point named AppEventReceiver.svc. Thus, Visual Studio has effectively converted the project from a SharePoint-hosted app project to a provider-hosted app project. I cover this point in detail every time I teach our deep dive developer’s class The Great SharePoint Adventure 2013.

My controversial statement above reflects the theory behind the SharePoint app model but not necessarily the mechanics of how things work or how things appear in the Visual Studio 2012 project system. Don’t get hung up on the fact that you have created a new Visual Studio project from the SharePoint-hosted app project template. That doesn’t mean the project will always continue to be a SharePoint-hosted app. You have heard the statement “people change”. Well, projects can change too. And any SharePoint-hosted app project that wants to support app events must change its limited ways and become either a provider-hosted app or an autohosted app.

August 27
The SharePoint Server 2013 Preview Virtual Machine Setup Guide

Back in 2010, Andrew Connell (AC) and I created a step-by-step guide to build out a virtual machine (VM) environment for SharePoint 2010 development. When we published it on the Members page of the Critical Path Training website, it quickly became our most popular download. Since we released the SharePoint 2010 setup guide, I have met many developers and IT Pros that swear by this document and use it as their ultimate reference because neither Microsoft nor any other organization has published anything even close to being as complete and as comprehensive.

When Microsoft announced the first public beta of SharePoint 2013 last month, AC and I began to receives queries from friends and colleagues about when we would be publishing the setup guide for this new version of SharePoint. Well, first of all, I must say setting up the environment for SharePoint 2013 brings new complexities that were not part of SharePoint 2010. For example, the development environment now requires two virtual machines instead of one because you cannot configure the required support to run SharePoint 2013 workflows on a computer that is a domain controller. There is also changes to the way Microsoft is recommending to create Web Applications to support host header site collections.

My work in all this was pretty. All I had to do was write this blog entry. My partner, AC, has done all the actual work to write up the new SharePoint 2013 version of our VM setup which was published earlier today on our website as a free download. You can download it now from the link below. Note that this download requires you to have a member account with the Critical Path Training website. If you do not already have a member account, you will be required to register for one with a valid email account. Enjoy and happy developing.

Download the SharePoint Server 2013 Preview Virtual Machine Setup Guide

August 24
Call Me Maybe for Developers

Sure, we've all heard the pop song by Carly Rae Jepsen and seen the cute lip dub videos by the Harvard University baseball team, the Miami Dolphins Cheerleaders and the US Swim Team. But seeing it redone by professional software developers many of which I have known for over a decade was simply awesome.

We can dance, we can dress and we can lip-sync with the best of them
August 14
SharePoint app code calls into SharePoint using CSOM and REST calls

This is the third post in a series of blog posts on the SharePoint app model. Here is the outline of this series.

If you haven’t read the previous posts in the series, you should consider reading them before continuing with this post. These earlier posts explain the basic architecture and the differences between SharePoint-hosted apps and cloud-hosted apps and discuss the role of the app web. This post assumes you already understand these concepts.

Getting Started with CSOM and the REST API

SharePoint apps cannot run any server-side code inside the SharePoint host environment. Therefore, they cannot use the SharePoint server-side object model. Instead, a SharePoint app must call from across the network to communicate with the SharePoint host environment. The two options that you have to accomplish this are using the client-side object model (CSOM) and issuing Web service calls based on the new SharePoint 2013 REST API.

As you recall, a SharePoint app can contain two fundamental types of code. First, a SharePoint app can contain client-side code that runs in the browser which is most often written in JavaScript. Secondly, a SharePoint app can contain server-side code that runs in the remote web associated with the app. In this post I will demonstrate writing this type of server-side code in C# although you can alternatively write it in VB or a plethora of other languages as well.

When you are designing a SharePoint app that must communicate with the SharePoint host environment, you must make two choices. First, you must decide whether to use client-side code or server-side code. Second, you must decide between CSOM and the REST API. This means there are four permutations for writing code in a SharePoint app that programs against a SharePoint site.

  1. Client-side JavaScript that uses CSOM
  2. Client-side JavaScript that uses the REST API
  3. Server-side C# code that uses CSOM
  4. Server-side C# code that uses the REST API

As you begin to consider whether to use CSOM or the REST API, you'll find that there is a good deal of overlap between them. Therefore, you will encounter scenarios where you could choose either one to accomplish the same goal. As a basic rule of thumb when getting started, you will find that CSOM is easier to use when programming in a managed language such as C#. You might also find that the REST API is easier to use when writing client-side JavaScript code especially when you are using today's most popular JavaScript libraries such as jQuery. However, there are still occasions where it is beneficial or necessary to write client-side code using CSOM or server-side code against the REST API.

My goal in writing this blog post is to get you started programming with each of these four programming styles listed above. However, I don't want to introduce too many topics at once so I will attempt to introduce the important concepts of CSOM and the REST API in isolation from other related topics. In this post I will avoid any detailed discussion of app authentication or app permissions. While these topics are essential in SharePoint app development, I think it's best to defer introducing them until later blog posts in this series.

In this post I will demonstrate using CSOM and the REST API by programming against the app web associated with a SharePoint app. My reason for doing this is that a SharePoint app by default has full permissions on its app web. Therefore, this scenario eliminates the need to deal with explicit app permission requests. I will revisit this topic in a later post in this series and provide you with the details you need to program against the host web which will require you to modify an app with explicit permission requests.

When I discuss writing server-side code in a cloud-hosted app in this post, I will concentrate on a scenario which involves internal authentication instead of external authentication. A scenario which involves internal authentication doesn't require explicit code to manage authentication. This will allow me to focus exclusively on the fundamentals of using CSOM and the REST API. In the next blog post in this series, I will center the discussion on app authentication and we will take a dive deep into the differences between how app authentication works in the Office 365 environment versus an on-premises farm.

I have complimented this blog post with a few sample projects I have written with the Visual Studio 2012 Release Candidate. The download is named TheCsomRestPartyPack.zip and it can be downloaded from here in the members page of the Critical Path Training website. If you are not already a member, you can sign up by supplying your email address.

Writing Client-side JavaScript using CSOM

It's pretty easy to get started with programming client-side JavaScript using CSOM. That's because all the code you need to get up and running is automatically added by Visual Studio 2012 and the SharePoint Tools when you create a new SharePoint-hosted app. Note that when you create a new SharePoint-hosted app project, Visual Studio also adds the JavaScript source file and required links for the jQuery core library. If you are beginning to develop SharePoint apps and you haven't yet become familiar with jQuery, now is the time to pick up a jQuery book or to work through some of the tutorials you can find at jQuery.com.

Now imagine you have just created your first SharePoint-hosted app project in Visual Studio 2012. Let's start off by examining the small bit of JavaScript code that Visual Studio 2012 adds into the app's start page named default.aspx.

$(document).ready(function () {
  SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () { sharePointReady(); });
});

This code uses the jQuery document ready event handler and an anonymous function to trigger its execution just after the browser has finished loading the DOM and the elements of the page are ready to access. Inside the anonymous function, there is a single line of code that calls to a JavaScript function supplied by SharePoint Foundation named SP.SOD.executeFunc.

It's important that you understand why the call to SP.SOD.executeFunc is necessary. It has to do with forcing the download of an essential JavaScript source file named sp.js. While the standard SharePoint master pages link to this JavaScript source file and several others, they are not linked in such a way that they are guaranteed to be downloaded and available for use in the browser before the page is displayed to the user. Instead, they are linked using a script-on-demand (SOD) mechanism.

The benefit of SOD to the user is that pages are displayed faster. More specifically, the user isn't required to wait until a bunch of JavaScript code downloads from across the network before seeing a page. The issue caused by SOD for a developer like yourself is that you must supply code to force the download of specific JavaScript source files such as sp.js before you can call the functions they contain. The file named sp.js is particularly important because it contains the core functions of CSOM.

If we examine the parameters passed in the call to SP.SOD.executeFunc, you can see the first two parameters pass the name of the sp.js source file and a JavaScript function inside that source file named SP.ClientContext.

SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () { sharePointReady(); });

When you call SP.SOD.executeFunc, the method's implementation downloads sp.js and then executes a function inside it named SP.ClientContext. The execution of this function initializes the client context which represents the heart and soul of the CSOM programming model. After that, the method's implementation executes whatever function that has been passed as the third parameter. The code supplied by Visual Studio provides an anonymous function that executes a function named sharePointReady. You can rewrite this code to simplify it and clean it up a bit to provide the generic starting point for any client-side code that uses CSOM.

$(function () {
  SP.SOD.executeFunc('sp.js', 'SP.ClientContext', sharePointReady );
});

function sharePointReady() {
  // code added here can begin to use CSOM
}

The important thing to observe here is that there is a pattern where you force the download of sp.js and then call a custom function where it is safe to use CSOM. If you use the code supplied by Visual Studio, the function where you can begin using CSOM is named sharePointReady. Now let's look at a longer code listing where the sharePointReady method is implemented to retrieve the Title property of the app web using CSOM.

$(function () {
  SP.SOD.executeFunc('sp.js', 'SP.ClientContext', sharePointReady);
});

// create page-level variables to hold client context and web
var context;
var web;

function sharePointReady() {

  // assign values to page-level variables
  context = new SP.ClientContext.get_current();
  web = context.get_web();

  // provide CSOM with instructions to load info about current web
  context.load(web);

  // issue asynchronous call across network for CSOM to carry out instructions
  context.executeQueryAsync(onSuccess, onFail);
}

function onSuccess() {
  $("#message").text("Site title: " + web.get_title());
}

function onFail(sender, args) {
  $("#message").text("Error: " + args.get_message());
}

The code in this listing creates two page-level variables named context and web to reference two CSOM objects. The first CSOM object is the client context which is referenced using a call to new ClientContext.get_current(). You can think of the client context as your connection back to the site which served up the current page. The second CSOM object referenced by the web variable represents the current SharePoint site (the app web in this example) which is retrieved by calling the get_web method on the client context object.

One of the most important concepts in CSOM programming is that many of its objects have to be initialized by calling across the network before their properties contain meaningful values. For example, the object referenced by the web variable does not have valid property values after the call to get_web. Instead, you must call context.load(web) to provide CSOM with instructions to populate its property values and then you must call context.executeQueryAsync to make an asynchronous call across the network in which CSOM will actually retrieve the property value for the current site and populate the object referenced by the web variable.

It's also important to observe that the call across the network in this example is made asynchronously. If client-side code running in the browser were to make a call across the network in a synchronous fashion, it would produce the undesired effect of freezing the user interface. This would result in an unacceptable user experience so it must be avoided. When writing client-side code which calls from the browser across the network you must ensure you are using asynchronous calls which is accomplished in CSOM by calling the context.executeQueryAsync method.

When you call context.executeQueryAsync you must pass two callback functions which I have named onSuccess and onFail. The first callback function named onSuccess is called by CSOM if the call across the network completes without errors. The second callback function named onFail is what CSOM calls if the call across the network experiences an error. In this simple example the onSuccess function has been written to retrieve the Title property of the app web by calling web.get_title. It also uses the jQuery style of coding to write the Title property value into the div elements with the id of message where it can be seen by the user.

$("#message").text("Site title: " + web.get_title());

In the sample code I have added to TheCsomRestPartyPack.zip, I have included a SharePoint-hosted app project named SharePointAppCSOMDemo. This SharePoint app contains client-side JavaScript code which demonstrates getting more involved with the CSOM. Here is a screenshot of the app's start page which shows its basic functionality.

For example, there is JavaScript code in the SharePointAppCSOMDemo project which demonstrates updating the app web's Title property, adding a new list and switching back and forth between a custom master page and the standard master page for SharePoint-hosted apps named app.master. For example, you can use CSOM to switch the master page for the current site using the following JavaScript code.

function onUseCustomMaster() {
  var masterUrl = web.get_serverRelativeUrl() + 
                  "/_catalogs/masterpage/CustomApp.master";
  web.set_masterUrl(masterUrl);
  web.update();
  ctx.executeQueryAsync(refreshPage, onError);
}

I will now conclude this section by summarizing some of the key points of programming client-side JavaScript using CSOM. First, your code must ensure that the file named sp.js has been downloaded before you can use any functions or objects provided by CSOM. Second, you must initialize certain CSOM objects before you use them. Finally, you initialize CSOM objects and perform other actions such as creating new lists by calling across the network in an asynchronous fashion using a call to executeQueryAsync.

Writing Client-side JavaScript using the REST API

As you have probably noticed over the last few years, REST-based Web services have become increasing popular throughout the IT industry and particularly within Microsoft. SharePoint 2013 introduces a new REST API that expose the much of the same functionality that is available through CSOM. This is great news for developers writing client-side JavaScript code because the new REST API often results in code that is easier to write and maintain when compared to programming with CSOM. The new REST API also provides essential entry points for servers-side code which does not run on the.NET Framework which does not have the ability to use CSOM. Because of this, you can say that the new REST API makes SharePoint 2013 a much more "open" platform.

A significant percentage of the new REST API has been created in accordance with a emerging web-based protocol known as Open Data Protocol (OData). The OData protocol has been designed to allow client applications to query and update data using standard HTTP verbs and to send and retrieve data in standardized formats such as Atom, JSON or plain XML. The OData protocol also includes provisions for common data retrieval tasks such as filtering, ordering and pagination. If you are planning to become proficient with the new REST API in SharePoint 2013, you will find that the OData website is a very useful resource.

http://www.odata.org/

Programming against the REST API in SharePoint 2013 is quite different than programming with CSOM. The first thing you will notice is that using the REST API does not require a SharePoint-specific JavaScript class library. Therefore, you do need to supply code to force the download of a JavaScript source file. Instead, the REST API requires you to parse together URLs that represents target objects such as sites, lists and items. Therefore, your first challenge is learning how to parse together these URLS according to the rules outlines by the OData protocol along with additional specifics added by SharePoint 2013. For example, you might be required to parse together an URL whose target object is a SharePoint site. Additionally, you might be required to add a query string parameter to indicate which property or properties you want to retrieve.

As you get started with the REST API, you can begin learning how to create the URLs required for querying data just using a browser. For example, you can type an URL into the address bar of the Internet Explorer and execute the request against a SharePoint site to see the results. For example, imagine there is a SharePoint 2013 site accessible at http://wingtipserver. You can type the following URL into the browser to execute an HTTP GET request to retrieve the Title property of the current site.

http://wingtipserver/_api/web/?$select=Title

The URL is made up of three basic parts. First, there is the base URL of http://wingtipserver/ that points to the site. In OData terminology this is known as the service root. The next part of the URL is the resource path that points to the target site which in this case is _api/web/. Finally, there are the query options which involve a single query string parameter in this case of ?$select=Title which tells the SharePoint host environment to return the site's Title property. When you execute a GET request through the browser using this URL, the SharePoint host environment returns the following XML result.

<entry xmlns="http://www.w3.org/2005/Atom" 
       xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" 
       xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" >

  <id>http://wingtipserver/_api/Web</id>
  <category term="SP.Web" />
  <content type="application/xml">
    <m:properties>
      <d:Title>Wingtip Test Site</d:Title>
    </m:properties>
  </content>

</entry>

By default, the SharePoint host environment responds to REST calls by returning XML which is structured according to a standard known as Atom Syndication Format. However, when making REST calls with JavaScript code it is often easier to request that results are returned in an easier-to-use format known as JavaScript Object Notation (JSON). This can be accomplished by adding the accept header to the GET request. For example, if you submit a GET request using the exact same URL and you include the accept header with a value of application/JSON, the result that comes back now looks like this.

{
  "d": {
    "__metadata": {
      "id": "http://wingtipserver/_api/Web",
      "uri": "http://wingtipserver/_api/Web",
      "type": "SP.Web"},
    "Title": "Hello REST"
  }
}

When the result is returned in JSON format, it can be easily transformed into a JavaScript object. This means you can access the data returned from a REST call without any need to parse through XML. This is a significant productivity win in many scenarios. If you use the getJSON function supplied by jQuery, you don't even have to convert the JSON result from text into a JavaScript object because that is done for you automatically.

Now I have covered enough background information to present the 'hello world' JavaScript code behind the start page of a SharePoint-hosted app which uses the REST API. To be consistent with the earlier example I showed using CSOM, our first REST API example will query the Title property of the app web. Note that the code in the following listing uses a standard JavaScript variable named _spPageContextInfo which the SharePoint host environment adds to every page.

$(function () {

  // parse together URL for HTTP GET request
  var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/Web/?$select=Title";

  // transmit GET request to SharePoint host environment
  jqhxr = $.getJSON(requestUri, null, onSuccess);
  jqhxr.error(onFail);
});

function onSuccess(data) {
  var appWebTitle = data.d.Title;
  $("#message").text(appWebTitle);
}

function onFail(errorObject, errorMessage) {
  $("#message").text("Error: " + errorMessage);
}

As you can see, the _spPageContextInfo variable exposes a property named webAbsoluteUrl which makes it possible to determine the service root of the current site. You parse together the URL required by taking this service root and appending the resource path to specify a target object (e.g. the current site) and a query string to include any query options you need. Once you have parsed together the correct URL, you can then transmit the HTTP GET request to the SharePoint host environment using the jQuery function named getJSON.

Just as in the case of programming against CSOM, you should ensure that calls across the network are made using an asynchronous technique so you do not freeze the user interface of the browser. Fortunately, all the jQuery functions such as getJSON, ajax and load have been implemented with asynchronous behavior. You just need to supply callback methods which are automatically executed when the result is returned from across the network. In this simple example, the callback method named onSuccess executes and passes a parameter named data with represents the JSON result. When using the getJSON method, you will find that the callback method passes a parameter which has already been converted from text into a JavaScript object. You can access the Title property of the SharePoint site by simply accessing the Title property of a JavaScript object.

function onSuccess(data) {
  var appWebTitle = data.d.Title;
  $("#message").text(appWebTitle);
}

The sample code in TheCsomRestPartyPack.zip contains a SharePoint-hosted app project named SharePointAppRESTDemo. This sample SharePoint app creates a Customers list in the app web at installation time and populates this list with a handful of sample customer items. I created the Customers list in this SharePoint app mainly so the app can demonstrate how to program against list items using the REST API. I also wrote all the JavaScript code in this app that is needed to demonstrate the full set of CRUD (create, read, update and delete) functionality that the REST API makes possible. Here's a screenshot of the start page and the Add New Customer dialog which will give you an idea of what this app can do.

I will leave it to you to explore all the code in this sample app. There is far too much JavaScript code to walk through it all in this post. However, I'd like to present a few chosen listings of the JavaScript code from this app to make a few more points for those getting started.

First, I would like to discuss returning a set of data in JSON format and rendering it as HTML. This is often accomplished using a separate JavaScript library. In this sample app I am using one of my favorites which is jsrender. This JavaScript library is based on its own unique template syntax which makes it fairly easy to convert a JSON result into an HTML element such as a list or a table. Here is a slightly watered-down version of the code in the SharePointAppRESTDemo app that returns the Customers list as a JSON result and then uses the jsrender library and its powerful template syntax to convert the list items into an HTML table for display on the app's start page.

function onDataReturnedListing(data) {

  // clear out the target element on the start page
  $("#results").empty();

  // obtain the JavaScript object array from the JSON result
  var odataResults = data.d.results;

  // create the header row for the HTML table
  var tableHeader = "<thead>" +
                      "<td>Last Name</td>" +
                      "<td>First Name</td>" +
                      "<td>Work Phone</td>" +
                    "</thead>";
  
  // create a new table using jQuery syntax
  var table = $("<table>", { id: "customersTable" }).append($(tableHeader));

  // create a rendering template using jsrender syntax
  var renderingTemplate = "<tr>" +
                            "<td>{{>Title}}</td>" +
                            "<td>{{>FirstName}}</td>" +
                            "<td>{{>WorkPhone}}</td>" +
                          "</tr>";

  // use the rendering template to convert JSON result to an HTML table
  $.templates({ "tmplTable": renderingTemplate });
  table.append($.render.tmplTable(odataResults));

  // write the table into a target element on the start page
  $("#results").append(table);

}

From this code you should be able to see the value of using the jsrender library. It makes it so much easier to write and maintain JavaScript code that converts data from the JSON format into HTML elements. I find that I am more impressed with the jsrender library and what it can do each time I use it. To be fair and impartial I must admit that my friends, AC and Scot, both tell me they prefer the knockout library hands down over jsrender. But then again, they are both Republican golfers and so I have to take what they say with a grain of salt. They probably just prefer knockout because they are accustom to having someone else do all the hard work for them and to have this work done out of sight where they don't have to watch. Oh, but I digress.

I'd like to show one final code snippet from the SharePointAppRESTDemo app to give you an idea of how to write code that actually updates list data within a SharePoint site. Here is the JavaScript code that is used to add new items to the Customers list.

// get new Customer data from new customer dialog
var LastName = returnValue.LastName;
var FirstName = returnValue.FirstName;
var WorkPhone = returnValue.WorkPhone;

// parse together URL with resource path for target list
var requestUri = _spPageContextInfo.webAbsoluteUrl +
                 "/_api/Web/Lists/getByTitle('Customers')/items/";

// create JavaScript object to create headers for request
var requestHeaders = {
  "accept": "application/json",
  "X-RequestDigest": $("#__REQUESTDIGEST").val(),
}

// create JavaScript object with new customer data
var customerData = {
  __metadata: { "type": "SP.Data.CustomersListItem" },
  Title: LastName,
  FirstName: FirstName,
  WorkPhone: WorkPhone
};

// convert customer data from JavaScript object to string-based JSON format
requestBody = JSON.stringify(customerData);

// transmit HTTP POST operation to SharePoint host environment to add new list item
$.ajax({
  url: requestUri,
  type: "Post",
  contentType: "application/json",
  headers: requestHeaders,
  data: requestBody,
  success: onSuccess,
  error: onError
});

I'd like to point out that the call to the ajax function includes a header named X-RequestDigest. This header is important because it contains an essential piece of information known as the form digest value. The SharePoint host environment relies on the form digest value to protect against replay attacks. The important thing to understand is that the SharePoint host environment will reject any REST call that attempts to modify content which does not contain the X-RequestDigest header with a valid form digest value.

Fortunately, it is pretty easy to obtain the form digest value because it gets added to all pages by the standard SharePoint master pages in a div element with an id of __REQUESTDIGEST. Therefore, you can read the form digest value on any standard page served up by the SharePoint host environment using this jQuery syntax.

var formDigestValue = $("#__REQUESTDIGEST").val()

You should also observe how data for the new list item is passed from this JavaScript code to the SharePoint host environment. It is done by creating a JavaScript object that is converted into a text-based JSON format using a call to the JSON.stringify function. The JavaScript object is initialized with properties named to match the site columns in the target list along with a property named __metadata. The __metadata property must be initialized with an inner JavaScript object that contains a property named type. The type property in this example is given a value of SP.Data.CustomersListItem which is a predictable type name given by the SharePoint host environment when you create a list with a title of "Customers". In other scenarios you might have to query a SharePoint list using the REST API in order to determine what value should be assigned to the type property when adding new items to a list.

Before moving on to server-side programming, let's summarize some of the key points of programming client-side JavaScript using the REST API. First, you must learn how to parse together the URLs required for making REST API calls according to the OData protocol and the specifics used by SharePoint 2013 to create resource paths which can be used to reference target objects such as sites, lists and list items. Second, passing input data and returning results in JSON format usually provides the easiest way to program in JavaScript. Third, the jQuery library is your friend because it provides convenient functions to transmit HTTP requests to the SharePoint host environment using whatever HTTP verb is required for the current request at hand. Last of all, you should get to know some of the great JavaScript libraries that are available for free. I demonstrated using jsrender in this post but there is also a great deal of excitement around other libraries such as knockout and SignalR.

Writing Server-side Code in Cloud-hosted SharePoint Apps

Now we will turn our attention from client-side programming to server-side programming. One favorable aspect of server-side programming for many experienced .NET developers is that you can leave behind the loosely-typed nature of JavaScript and begin coding in C# or VB which provides the benefits of compile-time type checking, better IntelliSense and full access to the libraries of the .NET Framework.

Also keep in mind that your server-side code runs in a standard ASP.NET application and not inside the SharePoint environment. Therefore, you don't have to worry about many of the strange constraints and SharePoint-isms that require your attention when writing server-side code in a farm solution such as crippling the local SharePoint farm's performance by forgetting to properly dispose of SPSite objects in memory.

For the sample code I will use to demonstrate server-side programming in this post, I will use two SharePoint app projects that have been designed to use internal authentication and to programming exclusively against the app web. I am using this scenario to simplify things because a cloud-hosted SharePoint app that uses internal authentication does not require explicit programming to manage app authentication. By eliminating any code to deal with app authentication, I can focus on the core fundamentals of CSOM and REST API programming.

The other nice thing about cloud-hosted SharePoint app projects that use internal authentication is that you can just open them in Visual Studio and test them out by pressing the {F5} key. However, you should take note that you must have your development environment configured with a local SharePoint 2013 farm to run the cloud-hosted app projects I will be discussing over the next two sections. If you want to learn about how I configured these sample apps to use internal authentication, you can read my post titled Configuring a Cloud-hosted SharePoint App to Use Internal Authentication.

Writing Server-side C# code that uses CSOM

Getting started with with server-side CSOM code in a cloud-hosted app is easier than it is with client-side JavaScript code. The first reason is that you have the benefit of compile-time type checking. The second reason is that you are able to use synchronous execution instead of asynchronous execution so your server-side code doesn't require callback methods like the JavaScript code I showed earlier.

The C# code I will show in this section is available in TheCsomRestPartyPack.zip download in a sample SharePoint app project named CloudAppCsomDemo. While this sample app will not win any awards for user interface design, it provides some simple examples of server-side C# code and a few ideas for cloud-hosted app designs. Here is a screenshot of the app's start page.

Let's see how easy it is to get started with programming CSOM on the server. The CloudAppCsomDemo app contains the following server-side C# code in the Page_Load method of the app's start page which retrieves the incoming SPAppWebUrl query string parameter with the app web URL and then uses CSOM to synchronously retrieve the app web's Title property and display it on a ASP.NET label control named lblAppWebTitle.

protected void Page_Load(object sender, EventArgs e) {

  // retrieve app web URL from incoming query string parameter
  string appWebUrl = Page.Request["SPAppWebUrl"];

  using (ClientContext clientContext = new ClientContext(appWebUrl)) {
    Web appWeb = clientContext.Web;
    clientContext.Load(appWeb);
    clientContext.ExecuteQuery();
    lblAppWebTitle.Text = appWeb.Title;
  }
}

At this point you're probably thinking that writing server-side code using CSOM looks pretty easy compared to writing it with client-side JavaScript. Well, in many scenarios that is indeed the case. However, there is a catch. If you add server-side CSOM code like this behind the start page of a cloud-hosted app, the user will be sitting around and waiting for the app's start page to load while your code is making round trips between the remote web and the SharePoint host environment. If your code is doing a significant amount of initialization work with the CSOM, the wait time to load and display the start page might approach an unacceptable amount of time.

A better design can often result from avoiding server-side CSOM code behind the app's start page because it results in a start page which loads faster without unnecessary delay. While many cloud-hosted apps will require CSOM code at start-up, this code can be moved into secondary pages and handlers which can be called from the start page asynchronously using client-side JavaScript. Let's walk through an example of how to create such a design.

We will begin be adding code to the app's start page Default.aspx to take the incoming SPAppWebUrl query string parameter which points to the app web URL and to cache it for other pages and handlers to use.

// code added to start page
protected void Page_Load(object sender, EventArgs e) {

  // cache url to web app for other pages
  Cache["SPAppWebUrl"] = Page.Request["SPAppWebUrl"];
}

The next step is to create a secondary page or handler which does the actual work against the CSOM. I have found that adding a Generic Handler project item (i.e. a handler with an .ashx extension) into the ASP.NET project for the remote web provides an easy and effective way to create a server-side entry point which can be called from client-side JavaScript on the start page. For example, you can create a generic handler named appWebTitle.ashx and implement it with the following code to return the app web Title property as simple text.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.SharePoint.Client;

namespace CloudAppCsomDemoWeb.Pages {

  public class appWebTitle : IHttpHandler {

    public void ProcessRequest(HttpContext httpContext) {
      
      // retrieve app web URL from cache
      string appWebUrl = httpContext.Cache["SPAppWebUrl"].ToString();
      
      string appWebTitle = string.Empty;
      using (ClientContext clientContext = new ClientContext(appWebUrl)) {
        Web appWeb = clientContext.Web;
        clientContext.Load(appWeb);
        clientContext.ExecuteQuery();
        appWebTitle = appWeb.Title;
      }

      // return response as simple text
      httpContext.Response.ContentType = "text/plain";
      httpContext.Response.Write(appWebTitle);
    }

    public bool IsReusable { get {return false;} }
  
  }
}

Once you have created a generic handler like this, you can call it and load its contents into a div element using JavaScript behind that start page which calls the jQuery load function.

$("#appwebtitle").load("/Pages/appWebTitle.ashx");

You can take this type of design one step further by implementing a generic handler to return its results in other formats such as HTML, XML or JSON. Here's an example of a generic handler that uses CSOM to discover the lists that exist within the app web and to return the title of each of these lists using an HTML <ol> element.

public void ProcessRequest(HttpContext httpContext) {

  string appWebUrl = HttpContext.Current.Cache["SPAppWebUrl"].ToString();

  using (ClientContext clientContext = new ClientContext(appWebUrl)) {
        
    // use CSOM to retrieve collection of lists
    Web appWeb = clientContext.Web;
    ListCollection appWebLists = appWeb.Lists;
    clientContext.Load(clientContext.Web);
    clientContext.Load(clientContext.Web.Lists);
    clientContext.ExecuteQuery();

    // set up HtmlTextWriter to write to response output stream
    httpContext.Response.ContentType = "text/html";
    StreamWriter innerWriter = new StreamWriter(httpContext.Response.OutputStream);
    HtmlTextWriter writer = new HtmlTextWriter(innerWriter);

    // create an HTML ol element with list of lists in app web
    writer.RenderBeginTag(HtmlTextWriterTag.Ol);
    foreach (var list in appWebLists) {
      writer.RenderBeginTag(HtmlTextWriterTag.Li);
      writer.Write(list.Title);
      writer.RenderEndTag(); // </li>
    }
    writer.RenderEndTag(); // <ol>

    // flush results to output stream and clean up
    writer.Flush();
    writer.Dispose();
  }

}

Let's look at one final example of server-side C# code which uses the CSOM to create a new list in the app web. The start page contains an ASP.NET UpdatePanel control which provides the user with the ability to add new lists to the app web. The UpdatePanel allows for a simple design where you can add server-side code behind a command button without forcing page postbacks. The code behind the Create New List command button looks like this.

// retrieve title and type for new list from server-side controls
string ListTitle = txtNewListTitle.Text;
int ListType = Convert.ToInt32(lstListType.SelectedValue);

// retrieve URL to app web
string appWebUrl = Page.Request["SPAppWebUrl"];

// use CSOM to create new list
using (ClientContext clientContext = new ClientContext(appWebUrl)) {
  ListCreationInformation newList = new ListCreationInformation();
  newList.Title = ListTitle;
  newList.Url = "Lists/" + ListTitle;
  newList.QuickLaunchOption = QuickLaunchOptions.On;
  newList.TemplateType = ListType;
  clientContext.Web.Lists.Add(newList);
  try {
    clientContext.ExecuteQuery();
    lblStatus.Text = "New " + lstListType.SelectedItem.Text + 
                     " created with title of " + ListTitle;
  }
  catch (Exception ex) {
    lblStatus.Text = "ERROR: " + ex.Message;
  }
}

// add client-side script to asynchronously reload lists
string updateScript = "$('#appweblists').load('/Pages/appWebLists.ashx');";
ScriptManager.RegisterClientScriptBlock(upNewList, 
                                        upNewList.GetType(), 
                                        upNewList.ClientID, 
                                        updateScript, true);

As you can see, it is relatively straight forward to create lists and other types of SharePoint site elements using server-side C# code which programs against the CSOM. At the end of this listing I have added a call to ScriptManager.RegisterClientScriptBlock in order to execute the client-side jQuery code required to retrieve the set of lists from the app web which includes the list that has just been created.

I will now conclude this section by summarizing some of the key points of programming server-side C# code using the CSOM. First, many programmers find this type of programming easier than using JavaScript because there is compile-time type checking and full access to the libraries of the .NET Framework. Second, the CSOM programming is a bit easier on the server because you call across the network synchronously using ExecuteQuery without having to worry about freezing the user interface as you do with client-side code. Third, there is often a need for loading content asynchronously, but this often means exposing additional entry points in the remote web project such as generic handler and web service methods and calling them from client-side JavaScript code. Finally, and best of all, you can use all the little tricks and techniques that the ASP.NET Framework has to offer without the frustrating limitations and constraints imposed on server-side code in farm solutions which run inside the SharePoint environment.

Writing Server-side C# code that uses the REST API

To say that writing server-side C# against the new REST API is more tricky than the CSOM is a bit of an understatement. Writing server-side C# code using the REST API can be a downright pain in your ASP. I think you will agree after seeing the code listings in this section.

The download named TheCsomRestPartyPack.zip contains a sample SharePoint app project named CloudAppRestDemo. This sample app provides the exact same functionality and user interface as the CloudAppCsomDemo app. The only difference is that one uses CSOM to talk to the SharePoint host environment where the other uses the REST API. The app which uses the REST API requires more C# code than the CSOM-based app to accomplish the same tasks. After seeing the comparison you will likely agree that C# code using the REST API is harder to write and maintain.

Let's start by examining the code in the Page_Load method of the app's start page which uses the REST API to retrieve the app web Title property and display it on a ASP.NET label control named lblAppWebTitle.

// retrieve URL to app web
string appWebUrl = Page.Request["SPAppWebUrl"];

// create URL for REST call to query for app web Title property
Uri uri = new Uri(appWebUrl + "/_api/web/?$select=Title");

// transmit HTTP GET request to SharePoint host environment
HttpWebRequest requestGet = (HttpWebRequest)WebRequest.Create(uri);
requestGet.Credentials = CredentialCache.DefaultCredentials;
requestGet.Method = "GET";
HttpWebResponse responseGet = (HttpWebResponse)requestGet.GetResponse();

// retrieve Title property from XML returned by SharePoint host environment
XDocument doc = XDocument.Load(responseGet.GetResponseStream());
XNamespace ns_dataservices = "http://schemas.microsoft.com/ado/2007/08/dataservices";
lblAppWebTitle.Text = doc.Descendants(ns_dataservices + "Title").First().Value;

The code in this listing begins by parsing together the proper URL to make the REST call which returns the app web's Title property in an ATOM-based XML result. Next, the code prepares and transmits an HTTP GET request to the SharePoint host environment using the new HttpWebRequest class that was introduced in .NET 4.0. When the call to the GetResponse method returns, you have to extract the Title property value from the returned XML document. If you are not familiar with LINQ to XML and the XDocument class, you should get up to speed on them because they make this type of programming much easier than using the older XML-based APIs of the .NET Framework.

As you can see in the listing above, the Descendants method of the XDocument class makes it much easier to extract the namespace-qualified Title property out of the following XML result.

<entry xmlns="http://www.w3.org/2005/Atom" 
       xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" 
       xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" >

  <id>http://big-long-url-to-app-web/_api/Web</id>
  <category term="SP.Web" />
  <content type="application/xml">
    <m:properties>
      <d:Title>Wingtip Test Site</d:Title>
    </m:properties>
  </content>

</entry>

Now let's look at the generic handler which has been written to use the REST API discover the set of lists in the app web and to generate an HTML list element which can be used for display on the start page. Here is the code inside the ProcessRequest method of the generic handler that accomplishes this work.

public void ProcessRequest(HttpContext context) {

  // prepare response as HTML and set up HtmlTextWriter
  context.Response.ContentType = "text/html";
  StreamWriter innerWriter = new StreamWriter(context.Response.OutputStream);
  HtmlTextWriter writer = new HtmlTextWriter(innerWriter);

  // get URL for app web
  string appWebUrl = context.Cache["SPAppWebUrl"].ToString();

  // create URL for REST API to retrieve lists from app web
  Uri uri = new Uri(appWebUrl + "/_api/web/lists/?$select=Title");

  // transmit HTTP GET request to SharePoint host environment
  HttpWebRequest requestGet = (HttpWebRequest)WebRequest.Create(uri);
  requestGet.Credentials = CredentialCache.DefaultCredentials;
  requestGet.Method = "GET";
  HttpWebResponse responseGet = (HttpWebResponse)requestGet.GetResponse();
  
  // load XML result in XDocument object    
  XDocument doc = XDocument.Load(responseGet.GetResponseStream());
  XNamespace ns_dataservices = 
             "http://schemas.microsoft.com/ado/2007/08/dataservices";

  // create an HTML ol element with list of lists in app web
  writer.RenderBeginTag(HtmlTextWriterTag.Ol);
  foreach (var list in doc.Descendants(ns_dataservices + "Title")) {
    writer.RenderBeginTag(HtmlTextWriterTag.Li);
    writer.Write(list.Value);
    writer.RenderEndTag(); // </li>
  }
  writer.RenderEndTag(); // </ol>

  // flush generated HTML to response stream and clean up
  writer.Flush();
  writer.Dispose();

}

Once again, the REST API requires that you parse together the URL for a GET request that queries the app web for the current set of lists. The code in this listing prepares an HTTP GET request that is sent and received using HttpWebRequest and HttpWebResponse objects. At the end there is code written using the XDocument class which enumerates through the returned XML document to create an HTML list element which contains a list item with the Title property of each list which is written into the generic handler's output stream.

When it comes time to modify content in a SharePoint site such as creating a list is when programming C# against the REST API gets pretty grungy. For example, you need to acquire the form digest value that was discussed earlier this post. However, the form digest value is not readily available as it was in the previous example which involved writing JavaScript behind a page served up from a SharePoint site. Instead, you must make an HTTP POST request with an URL that queries the REST API for context information using a URL that ends with _api/contextinfo. Here is an example of a utility function I wrote named GetFormDigest which calls to the SharePoint host environment to acquire a Form Digest value that can then be used in subsequent requests that modify content.

private string GetFormDigest(){
  string appWebUrl = Cache["SPAppWebUrl"].ToString();
  Uri uri = new Uri(appWebUrl + "/_api/contextinfo");
  HttpWebRequest requestPost = (HttpWebRequest)WebRequest.Create(uri);
  requestPost.Credentials = CredentialCache.DefaultCredentials;
  requestPost.Method = "POST";
  requestPost.ContentLength = 0;
  HttpWebResponse responsePost = (HttpWebResponse)requestPost.GetResponse();
  XDocument doc = XDocument.Load(responsePost.GetResponseStream());
  XNamespace ns_dataservices = 
             "http://schemas.microsoft.com/ado/2007/08/dataservices";
  return doc.Descendants(ns_dataservices + "FormDigestValue").First().Value;
}

In addition to acquiring a form digest value, creating a new list with the REST API requires you to parse together the payload for the request body using either an ATOM-based XML format or JSON. In our scenario the XML payload must contain information about the new list that is being created. Since we are working with C# instead of JavaScript, it is easier to use the ATOM-based XML format instead of JSON. The code behind Default.aspx contains a protected string constant named AtomXmlForNewList which provide a template for creating the XML required to create a new list.

protected string AtomXmlForNewList = @"
<entry xmlns='http://www.w3.org/2005/Atom' 
	xmlns:d='http://schemas.microsoft.com/ado/2007/08/dataservices' 
	xmlns:m='http://schemas.microsoft.com/ado/2007/08/dataservices/metadata' >

  <category term='SP.List' 
            scheme='http://schemas.microsoft.com/ado/2007/08/dataservices/scheme' />
    
  <content type='application/xml'>
    <m:properties>
      <d:Title>@Title</d:Title>
      <d:BaseTemplate m:type='Edm.Int32'>@ListTypeId</d:BaseTemplate>
    </m:properties>
  </content>

</entry>";

Using a string-based template like this, your code just needs to do a search-and-replace operation on the two placeholders named @Title and @ListTypeId. Then you write the resulting XML document into the body of a POST request that you transmit to the SharePoint host environment. Here's the code in the CloudAppRestDemo app that pulls everything together to create new list in the app web using the REST API.

// create URL with resource path referencing app web's list collection
string appWebUrl = Cache["SPAppWebUrl"].ToString();
Uri uri = new Uri(appWebUrl + "/_api/web/lists/");

// create HttpWebRequest for POST operation with Windows authentication credentials
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.Credentials = CredentialCache.DefaultCredentials;

// add header with form digest value
request.Headers["X-RequestDigest"] = GetFormDigest();

// set format of response body
request.Accept = "application/atom+xml";

// create ATOM-based XML document for creating new list
request.ContentType = "application/atom+xml";
string body = AtomXmlForNewList;
body = body.Replace("@Title", txtNewListTitle.Text);
body = body.Replace("@ListTypeId", lstListType.SelectedValue);

// write create ATOM-based XML document to request body
request.ContentLength = body.Length;
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(body);
writer.Flush();

try { 
  // send synchronous HTTP POST request to SharePoint host environment
  HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  lblStatus.Text = "New " + lstListType.SelectedItem.Text + 
                   " created with title of " + ListTitle;  
}
catch (Exception ex) {
  lblStatus.Text = "ERROR: " + ex.Message;
}

So now you have seen a direct comparison between server-side C# code using both CSOM and the REST API. Most developers will agree that using the CSOM is significantly easier. That's because CSOM manages the form digest for you behind the scenes and it doesn't require you to parse together URLs and XML documents. I will prefer using CSOM over the REST API for server-side C# code until someone is able to show me that the REST API has performance advantages or offers functionality not available through the CSOM. But then again, Microsoft's big investment in the REST API was not made for this scenario. Microsoft was incented to create the new REST API for the benefit of client-side JavaScript code and for server-side code not running on the .NET Framework which has no access to CSOM.

Summary

You have just read through a long post which I wrote to get you started with developing SharePoint apps which communicate with the SharePoint host environment using CSOM and the new REST API. As you have seen, there are four basic styles. I typically prefer using the REST API over CSOM when writing client-side JavaScript code because it allows me to work with JSON which integrates well with other JavaScript libraries such as jQuery, jsrender and knockout. However, there are some scenarios where you will find that using CSOM is just as easy or easier. I find it's when I am writing server-side code with C# that there is such a drastic difference in productivity. I will always prefer the CSOM over the REST API in this scenario.

For the purposes of creating a smoother learning path, I avoided any discussion of app authentication and app identity in this post. However, these are essential topics that must be understood by anyone developing cloud-hosted SharePoint apps. Therefore, they will be the focus of the next post in this series that will pick up where this post leaves off.

August 09
Configuring a Cloud-hosted SharePoint App to Use Internal Authentication

My life is different than that of many SharePoint developers because the focus of my career is on education. I find myself constantly writing new SharePoint projects whose main purpose is to demonstrate to other SharePoint developers how to get started with a new API or a new programming technique. Over the last year I have written my fair share of sample SharePoint projects in Visual Studio 2012 to demonstrate the programming skills required for SharePoint app development with SharePoint 2013.

The Holy Grail in writing demos for Visual Studio is to configure a project which someone can just open and press the {F5} key to see it run. When a Visual Studio project targets a SharePoint environment, there is sometimes an extra step between opening the project and pressing the {F5} key where you modify the project's test site to point to a valid SharePoint site running in the local farm.

Lately I have been writing sample projects for cloud-hosted SharePoint apps for our new SharePoint 2013 developers class (insert subliminal marketing plug here). The goal in writing these cloud-hosted apps is to demonstrate how to write server-side C# code which uses the client-side object model (CSOM) and the new REST APIs in SharePoint 2013. However, it's tricky to get the SharePoint environment set up correctly in a local farm to support external authentication because you have to configure a server-to-server (S2S) trust. You can see what is required in AC's recent post and after reading that you will likely agree that the S2S configuration isn't the open-project-and-press-{F5} experience that will appeal to the masses.

It's far easier to get external authentication working in the SharePoint 2013 environment provided by a developers site in the Office 365 beta program. I have to hand it to Microsoft how smoothly they have made things work. However, someone has to pre-register for a beta account with their personal email account to obtain access to a developers site in Office 365. This requirement certainly compromises my ability to have a classroom full of students simultaneously open one of my sample projects and {F5} their way to spontaneous gratification.

My goals as an educator have been further complicated by the fact that cloud-hosted SharePoint apps that rely on external authentication must be written differently depending on whether they run in the Office 365 environment or within an on-premises farm. I decided it would be a good thing if I could write sample projects that abstracted away the differences between these two different types of SharePoint 2013 environments.

That leads me to the key point of this bog entry. I have discovered a little trick to get sample cloud-hosted SharePoint app up and running using internal authentication instead of external authentication. This has a nice benefit from a teaching perspective because a SharePoint app does not require any explicit code for managing authentication. It all happens transparently behind the scenes. It also allow me to achieve the open-the-project-and-press-{F5} effect to give my sample projects that happy Hollywood ending.

In order to use this trick, you have to make a few assumptions. First, you must be developing and testing your SharePoint apps within a local SharePoint farm as opposed to Office 365. This means you must build out a VM or a developer workstation with a local SharePoint farm and configured it to run SharePoint apps. Second, your local test site must be running within a claim-based Web Application that is configured to authenticate the user using integrated Windows authentication. Finally, all the work you do with CSOM and REST must be done against the app web associated with the SharePoint app you are developing. While these assumptions do not match the majority of real-world scenarios, they work well in the classroom when I want to discuss CSOM and the REST APIs without getting bogged down in the painful details of external authentication. It is much easier to teach people about app authentication after I have already taught them the basics of CSOM and the new REST API.

Creating the new Project for a Cloud-hosted SharePoint App

You should begin by creating a new Visual Studio 2012 project using the App for SharePoint 2013 project template. I am going to create my project as a C# project although you could alternatively create the project using VB.NET.

This new SharePoint app should be configured to use a local SharePoint site as its testing/debugging site and a hosting model of Provider-hosted.

When you click the Finish button, Visual Studio creates a new solution with two projects. The first project above is for the portion of the SharePoint app that gets installed into a SharePoint host environment inside the context of a specific site. The second project below is an ASP.NET project that is used to implement the remote web for this SharePoint app. Note that Visual Studio creates the name for the remote web project by appending "Web" to the end of the name of the first project.

The next step is to open the AppManifest.xml file in the top project in code view. Accomplish this by right-clicking it and selecting View Code which will display the raw XML of the app manifest and allow you to edit it. You will see inside the AppPrincipal element that there is a RemoteWebApplication element which means that this new SharePoint app is initially configured to use external authentication. Modify the AppPrincipal element by replacing the a RemoteWebApplication element with an element named Internal. Once you have updated the AppManifest.xml file to look like the XML snippet below, save your changes and close the file.

<App xmlns="http://schemas.microsoft.com/sharepoint/2012/app/manifest"
  Name="CloudAppDemo"  
  ProductID="{6f825c04-ff6d-4779-b6fe-0fe8d732997c}"
  Version="1.0.0.0"
  SharePointMinVersion="15.0.0.0" >

  <Properties>
    <Title>Cloud App Demo</Title>
    <StartPage>~remoteAppUrl/Pages/Default.aspx?{StandardTokens}</StartPage>
  </Properties>

  <AppPrincipal>
    <Internal/>
  </AppPrincipal>

</App>

The next issue you must deal with involves properly creating the app web when the SharePoint app is installed. The initial problem to overcome is that Visual Studio has created this new SharePoint app project in such a way that it will not create an app web during installation. For many cloud-hosted SharePoint apps, this out-of-the-box configuration makes sense because they will use their own external databases to store their content and they will have no need for an app web in their designs. However, in our case we want our new cloud-hosted SharePoint app to create its own app web when it is installed. Fortunately, this is simple to fix.

Here is how to deal with the scenarios where you want a cloud-hosted app to create its own app web during installation. You can simply right-click on the top project and select Add > New Item. Once you add a new project item from one of the Office/SharePoint item templates such as List, Site Column or even Empty Element, Visual Studio automatically adds support to your project to create a new app web. Here is a before screenshot and an after screenshot that shows what Visual Studio does to your project when you add a new project item based on the Empty Element template.

There is one final modification you need to make on the remote web project. In particular, you must enable the remote web to support Windows Authentication project. Visual Studio 2012 disables Windows Authentication by default in a new cloud-hosted SharePoint app project because it isn't used in the Office 365 environment. However, you can enable Windows Authentication in the remote web project by modifying a project property using the standard Visual Studio property sheet.

Now you are at a point where you can start writing server-side code in the remote web project behind the start page named Default.aspx. Start by removing the code that Visual Studio has added to the Page_Load method. Now you can write code that uses CSOM and the new REST API against the app web and your code does not require any explicit coding for authentication. Here's an example of how to write the 'hello world' code to retrieve the Title property of the app web using both CSOM and the new REST API.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

// extra imports
using Microsoft.SharePoint.Client;
using System.Net;
using System.Xml.Linq;

namespace CloudAppDemoWeb.Pages {
  public partial class Default : System.Web.UI.Page {

    protected void Page_Load(object sender, EventArgs e) {

      // get URL to app web
      string appWebUrl = this.Request.QueryString["SPAppWebUrl"];

      // *** hello world using CSOM ***
      using (ClientContext ctx = new ClientContext(appWebUrl)) {
        Web appWeb = ctx.Web;
        ctx.Load(appWeb);
        ctx.ExecuteQuery();
        string appWebTitleCSOM = appWeb.Title;
        // display Title property on page
        Response.Write("<h2>App Web Title retrieved using CSOM</h2>");
        Response.Write("<div>" + appWebTitleCSOM + "</div>");
      }

      // *** hello world using REST API ***
      Uri uri = new Uri(appWebUrl + "/_api/web/?$select=Title");
      HttpWebRequest requestGet = (HttpWebRequest)WebRequest.Create(uri);
      requestGet.Credentials = CredentialCache.DefaultCredentials;
      requestGet.Method = "GET";
      HttpWebResponse responseGet = (HttpWebResponse)requestGet.GetResponse();
      XDocument doc = XDocument.Load(responseGet.GetResponseStream());
      XNamespace ns_dataservices = "http://schemas.microsoft.com/ado/2007/08/dataservices";
      string appWebTitleREST = doc.Descendants(ns_dataservices + "Title").First().Value;
      // display Title property on page
      Response.Write("<h2>App Web Title retrieved using REST API</h2>");
      Response.Write("<div>" + appWebTitleREST + "</div>");
    }
  }
}

Now for the fun part. Press the {F5} key, carry on and keep calm (if you can).

August 02
Visual Studio 2012 RC does not recognize 127.0.0.1 as a local address

I found a small bug with Visual Studio 2012 and the new SharePoint Tools. It's not a big deal because it has an easy workaround once you know what to do. The issue surfaces during development with SharePoint 2013 when you have a domain name such as http://intranet.wingtip.com that you have used as the URL for a local Web Application or a local Host Header site collection. A problem occurs when you configure the DNS settings for this domain name to point to back to the local machine using the IP address of 127.0.0.1. When you attempt to create a new farm solution or sandboxed solution and assign this local URL as the test site, Visual Studio complains with the following error.

The workaround is simple. Change the DNS settings from 127.0.0.1 to one an actual IP addresses that is being used by the local machine. For example, imagine I set up the DNS settings for my developer workstation using the HOST file with an IP address of 127.0.0.1.

127.0.0.1 intranet.wingtip.com 
127.0.0.1 extranet.wingtip.com 
127.0.0.1 www.wingtip.com 

The workaround is to simply use one of the actual IP addresses used by the local machine instead of 127.0.0.1

192.168.150.2 intranet.wingtip.com 
192.168.150.2 extranet.wingtip.com 
192.168.150.2 www.wingtip.com 

Once you do this, Visual Studio will then recognize the domain you are using as a local domain and you will avoid the error shown above. Note that this is a known issue to the Visual Studio team and it will be fixed in a future release of the SharePoint Tools.

July 30
My first weekend in Napa

I am a dinosaur. That goes without saying. I’ve been involved in SharePoint development since March of 2003. That’s when I got my first beta copy of Windows SharePoint Services 2.0 and began the self-imposed, sadomasochistic torture that has now lasted over a decade. Now it is 10 years and 4 major releases of SharePoint later and I have literally installed SharePoint thousands of times so I could configure a local farm to create a SharePoint development environment.

So here’s the main question that freaks out so many .NET developers who are considering whether to get involved with SharePoint. Why do SharePoint developers spend so much of their time learning to be SharePoint administrators? To an old-school dinosaur like me, the answer to this question seems so obvious. Learning to build and configure a local farm has been the cost of doing business for a SharePoint developer. You need a local farm to develop anything for SharePoint, right? Or at least that's what a dinosaur will tell you.

I got this friend, Mike Morton, who works at Microsoft as a Senior Program Manager on Visual Studio. He is a senior member of the team that built the SharePoint Tools in Visual Studio 2010. I give his team credit for providing the Visual Studio integration that changed the way we all develop for SharePoint. But Mike is not the kind of guy to rest on his laurels.

For the last two years Mike’s team has been revising the SharePoint Tools and getting them ready for SharePoint 2013. They just released a new version of the SharePoint Tools that runs with the Visual Studio 2012 Release Candidate. I heard that's what I need to develop for the new public beta of SharePoint 2013. So what's an excited dinosaur to do other than build out a local SharePoint 2013 farm and fire up those new SharePoint Tools.

Mike Morton is not a sales guy. In fact, he's quite the opposite. If he had to sell vacuum cleaners for a living, this guy would starve. Yet lately Mike's been trying to sell me on something new. Something he said was the coolest new feature of the SharePoint Tools. Something he said we've all been asking for. Something he said that will flood the SharePoint space with a new breed of developer. The thing he's been talking about is the SharePoint Tool's new ability to participate in remote development and a second lightweight toolset named "Napa" for those just getting started.

This past weekend was life changing. I had a little extra free time and I thought I would humor Mike by giving this new “remote development” story and the new Napa toolset a try. Like any good dinosaur, I started this exercise with a healthy sense of skepticism. I mean, seriously, can you really develop for SharePoint without a local farm? What a pipe dream. But as things progressed, my skepticism eroded away. It was awful. Things worked even easier and smoother than I could have ever imagined. By Sunday night I was filled with a sense of trepidation and fear. SharePoint dinosaurs like myself are on the verge of extinction. So let me explain why.

Friday Night

I started out on Friday night. I did have much time because I was meeting some people for dinner. But I knew I had to sign up with Microsoft for an Office 365 Developer Site. In about 20 minutes I went to this Microsoft website, gave them some basic information and submitted my request for an Office 365 developers site. After that, I headed out to dinner where I had just a few tiny little glasses of red wine. I got home a little after midnight and looked at the welcome email from the Microsoft Online Services team. This email provided the information I needed to log on to Office 365 and my new SharePoint developers site. I wanted to dive in but the red wine was telling me to get a little sleep first.

Saturday Morning

Boy, do I love weekends. I'm always getting up early and looking for something to do. I was excited about this weekend because I had big plans to install the most recent beta of Windows 8 on my Dell Precision 2400. I downloaded the public beta of Windows 8 and did a clean install of Windows 8 with all the default options. And then with nothing other than the operating system installed, I set out to develop my first SharePoint app of the day.

I started by firing up Internet Explorer 10 and then I logged into my new developer site in Office 365. Next, I needed to find the SharePoint app that goes by the name of "Napa". Napa is an app create by Mike's team that you can use to build SharePoint apps and apps for Office. The interesting thing about Napa is that you use it to build apps just using the browser.

On the home page of my developer site, I clicked the Site Contents link and then click add an app.  On the next page, I clicked SharePoint Store to see a list of apps that were available to me for installation. Here is where I found the "Napa" Office 365 Development Tools app which I then installed into my developer site.

Next, I fired up the Napa app so I could create my first SharePoint app. When you create a new app, Napa gives you a choice between a SharePoint app and three other types of apps for Office. I created a new SharePoint app named SilverOak to honor one of my favorite vintages in Napa Valley.

After creating this new app, I then saw a new project for it in the browser. On the left-hand side was an explorer-like view which is used to view and open the app's source files. I began by editing the app's start page named default.aspx. I was impressed that the browser-based editor provided color coding and a simple HTML editing experience. I was also happy to see that Napa had automatically included the source files and links I need to use the jQuery core library. Very nice.

Next, I opened the App.js file with the JavaScript that contained the app's logic. The JavaScript editor is also color coded and it even underlines JavaScript code when it finds an error. It's definitely not the same experience as writing JavaScript in Visual Studio, but it's still pretty impressive for a browser-based JavaScript editor. I made a few changes to the starting code Napa gave me just so I could test out the traditional 'Hello World' style app.

When it's time to test an app in Napa, you just need to click the Run Project button in the lower left-hand corner of the browser.

When you click the Run Project button, Napa packages up your app and then installs it in your developer test site. While the SilverOak app will not win any awards, it only took me a few minutes to get it up and running.

So that was Saturday morning. I developed a SharePoint app and there was no local farm nor installation of Visual Studio anywhere in sight. I was developing for SharePoint 2013 armed with with nothing more than Internet Explorer.

Saturday Night

I was impressed by what happened earlier that day when I found that you can create, write and test a SharePoint app without any tools installed on your developer workstation. While impressive, this approach lacked the excitement I was looking for on a Saturday night. So I decided it was time to install the Visual Studio 2012 Release Candidate and the new SharePoint Tools on my bare bones Windows 8 build to see what gives.

First, I found and installed the Visual Studio 2012 Release Candidate. That took about 30-40 minutes to complete to download and installation. Next, I installed the new version of the SharePoint Tools which Mike Morton and his team released to work with the Visual Studio Release Candidate. Once I had the tools installed, I was all ready to revisit the SilverOak project in Visual Studio and kick its tires.

I logged back into to my Office 365 developers site and opened the SilverOak project I had created earlier that morning. Once I had this project opened in Napa, I clicked the Open in Visual Studio button to convert the project into a form that can be opened within Visual Studio.

Napa did the project conversion, downloaded the project files locally and automatically opened it in Visual Studio 2012. There I was looking at the same source files but in a far more familiar environment. At this point I assumed there would be some tricky stuff I had to figure out to correctly configure the project to a point where I could actually upload and test the app up in Office 365. However, I pressed the {F5} key just for grins to see what would happen. Holy stegosaurus, Batman. It just worked right out of the box.

Now, I had all the benefits of the Visual Studio environment such as improved JavaScript IntelliSense and awesome new support for the NuGet feature that makes it quick and easy to add the additional JavaScript libraries like JQuery UI, Knockoutjs and Modernizr. I just had to write the code and then press {F5} to test and debug my work. My only regret was that I stayed sober all night because I figured things would get tricky and I wanted to stay sharp. In retrospect, I should have had a glass of red wine by my side.

Sunday Morning

I woke up early again and sat back down at my Windows 8 machine. I was happy with what I had done the day before but I still wanted to see what else there was to this remote development story. It then also occurred to me that the SilverOak project was just a SharePoint-hosted app. It was all client-side JavaScript. It didn't have any server-side C# code. And after all, how can a SharePoint developer prove his manliness (or her womanliness) to anyone without writing some server-side C# code.

It was time for File > New > Project so I could see what the experience is like when creating a new cloud-based SharePoint app. I created a new Visual Studio project named Cakebread using the App for SharePoint 2013 project template provided by the SharePoint Tools.

When you create a new project, the SharePoint Tools make you enter the URL for a test site and select a hosting model. I pointed to my developer site and selected the hosting model named Autohosted.

Once again, the SharePoint Tools add enough starter code to a new SharePoint app project to provide the 'Hello World' experience out of the box. Once the app project was created, I just pressed the {F5} and watched it install into my developer site in Office 365. Along the way the developer site prompts you to ensure that you trust the app being installed.

At this point, I saw the light. All the SharePoint goo and the bad dreams of a decade's worth of SharePoint installs was up in the cloud and not my concern. On my developer machine, there was nothing but cutting-edge purity, the latest and greatest for any .NET developer.  I was testing and debugging C# code running inside IIS Express and the Visual Studio debugger and single-stepping through my C# code. My C# code running in the local Visual Studio debugger was freely calling back into the Office 365 developer site up in the cloud using the client-side object model (CSOM) and the new REST API. Yes, this was true, hardcode SharePoint development for the manliest of manly men and there was no local SharePoint farm in sight.

After getting my first Autohosted SharePoint app up and running, I celebrated with a post-code-app cigarette. Then I found I was addicted. I spent the rest of the day creating more SharePoint apps and getting to know how to get around in my developer sites in Office 365.

What a great weekend. All I can say is great job, Mike. Thanks to your team for getting a vision and implementing it.

Once You Go App, You Never Go Back

Now that Microsoft has released the first public beta of SharePoint 2013, the Microsoft marketing drum is pounding out the mantra of "apps, apps, apps and more apps". However, a true dinosaur like me knows very well that the new SharePoint app model will not cure cancer, make me look younger or replace farm solution development in the near future. The SharePoint app model is just a new option with a bunch of nice benefits.

So, do I think SharePoint developers are now free from ever again having to build out or obtain a VM with a local SharePoint farm? The answer really has to do with where you plan to target your SharePoint development. If you plan to develop SharePoint solutions that will target on-premises SharePoint farms, then you need to develop on a local SharePoint farm. Likewise if you plan to develop SharePoint apps that will target on-premises SharePoint farms, then you need a local SharePoint farm at some point in the development lifecycle. However, you can start your app development project in an Office 365 developer site and then move over to a local SharePoint farm in the final stages of coding and testing before you deploy it. This enticing new world where a SharePoint developer never needs a local SharePoint farm is mainly for the folks who only care about building SharePoint apps for the Office 365 environment.

But then I think about this new breed of SharePoint developer that Mike Morton described to me. A developer that's never never used SharePoint before and has never seen a SharePoint dinosaur like me (except maybe in a museum). This developers has a very high IQ and has tons of experience with things like .NET, C#, JavaScript and jQuery. This is the type of new developer talent that Microsoft is trying to attract to build a critical mass of useful business apps in the Office Store and the SharePoint store. A couple years from now we will look back and see how things worked out. However, one thing is clear. Having a plethora of useful apps available for companies using Office 365 will be a key factor in the overall success of Office 365. And Microsoft made the decisions that it didn't want to bet the farm by relying on old-school dinosaurs like me.

July 23
SharePoint apps are isolated with respect to request processing and storage

This is the second post in a series of blog posts on the SharePoint app model. Here is the outline of this series.

If you haven’t read the first post in the series on why SharePoint app code cannot run inside the SharePoint environment, you should consider reading it first before continuing with this post. The first post explains the basic architecture and the differences between SharePoint-hosted apps and cloud-hosted apps. This post assumes you already understanding these differences.

SharePoint apps can create pages and lists in isolated storage

Each time you install a SharePoint app, you must install it into a specific target site. If the target site is a standard site, the SharePoint app is installed at site scope. If you install a SharePoint app in a special type of site known as a catalog site, then the app is installed a tenancy scope. Installing an app at tenancy scope is valuable because a single instance of an app can be configured for use across all site collections and sites inside a tenancy.

A SharePoint app has the capability to add its own files to the SharePoint host during installation. For example, a SharePoint-hosted app will typically add a start page, a CSS file and a JavaScript file to implement the app's user experience. The SharePoint host stores these files in the standard fashion by adding them to the content database associated with the target install site. Beyond basic pages, a SharePoint app also has the ability to create other SharePoint-specific site elements in the SharePoint host during installation such as lists and document libraries.

Let’s look at an example. Imagine you want to create a simple SharePoint app to manage customers. During installation, the app can be designed to create a customer list using the standard Contacts list type along with a set of pages designed to provide a snazzy user experience for adding and finding customers. Your app could additionally be designed to create a document library upon installation so that the app can store customer contracts as Word documents where each Word document would reference a specific customer item in the customers list.

So where does the SharePoint host store the content added by an app during installation? The answer is inside a special child site that the SharePoint host creates under the host site where the app is being installed. This child site is known as the app web. A simple example of a host site and the app web created during a site-scoped installation is shown in the following diagram.

The app web is an essential part of the SharePoint app model because it represents the isolated storage that is owned by an installed instance of a SharePoint app. The app web provides a scope for app’s private implementation details. Note that an app by default has full permissions to read and write content inside its own app web. However, an app has no other default permissions to access content from any other location in the SharePoint host. The app web is the only place an app can access content without requesting permissions that then must be granted by a user.

There is an important aspect of the SharePoint app model that deals with uninstalling an app and ensuring that all the app-specific storage is deleted automatically. In particular, a SharePoint host will automatically delete the app web for an app whenever the app is uninstalled. This provides a set of cleanup semantics for SharePoint apps that is entirely missing from the development model for SharePoint solutions. When an app is uninstalled, it doesn’t leave a bunch of junk behind. I wish I could same the same thing for all the SharePoint solutions I have created over the years.

You should understand that the installation of a SharePoint app doesn’t always result in the creation of an app web. Some apps are designed to create an app web during installation and some are not. A SharePoint-hosted app is the type of app that will always create an app web during installation. This is a requirement because a SharePoint-hosted app requires a start page that must be added to the app web.

However, things are different with a cloud-hosted app. Since a cloud-hosted app has a start page that is served up from an external website, it does not require the creation of an app web during installation. Therefore, the use of an app web in the design of a cloud-hosted app is really just an available option as opposed to a requirement as it is with a SharePoint-hosted app.

When you design a cloud-hosted app, you have a choice whether you want to create an app web during installation to store private app implementation details inside the SharePoint host. Some cloud-hosted apps will store all the content they need within their own external database and will not need to create an app web during installation. Other cloud-hosted apps can be designed to create an app web during installation in scenarios where it makes sense to store content within the SharePoint host for each installed instance of the app.

The app package and the inner solution package

A SharePoint app is packaged up for deployment using a distributable file known as an app package. An app package is a ZIP file with a .app extension. If you create a new SharePoint app project named MyFirstApp, the project will generate a app package named MyFirstApp.app as its output. Note that the file format for creating an app package is based on the Open Package Convention (OPC) format. This is the same file format that Microsoft Office begin to use with the release of Office 2007 for creating Word documents (docx) and Excel workbooks (xslx).

The primary requirement for an app package is that it contains a top-level file named AppManifest.xml which contains essential metadata for app. The SharePoint host relies on properties it discovers inside AppManifest.xml so that it can properly install, track and launch a SharePoint app. Here's an example of the AppManifest.xml file used by a SharePoint-hosted app which contains standard app properties such as Name, ProductID, Version, Title and StartPage.

In addition to the AppManifest.xml file, the app package often contains additional files that are used as part of the app's implementation. For example, the app package for a SharePoint-hosted app contains a file for the app's start page along with other resources used by the start page such as a CSS file and a JavaScript file. These are example of files that are added to the app web as part of the app installation process.

The distribution mechanism used by a SharePoint app to add pages and lists to the app web during installation is a standard solution package. Does this sound familiar? Yes, it a CAB file with a .wsp extension. It sounds familiar because the solution package file used by a SharePoint app has the exact same file format as the solution package files which we have been using to deploy SharePoint solutions in SharePoint 2007 and SharePoint 2010. The one key difference is that the solution package used by a SharePoint app is embedded as a .wsp file inside the app package as shown in the following diagram.

When a user installs a SharePoint app, the SharePoint host examines the app package to see if it contains an inner solution package. It is the presence of an inner solution package inside the app package file that tells the SharePoint host whether it needs to create an app web during installation. If the app package does not contains an inner solution package, the SharePoint host installs the app without creating an app web.

The inner solution package for a SharePoint app should contain a single Web-scoped feature. The SharePoint host activates this feature automatically on the app web immediately after the app web is created. This features is what makes it possible to add declarative elements such as pages and lists as the app is installed. However, the inner solution package for a SharePoint app cannot contain any type of DLL or any .NET code whatsoever. Therefore, you can say that the inner solution package is constrained because it must be a fully declarative solution package. This is different than the solution packages for farm solutions and sandboxed solutions which can contain DLL assemblies with custom .NET code written in either C# or VB.NET.

Processing page requests from the app web

Next, let’s turn our attention to the start page for a SharePoint-hosted app. As you have seen, the start page for a SharePoint-hosted app is added to the app web during installation. Now imagine a scenario where you have installed a SharePoint app with the name of MyFirstApp in a team site which is accessible through the following URL.

https://intranet.wingtip.com.

During app installation, the SharePoint host creates the app web as a child site under the target host site. The SharePoint host creates a relative URL for the app web based on the app’s Name property. Therefore, in our example the app web is created with a relative path of MyFirstApp. If the app’s start page named default.aspx is located in the app web inside the Pages folder, then the relative path to the start page is MyFirstApp/Pages/default.aspx. Now your intuition might be telling you that the app’s start page will be accessible through an URL that combines the base URL to the host site together with the relative path to the start page.

https://intranet.wingtip.com/MyFirstApp/Pages/default.aspx

However, this is not the case. The SharePoint host does not make the app web nor any of its pages accessible through the same domain as the host site. Instead, the SharePoint host creates a new unique domain on the fly each time time it creates a new app web as part of the app installation process. This allows the SharePoint host to isolate all the pages from an app web in its own private domain. The start page for a SharePoint-hosted app will then be made accessible through an URL that looks like this.

https://wingtiptenant-ee060af276f95a.apps.wingtip.com/MyFirstApp/Pages/Default.aspx

If you look back at the AppManifest.xml file shown earlier, you notice that it did not include a hard-coded path to the app’s start page. Instead, the URL to the start page contains a dynamic token named ~appWebUrl. This dynamic token is replaced by the SharePoint host when the app is installed. This makes sense because the URL that will be used to access the app web is not even known until the SharePoint host creates a new domain for the app during installation. After creating the app web, the SharePoint host can then use it to create the URL to the start page.

So why doesn’t the SharePoint host serve up pages from the app web using the same domain as the host site? At first, the reasons why the SharePoint host serves up the pages from an app web in their own isolated domain might not be obvious. There are two primary reasons why the SharePoint app model does this. Both of these reasons are related to security and the management and enforcement of permissions granted to an app.

The first reason for isolating an app web in its own private domain has to do with preventing direct JavaScript calls from pages in the app web back to the host site. This security protection of the SharePoint app model builds on the browser’s built-in support for prohibiting cross-site scripting (XSS). Since JavaScript code running on pages from an app web pages originates from a different domain, this code cannot directly call back to the host site. More specifically, calls from JavaScript running on app web pages do not run with the same identity nor the same permissions as JavaScript code behind pages in the host site.

The second reason for creating an isolated domain for each app web has to do with page processing and JavaScript callbacks that occur on the server. The SharePoint host creates a new unique domain for each app that it installs. This in turn allows the SharePoint host to determine exactly which app is calling when it sees an incoming request from a page in an app web. They key point is that the SharePoint host is able to authenticate the SharePoint app and examine its permissions any time a call originates from the domain of an app web. As you remember from earlier, an app has default permissions to access its app web but it has no default permissions anywhere else in the SharePoint host. The ability for the SharePoint host to authenticate calls from apps using the isolated app web domain is essential to enforcing this default permissions scheme.

This is huge. The idea that SharePoint 2013 introduces new authentication support for apps in addition to its existing authentication support for users is a significant part of the SharePoint app model. In effect. this is what allows SharePoint apps to become a first class security principals. This alone gives the new SharePoint app model many advantages over SharePoint solutions development. In this post I am going to keep the discussion authentication with SharePoint apps brief. I am going to create another blog post later in this series that will go into much greater detail about how, when and why SharePoint apps are authenticated.

Configuring your local on-prem farm for deploying and developing apps

If you have acquired a new beta test site in Office 365, you have an environment that has already been configured to deploy and run SharePoint apps. Everything is all set to go. However, what if you want to build out a local farm with SharePoint 2013 on your development machine so you can deploy and develop SharePoint apps locally? If you want to do this (and I recommend you do), then you must perform a few extra tasks after installation to properly configure the environment for developing SharePoint apps. This can all be done using Windows PowerShell and I will conclude this post by walking you though the steps required.

Remember that the new SharePoint app model was really designed for Office 365. Therefore, the environment for running SharePoint apps must be configured at tenancy level. The idea of tenancy-level configuration makes a great deal of sense in Office 365. However, the concept of creating and configuring tenancies in an on-prem farm can be far more confusing.

First things first. To run SharePoint apps locally you need to create an instance of a new SharePoint 2013 service application named the App Management Service Application. This step is an easy one because you can create the required instance of the App Management Service Application using the Farm Wizard right after you have created a new SharePoint 2013 farm.

Next, you need to use PowerShell to configure the root domain name for app webs. This can be done by calling a new PowerShell cmdlet named Set-SPAppDomain and passing a base URL that the SharePoint host will use to create a new domain each time it create a new app web during app installation. For example, you can configure the root domain for app webs to be something such as apps.wingtip.com.

# assign base domain name to configure URL used to access app webs
Set-SPAppDomain "apps.wingtip.com" –confirm:$false

Next, you have to ensure that you have an instance of the Microsoft SharePoint Foundation Subscription Settings Service Application. However, this is a bit more tricky because you cannot create a new instance of this service application using the farm wizard. Nor can you create a new instance of this service application by hand in Central Administration. Instead, you have to use PowerShell. At the end of this post, I have included a complete script that does all the work for you.

Now let's discuss the importance of creating an instance of the Subscription Settings Service Application in an on-prem farm. The Subscription Settings Service is what SharePoint uses to create and manage tenancies. Without this service, the local farm has no tenancies which means you cannot install or run SharePoint apps. However, when you create new an instance of the Subscription Settings Service Application in an on-prem farm, the service automatically creates a default tenancy. This default tenancy automatically includes all the sites and site collections in the local farm.

The important point is that you do not need to explicitly create tenancies within an on-prem farm. Instead, you simply need to create an instance of the Subscription Settings Service Application and you let it create the default tenant. After creating an instance of the Subscription Settings Service Application, you can complete the configuration for local SharePoint app development by running the following PowerShell cmdlet named to Set-SPAppSiteSubscriptionName to configure a name for the default tenant.

# assign name to default tenant to configure URL used to access app web
Set-SPAppSiteSubscriptionName -Name "WingtipTenant"

Now you know how to configure your development workstation with PowerShell so that you can begin developing apps where the testing and debugging is conducted in local sites. You should also keep I mind that the introduction of SharePoint apps places new requirements on IT Pros and developers alike to configure DNS to ensure that the domain name of a newly created app points back to the web server of the SharePoint host. Visual Studio 2012 provides assistance during development by automatically updating the local LMHOST file to configure the domain name for apps during debugging. However, you should also learn how to use wildcards in DNS so you can redirect any domain beginning with apps.wingtip.com using a single DNS entry.

I will conclude with a complete listing of a Windows PowerShell script that can be used to configure a local farm to allow for SharePoint app development. Remember that this script assumes that you have already run the farm wizard and used it to create an instance of the App Management Service Application. This script also assume that the farm wizard has created a service application pool named SharePoint Web Services Default which will be used as the service application pool with the new service. My hope is that you can copy and paste the PowerShell code in this script and just make minor adjustments to get things up and running. Note I have added a few line breaks to make things more readable online in this post but you will have to remove them before running this script.

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
cls

# assign root domain name to configure URL used to access app webs
Set-SPAppDomain "apps.wingtip.com" –confirm:$false 

# Start SPSubscriptionSettingsService and wait for it to start
Write-Host "Ensure Subscription Settings Service is running" 

$service = Get-SPServiceInstance |
               where{$_.GetType().Name -eq "SPSubscriptionSettingsServiceInstance"} 

if($service.Status -ne "Online") { 
    Write-Host "Starting subscription service" 
    Start-SPServiceInstance $service 
} 

# wait for subscription service to start" 
while ($service.Status -ne "Online") {
  # delay 5 seconds then check to see if service has started   sleep 5
  $service = Get-SPServiceInstance | 
                  where{ $_.GetType().Name -eq "SPSubscriptionSettingsServiceInstance" }
} 

# create an instance Subscription Service Application and proxy if they do not exist 
if($serviceApp -eq $null) { 
  Write-Host "Subscription Service Application does not exist, time to create it" 
  $pool = Get-SPServiceApplicationPool "SharePoint Web Services Default" 
  $serviceAppName = "Setting Service Applicaton" 
  $serviceAppDbName = "Setting_Service_" + [System.Guid]::NewGuid().toString() 
  $serviceApp = New-SPSubscriptionSettingsServiceApplication # [remove line break] 
                                      -ApplicationPool $pool # [remove line break]
                                      -Name $serviceAppName  # [remove line break] 
                                      -DatabaseName $ServiceAppDbName 

  $serviceAppProxy = New-SPSubscriptionSettingsServiceApplicationProxy # [remove line break]
                                                   -ServiceApplication $serviceApp
  
  Write-Host "Instance of the Subscription Service has been created"
}

# assign name to default tenant to configure URL used to access web apps 
Set-SPAppSiteSubscriptionName -Name "WingtipTenant" -Confirm:$false
July 18
SharePoint app code cannot run inside the SharePoint environment

This is the first post in a series of blog posts on the SharePoint app model. Here is the outline of this series.

Get the custom code out of SharePoint

The server-side code you write for a SharePoint solution runs inside the SharePoint environment. For example, managed code deployed in a farm solution runs inside the main SharePoint worker process (w3wp.exe). Managed code deployed using a sandboxed solution runs inside the SharePoint sandbox worker process (SPUCWorkerProcess.exe). However, The SharePoint app model mandates that code from an app cannot run inside any process that is launched or managed by SharePoint.

There are a few simple reasons why Microsoft wants to get rid of custom code that runs inside the SharePoint environment. The first reason has to do with increasing the stability of SharePoint farms. The one is pretty obvious. Getting rid of any type of custom code running inside the SharePoint environment results in lower risk, fewer problems and greater stability for the hosting farm.

The second reason has to do with a company’s ability to upgrade to newer versions of SharePoint. The underlying problem is that SharePoint solutions which contain code that programs against the SharePoint server-side object model have been notorious at creating migration problems when a company is upgrading from one version of SharePoint to the next. More to the point, Microsoft has witnessed many of their biggest SharePoint customers postponing the upgrade of their production farm for months and sometimes years until they have had time to update and test all their SharePoint solutions on the new version of SharePoint. Since this problem negatively affects SharePoint sales revenue, you can bet it was pretty high on the fix-it priority list when Microsoft began to design SharePoint 2013.

Your custom code has to run somewhere

When you develop a SharePoint app you obviously need to write custom code to implement your business logic. It is also clear that app's code must run some place other than the Web servers in the hosting SharePoint farm. The SharePoint app model gives you two places to run your custom code. First, a SharePoint app can contain client-side code which runs inside the browser on the user's machine. Secondly, a SharePoint app can contain server-side code that runs in an external website that is implemented and deployed as part of the app itself.

There are many different ways in which you can design and implement a SharePoint app. For example, you could create SharePoint app that contains only client-side resources such as web pages and client-side JavaScript code which are served up by the SharePoint host. This type of app is known as a SharePoint-hosted app because it doesn't require its own external website. If it's late at night when there's nobody around and your feeling a bit naughty, you could even write a SharePoint-hosted app that uses Silverlight code instead of JavaScript code to implement its client-side business logic.

Now imagine you want to create a second SharePoint app in which you want to write server-side code in a language such as C#. This type of SharePoint app will require its own external website so that your server-side code has a place to execute outside the SharePoint environment. In the new SharePoint 2013 terminology, a SharePoint app with its own external website is known as a Cloud-hosted app. The following diagram shows the key architectural difference between a SharePoint-hosted app and a cloud-hosted app.

HostingApps

From this diagram you can see that both SharePoint-hosted apps and cloud-hosted apps have a start page that represents the app's primary entry point. With a SharePoint-hosted app, the app's start page is served up by the SharePoint host. However, with a cloud-hosted app the start page is served up from the external website. Therefore, SharePoint must track the external URL for each cloud-hosted app that has been installed so that it can redirect users to the app's start page. The SharePoint infrastructure creates a client-side JavaScript component known as a launcher which is used to actually redirect the user from the SharePoint host over to the external app.

When you decide to develop a cloud-hosted SharePoint app, you must take on the responsibility hosting the app's external website. However, this responsibility of creating and deploying an external website along with a SharePoint app also comes with a degree of flexibility. You can implement the external website for a SharePoint app using any existing Web-based development platform.

For example, the external website for a cloud-hosted SharePoint app could be implemented using a non-Microsoft platform such as Java, LAMP or PHP. However, the easiest and the most common approach for SharePoint developers will be to design and implement the external website for cloud-hosted apps using Visual Studio 2012 and the ASP.NET Framework.

Let's look at an example. Imagine you would like to develop a cloud-hosted SharePoint app. Visual Studio 2012 and the new SharePoint Tools provide you with a new project template for SharePoint apps development that quickly create the starting point you need for creating a cloud-hosted SharePoint app. This starting point is a Visual Studio solution which contains two separate projects as shown in the following screenshot.

Cloud-hosted App Projects

The first Visual Studio project in this example is named MyCloudHostedApp. This is the SharePoint app project that creates the distributable installation file named MyCloudHostedApp.app that gets installed inside a SharePoint host. As you can see from the screenshot, this project contains an important XML file named AppManifest.xml which tracks the app’s metadata that is used by SharePoint when the app is installed. The project also contains an image file named AppIcon.png that is used to add a custom icon to the page in SharePoint with the launcher that the user clicks on to navigate to the start page of the app.

The second project named MyCloudHostedAppWeb is used to develop the ASP.NET Web Application that will serve as an implementation of the cloud-hosted app’s external website. Note that Visual Studio uses the naming convention of adding “Web” to the end of the name of the first project to create the name for the second project. Therefore, the project for the SharePoint app is named MyCloudHostedApp and the project for the external website is named MyCloudHostedAppWeb. You will also find that a SharePoint app project such as MyCloudHostedApp has a project property named Web Project which can be used to reference the external website project which allows Visual Studio to recognize these two projects are used together to develop single cloud-hosted app.

From the screenshot above, you can see that the MyCloudHostedAppWeb project contains a page named default.aspx which is located inside a folder named Pages. This page will be used as the app’s start page. Now let's examine the AppManifest.xml file in the SharePoint app project to see how the app's metadata is configured to use default.aspx as its start page.

AppManifest

Note that the app manifest contains a top-level App element with an inner Properties element. Within the Properties element are two required elements named Title and StartPage. The Title element contains human-readable text that is displayed along with the launcher. The StartPage element contains the URL that SharePoint uses in the launcher to redirect the user to the start page in the external website. When an app is deployed into production, the StartPage element will contain the full path to the start page on the Internet.

https://appserver.wintip.com/MyCloudHostedAppWeb/Pages/Default.aspx

When you are developing a cloud-hosted app, Visual Studio provides a convenient dynamic token named ~remoteAppUrl which eliminates your need to hardcode the path to the external website during the development phase. For example, Visual Studio created the StartPage element with the following value.

~remoteAppUrl/Pages/Default.aspx?{StandardTokens}

The reason this works is that the SharePoint app project named MyCloudHostedApp has a Web Project property which associates it with the external website project named MyCloudHostedAppWeb. Whenever you deploy or debug your solution, Visual Studio will perform a substitution to replace ~remoteAppUrl with the current URL of the Web Project. Note that the ~remoteAppUrl token will always be replaced by Visual Studio before the app manifest is installed into a SharePoint host. Therefore, SharePoint really sees a value for the StartPage element that looks like this.

https://localhost:44300/Pages/Default.aspx?{StandardTokens}

Note that the value of the StartPage element in this example contains a second dynamic token named {StandardTokens}. This token is different that the ~remoteAppUrl token because it is not replaced by Visual Studio. Instead, this dynamic token remains inside the app manifest after it has been installed into a SharePoint host. It is the SharePoint infrastructure and not Visual Studio that performs the substitution on this token. Whenever SharePoint uses this StartPage element to create the URL for a launcher, it replaces {StandardTokens} with a standard set of query string parameters used in SharePoint app development such as SPHostUrl and SPLangauge.

default.aspx?SPHostUrl=http%3A%2F%2Fwingtipserver&SPLanguage=en%2DUS

When you implement the code behind the start page of a SharePoint app, you can generally expect that the page is passed these two query string parameters named SPHostUrl and SPLanguage which you can use to determine the language in use and the URL back to the site in the SharePoint host. In quite a few scenarios, SharePoint will add additional query string parameters beyond these two.

What’s nice about developing a cloud-hosted app using this type of Visual Studio solution is that you can develop and debug both projects at the same time within a single session of Visual Studio 2012. This approach will be appealing to experienced .NET developers because it allows them to write the app’s server-side code using C# or VB.NET using the latest and greatest version of the .NET Framework (version 4.5). You can also leverage the libraries of the .NET Framework and benefit from essential Visual Studio support for debugging and IntelliSense. Moreover, the code runs outside of the SharePoint environment so you avoid many of the frustrating limitations and idiosyncratic SharePoint-isms that SharePoint developers have had to deal with over the years. Compare this to writing C# code for a sandboxed solution that has to deal with frustrating limitations of the SharePoint 2010 sandbox. Now that's a good reason to get excited about developing SharePoint apps.

Using an ASP.NET application to implement the external website also provides flexibility in deployment. When deploying a cloud-hosted SharePoint app within a private network, you can host the external website on a local Web server running within the same LAN as the hosting SharePoint farm. For other scenarios that require scaling and/or accessibility from anywhere on the Internet, you can deploy the ASP.NET application in the cloud using Windows Azure Services.

A tale of three app hosting models

When you create your first SharePoint app in Visual Studio 2012, you will not see a specific option to create a cloud-hosted app. Instead, Visual Studio gives you three options for selecting the app's hosting model. The three options you get are Autohosted, Provider-hosted and SharePoint-hosted as shown in the following screenshot.

CreateNewSharePointApp

At a high-level, Autohosted apps and Provider-hosted apps are just two different variations of a cloud-hosted app. Everything I have explained in this blog post about cloud-hosted apps applies equally well to both Autohosted apps and Provider-hosted apps. So then you ask, "what's the difference between the two?" I will first explain what an Provider-hosted app is and then I will finish by discussing the value of an Autohosted app. However, I will keep this discussion at a fairly high level and wait until later in the series to drill down into more detail.

When you decide to create a Provider-hosted app, then you will ultimately be responsible for deploying the external website and making it accessible on the Internet or on a private network. As I mentioned earlier, you have the option of deploying this external website on a local Web server or up in the cloud using Windows Azure services. What is important to see is that the external website must be deployed and made accessible to the users who will access it before you begin to install the SharePoint app that relies on this external website.

The Autohosted app can provide a better strategy for deploying the external website associated with a cloud-hosted app. The main idea is that an Autohosted app calls upon infrastructure built into Office 365 that can automatically deploy the external website when the app is installed. Note that this approach will only work in the Office 365 environment and cannot be used in scenarios in which SharePoint apps are installed within an on-prem farm.

The automated deployment model provided by Autohosted apps relies on a special implementation which integrates Windows Azure Services together with the Office 365 environment. Inside the installation file for an Autohosted app, there is extra metadata and all the ASP.NET application source files required to spin up a Web Site in Windows Azure Services in order to deploy the external website. An Autohosted app can even go one step further by allowing you to automate the creation of a SQL Azure database as part of the app installation process. There are a ton of details you need to know to make it all work, but here I just wanted to explain things at a high level so you can understand that both Provider-hosted apps and Autohosted apps are really just cloud-hosted apps that mainly differ in how their external website gets deployed.

Conclusion

So now you understand one of the key points of the SharePoint app model. Custom code never runs inside SharePoint. It runs somewhere else. You have the option of writing both client-side code and server-side code. A SharePoint-hosted app is easier to create, implement and deploy. However, it does not provide the opportunity to add server-side code. A cloud-hosted app will yield more power because you can write as much server-side code as you would like using a managed language such as C# and your code is not limited by all those frustrating limitations and issues created by running code inside the SharePoint environment. In my next post, I will dive into the details about how the SharePoint infrastructure is able to isolate SharePoint apps with respect to request processing and storing app-specific content within a SharePoint content database.

1 - 10Next
 

About this blog

 
About this blog
Welcome to SharePoint Blogs. Use this space to provide a ;.;.;.message about this blog or blog authors. To edit this content, select "Edit Page" from the "Site Actions" menu.

© Copyright 2012 Ted Pattison.  |  All Rights Reserved
LOGIN