Recently I’ve been looking into building SharePoint apps both for Office 365 and for on-premises SharePoint 2013.

It’s not to complicated but the right steps have to be followed.

First in Visual Studio I created a new app

NewApp1

Supply the Name of the project and click on Ok

NewApp2

I’ve supplied my SharePoint site. In this case I’m selecting my on-premises development site and I want this to be a Provider-hosted application.

Then I’m selecting the ASP.Net MVC Web Application as my web application type. I’m not sure why you would ever go for Web Forms. I guess it just adds an additional step to keep us all entertained.

NewApp3

and then finally as this is an on-premises app I’m selecting the Use a certificate option.

NewApp4

So now we’ve got the base app that is deployable. But still a few things to do as I want this app to create a new list in SharePoint.

In the HomeController.cs I’m going to add the site creation in the Index() module. This will not be the right place of course to do this, but I wanted to keep my example easy to replicate.

I’m adding the following code (the bits in bold are new the rest of the code I’ve included to show the right location.) I’m only going to create a simple custom list.

Web spWeb = null;

var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);

using (var clientContext = spContext.CreateUserClientContextForSPHost())

{

if (clientContext != null)

{

spWeb = clientContext.Web;

clientContext.Load(spWeb, web => web.Url);

clientContext.ExecuteQuery();

ViewBag.WebUrl = spWeb.Url;

ListCreationInformation listInfo = new ListCreationInformation();

listInfo.Title = “My Test List”;

listInfo.TemplateType = (int)ListTemplateType.GenericList;

List splist = spWeb.Lists.Add(listInfo);

splist.Description = “My Test List Description”;

splist.Update();

clientContext.ExecuteQuery();

}

}

 

Now I’m ready to deploy the solution. I’m hitting F5 in Visual studio and my app is appearing:

TrustApp

I’m trusting it and … Visual studio is complaining:

 

AppAccessDenied

Microsoft.SharePoint.Client.ServerUnauthorizedAccessException was unhandled by user code
  HResult=-2146233088
  Message=Access denied. You do not have permission to perform this action or access this resource.

 

Hmm, I’m getting an access denied. I did trust the app, so what is wrong. Within the app the permissions needed by the app will need to be supplied.

In my case I’m going to be lazy and I’m giving the app full control on the site collection.

AppManifestxml

Now the app runs successfully and my custom list is added.

job-done

Advertisements