Click here to Skip to main content
15,879,095 members
Articles / Hosted Services / Azure

Creating A LightSwitch SharePoint 2013 Multi-Tenant Provider-Hosted Application

Rate me:
Please Sign up or sign in to vote.
4.80/5 (4 votes)
19 Aug 2014CPOL9 min read 31.8K   81   4   8

image

Download the Code: CloudBusinessTasks.zip

When you deploy your SharePoint Provider-Hosted Cloud Business App, you can use an authentication key from the Microsoft Seller Dashboard to allow multiple SharePoint websites to consume the same website application. You can segment the data so that each SharePoint website only sees its own data using row level filtering.

Note: To complete this tutorial you must have Visual Studio 2013 with the Visual Studio 2013 Update 2 (or higher) installed.

The Life Of A Cloud Business Application

A SharePoint Cloud Business app (CBA) is deployed in a multiple parts.  First, there is the traditional web hosting provider (such as Azure websites) for the CBA to run on.  Next, the SharePoint specific parts and metadata (for example, the lists the app uses or any special SharePoint types it defines) are installed on the SharePoint site that the CBA is installed on (the application is installed using an .app file). 

image

The following are the steps performed when a user runs the CBA application in SharePoint:

  • The user opens their web browser and navigates to the SharePoint site
  • The user launches the CBA app by clicking a link on the SharePoint site
  • SharePoint redirects browser to the 3rd party web server where the LightSwitch SharePoint enabled Cloud Business App (CBA) is located.  This redirect sends along special SharePoint OAuth authentication.
  • The CBA app detects the SharePoint identity and talks back to SharePoint to make sure the user is who they claim to be
  • The CBA can now impersonate the user whenever they communicate with SharePoint

Create The Sample Application

image

Open Visual Studio and select File, then New Project, and create a Cloud Business App.

image

Point it to your SharePoint developer site (or click the link to take you to the website that shows you where we can sign up for a SharePoint developer site).

image

After the Solution is created, right-click on the Data Sources folder in the Server project and select Add Table.

Create a table with the following structure:

image

Next, set the table to update the SharePoint Newsfeed

image

Click on the table header so that you set scope to the entire table. In the table Properties, enable the Created and Updated post settings under Social.

Set the Summary Property to TaskName.

Enable Multi-Tenant Capability

We will enable multi-tenant capability in the application by programmatically recording the website that the user is coming from, in the HostURL property in the Task table, and setting a filter that will only show a user data from the website they are coming from.

image

While the table is still selected, select Write Code then Tasks_Inserting.

Use the following code for the method:

partial void Tasks_Inserting(Task entity)
{
    // Set the HostURL
    entity.HostURL = this.Application.SharePoint.HostUrl.Host;
}

image

Return to the table designer, select the table, and select Write Code then Tasks_Updating.

Use the following code for the method:

 partial void Tasks_Updating(Task entity)
{
    // Set the HostURL
    entity.HostURL = this.Application.SharePoint.HostUrl.Host;
}

image

Return to the table designer, select the table, and select Write Code then Tasks_Filter.

Use the following code for the method:

 partial void Tasks_Filter(ref Expression<Func<Task, bool>> filter)
{
    // Only allow users to see records from their own site
    filter = e => e.HostURL == this.Application.SharePoint.HostUrl.Host;
}

Note: For more information on how the filtering works, see the LightSwitch article on row level filtering.

image

The HostURL field is set as a required field. We need to provide a default value for it (even though the value will be overwritten in server-side code).

Select the HTMLClient tab  and then Write Code, and then created, to create client-side JavaScript code for the Task entity.

Use the following code for the created method:

myapp.Task.created = function (entity) {
    // Set a default value.
    // This will be overwritten
    // in the Inserting/Updating
    // methods.
    entity.HostURL = " ";
};

Create The Screens

image

Right-click on the Screen folder in the Client project and select Add Screen.

image

Select the Common Screen Set template.

image

The screens will be created.

Format The Screen

image

We don’t need the HostURL displayed on the edit screen.

Open the AddEditTask screen, by double-clicking on it in the Solution Explorer.

Right-click on the Host URL control to select it, and delete it.

Add A Delete Button

image

We can customize the application to add a Delete button.

Open the View Task screen, and click on the Command Bar to expand it.

Click the Add button and add a Delete button.

image

A Delete method will show in the View Model on the left-hand side of the screen.

Right-click on the Delete method and select Edit Execute Code.

Use the following code for the method:

myapp.ViewTask.Delete_execute = function (screen) {
    // Delete the Task
    screen.Task.deleteEntity();
    // Save changes
    myapp.commitChanges().then(null, function fail(e) {
        // There was an error - show it in a box
        msls.showMessageBox(e.message, {
            title: "Error",
            buttons: msls.MessageBoxButtons.ok
        }).then(function (result) {
            if (result === msls.MessageBoxResult.ok) {
                // Discard Changes
                screen.details.dataWorkspace.ApplicationData
                    .details.discardChanges();
            }
        });
    });
};

Test The Project

image

We will now Debug the application.

Note: While we will be directed to and logged into the SharePoint website, it will pass us back to our local development machine, and we will be running the application directly from our development machine.

Select Debug, then Start Debugging to Debug the project.

image

You will be prompted to log into your SharePoint development site.

image

You may also have to log into the web page of your SharePoint developer website.

image

You will have to Trust the application.

image

The application will load.

image

We can add Tasks by clicking the Add button.

image

We can enter task details, and save them by clicking the Save button.

image

Clicking on a Task shows the details and allows us to Edit or Delete the Task.

We can see that the Host URL is programmatically set.

image

We can also navigate to the Newsfeed

image

The Task will show in the Newsfeed with an option to follow any changes or navigate directly to it.

Publish The Application

image

You will need to determine the location that you plan to publish your website application to.

Creating a website on Azure is a good choice.

Wherever you decide to deploy your website to, you must publish to a site that has a domain name (not an IP address) that has a (SSL) secure certificate (https://).

image

The URL will be required to create a client id, and it is also required for the Visual Studio publishing wizard (used to actually deploy the application to production).

image

The application will need a database, so be sure to create a linked resource

image

…and specify a SQL Database.

Obtain A Client ID

image

To obtain a client id that will allow your application to be published in multiple SharePoint sites, you need to go to: http://sellerdashboard.microsoft.com and create an account.

The following steps only create a client id, it does not publish your application to the Microsoft Office 365 or SharePoint Online store. A client id is required for that process, but to actually publish your application in the store there is a secondary process.

image

After your account is approved (this may take a few days), log in and select APPS, then client ids and then add a new oauth client id.

image

Fill out the form.

  • Friendly Client ID Name – Any name you want
     
  • App Domain - The domain name without the “https://” part 
     
  • App Redirect URL – Using this form: https://DomainName.com/SharePointLaunch.aspx?{StandardTokens}

image

You will receive your Client ID and Client Secret that you will need in the publishing wizard (in the next step).

Using The Publishing Wizard

image

In Visual Studio, open the Configuration Manager.

image

Change to Release mode.

image

While still in Visual Studio, open the publishing wizard.

image

Select Provider-hosted for SharePoint Options.

image

Choose your hosting option and click Next.

image

If you are using a Azure Web Site you would select it at this point.

image

The Azure Web Site option will allow you to sign in and select the web site you configured.

image

For Security Setting you must set https to required.

Therefore you must host the site at a location that has a secure certificate so that https will work. You cannot use a IP address, you must use a domain name.

image

Enter the domain name for the application, including the “https://” part.

For SharePoint Client ID and Client secret, enter the values saved earlier.

image

On the Summary page, click Publish to deploy the application.

Note, you will not be able to log into the website unless you are calling it through the SharePoint website using a link that will be created in the next step.

image

The .app file will also be created (Visual Studio will open it up in a window), we can now upload it to our SharePoint site.

Deploy The Application

image

To properly test your application, you will want to obtain another SharePoint site for testing.

See: Creating A SharePoint Online Testing Site for directions on creating a test site and deploying the application using the .app file.

image

When we run the application, each site can only see their own data.

image

When we log directly into the database we see that it stores data from each SharePoint site it is deployed on.

Changing The Database Connection String At Runtime

You can change the database connection string at run-time to allow each tenant to have their own database.

image

This method isn’t available in the Write Code drop down on the designers.  Instead, to find it, go into the ApplicationDataService.lsml.cs file

image

… and start typing “partial “ and intellisense will show you an auto-complete drop down.  You can then select the _InitializingConnection method. 

image

The DatabaseConnectionState object passed into this method has one property, the ConnectionString, that you can get/set as needed.  This allows you to switch your data connection at runtime based on any rule you desire.

This method is only available for "Database" connections (either the ApplicationData or another attached Database data source).

For OData service and SharePoint data sources, the partial methods are:

partial void DeveloperData_SendingRequest(ODataSendingState state)
partial void DeveloperData_ReceivedResponse(ODataReceivedState state)

These methods allow you to intercept/inspect the outgoing request to the backend OData service, and inspect the incoming response from the backend service.

Special Thanks

A special thanks to Matt Evans, Eric Erhardt, Josh Booker, and Dave Kidder and for assistance in creating this article.

Links – Microsoft (LightSwitch)

SharePoint Hosting & Authentication Options for LightSwitch (Brian Moore)

Publishing LightSwitch apps for SharePoint to the Catalog (Brian Moore)

Using the Person Business Type

Integrating Documents in Cloud Business Apps

All About Newsfeeds With Your Cloud Business App (Nicole Haugen)

Links – Microsoft (Seller Dashboard)

Create Your Account and Add Payout Information in the Microsoft Seller Dashboard

How to: Create client IDs and secrets in the Microsoft Seller Dashboard

Create Client IDs and Secrets in the Microsoft Seller Dashboard

Microsoft Seller Dashboard FAQ

Links – LightSwitch Help Website

Deploy A LightSwitch Application To Office 365 / SharePoint Online

Creating A SharePoint Online Testing Site

Exploring SharePoint 2013 Visual Studio Cloud Business Apps (LightSwitch)

Implementing Documents in a SharePoint 2013 Cloud Business App (LightSwitch)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) http://ADefWebserver.com
United States United States
Michael Washington is a Microsoft MVP. He is a ASP.NET and
C# programmer.
He is the founder of
AiHelpWebsite.com,
LightSwitchHelpWebsite.com, and
HoloLensHelpWebsite.com.

He has a son, Zachary and resides in Los Angeles with his wife Valerie.

He is the Author of:

Comments and Discussions

 
QuestionTrouble enabling SharePoint to CBA Pin
seebiz27-May-15 3:20
seebiz27-May-15 3:20 
AnswerRe: Trouble enabling SharePoint to CBA Pin
defwebserver27-May-15 5:29
defwebserver27-May-15 5:29 
I am sorry but I have never seen that error. The only thing I can suggest is reinstalling the Office Developer tools.
QuestionDelete Button not function Pin
Member 1118488227-Oct-14 16:07
Member 1118488227-Oct-14 16:07 
AnswerRe: Delete Button not function Pin
defwebserver27-Oct-14 17:45
defwebserver27-Oct-14 17:45 
QuestionRunning this application does not open the website on Dev machine Pin
Member 45500574-Sep-14 13:11
Member 45500574-Sep-14 13:11 
AnswerRe: Running this application does not open the website on Dev machine Pin
defwebserver4-Sep-14 13:32
defwebserver4-Sep-14 13:32 
QuestionCreated an addendum ;-) Pin
Jan Van der Haegen21-Aug-14 12:55
Jan Van der Haegen21-Aug-14 12:55 
AnswerRe: Created an addendum ;-) Pin
defwebserver21-Aug-14 13:05
defwebserver21-Aug-14 13:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.