You are here:   Blog
Register   |  Login

 

Jun 8

Written by: Michael Washington
6/8/2014 9:10 PM  RssIcon

image

You can create a Visual Studio LightSwitch SharePoint enabled Cloud Business App (CBA) that consumes and updates SharePoint Lists, including uploading documents to SharePoint Document Libraries. You can even dynamically create SharePoint Document Libraries in code so that they are available for use in your multi-tenant provider-hosted SharePoint applications.

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

To understand how documents are integrated into a CBA app, we will first walk-thru the completed application:

image

We install the CloudBusinessTasks application and click on it to run it.

image

The application loads.

image

A message indicates that a SharePoint List called TaskDocuments has been created.

image

We create a Task.

image

We click on the Task we just created to edit it.

image

We select the Documents tab.

image

We select Add Document.

image

We have the option to upload a document or create one.

We decide to create a new Microsoft Word Document.

image

The document is created, we edit it, and we navigate back to the website.

image

In the SharePoint site, we see the document has automatically been saved and uploaded to the TaskDocuments library.

We can click on the CloudBusinessTasks link to navigate back into the application.

(note: while we were editing the document, we could have clicked the web browser ‘back’ button to automatically save the document and navigate directly back to the application)

image

We note that this time the message indicates that the Document Library already exists.

We can click on the Task to see the details.

image

Clicking on the Documents tab shows us all the documents associated with the Task.

image

Clicking on a document opens it up.

Creating The Application

image

We start with the application created in: Creating A LightSwitch SharePoint 2013 Multi-Tenant Provider-Hosted Application.

Create The Document Library List

image

First, we need to create a SharePoint Document Library List.

Log into your SharePoint Development site, and click add an app under Site Contents.

 

image

Add a Document Library.

image

Call it TaskDocuments.

image

After the list is added to the list of apps in Site Contents, select the SETTINGS.

We now need to add a column (TaskID) to allow us to associate a Document to a Task.

image

In the Settings, select Create column.

image

Call the column TaskID and set its type to Single line of text.

This is so that each document can be associated with a Task in the application.

Click OK.

Connect To The Document Library

image

In Visual Studio, right-click on Data Sources and select Add Data Source.

image

Select SharePoint.

image

Enter the address of your Development SharePoint server.

image

You may have to log in.

image

Select the TaskDocuments from Document Libraries, and UserInformationList from Lists.

image

The lists will show in the project.

Enhance The Task Table

image

Open the Task table and create a field called TaskID.

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;
            // Create a unique ID for this Task
            // so that we can also store it in the Document
            // Library document to relate it to the Task
            entity.TaskID = System.Guid.NewGuid().ToString();
        }

 

 

image

  1. Return to the Task table and click the Relationship button.
  2. Select TaskDocument as the To table.
  3. Set the Multiplicity to One to Many.
  4. Set TaskID as the Primary and Foreign keys.

image

The relationship will show.

Update The Screens – Documents

image

Open the ViewTask screen and select the Add TaskDocuments link (that now shows because we created a relationship between the Task table and the TaskDocuments SharePoint Document Library list).

image

Select the Tabs node and then select Add Tab.

image

Select the Tab that was just added and change it’s name in its Properties to Documents.

select Add under the section and then select the Task Documents collection.

image

Select the Command Bar to open it, and click Add to add a Button.

For the Button method, select the TaskDocuments.createOrUpdateDocument method.

image

In the Properties for the Button change its name to AddDocument.

Update The Screens – Main Screen

image

We will now create JavaScript on the first page, that will call a handler (StartUpTasks.ashx), that will dynamically create the SharePoint Document Library List (if needed).

Open the BrowseTasks screen and add a New Custom Control to the screen.

image

Use the default data path.

image

Drag the control to the top position.

image

In the Properties for the control, set the Label Position to None.

image

Also, in the Properties for the control, select Edit Render Code.

Use the following code for the method:

 

myapp.BrowseTasks.ScreenContent_render = function (element, contentItem) {
    $.ajax({
        type: 'post',
        data: {},
        url: '../StartUpTasks.ashx',
        success: function success(result) {
            // Parse the JSON returned
            //attach the permissions to the global 'myapp' object 
            //so it is accessible to the client anywhere.
            myapp.settings = jQuery.parseJSON(result);
            var strHeader = "";
            // Loop through each row returned
            $.each(myapp.settings, function () {
                var strCurrentHeader = this.Type;
                var strValue = this.Value;
                // Only show header if it has changed
                if (strHeader !== strCurrentHeader) {
                    // Update strCurrentHeader
                    strHeader = strCurrentHeader;
                    $(element).append("<b><u>" + strHeader + "</u></b><br/>");
                }
                // Show value of the current row
                $(element).append(strValue + "<br/>");
            });
        }
    });
};

 

The Handler - Create The SharePoint List (If Needed)

image

We will now create the handler, that will dynamically create the SharePoint Document Library List (if needed).

Right-click on the Server project and select Add then New Item.

image

Create a Generic Handler called StartUpTasks.ashx, and use the following code for the handler:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.LightSwitch.Server;
using Microsoft.LightSwitch.Security;
using Microsoft.LightSwitch.Security.Server;
using LightSwitchApplication;
namespace LightSwitchApplication
{
    [Serializable]
    public class setting
    {
        public string Type { get; set; }
        public string Value { get; set; }
    }
    public class StartUpTasks : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            List<setting> settings = new List<setting>();
            using (ServerApplicationContext ctx = ServerApplicationContext.CreateContext())
            {
                var currentUser = ctx.Application.User;
                if (currentUser.IsAuthenticated)
                {
                    // Call the SharePoint CSOM API
                    var clientContext = ctx.Application.SharePoint.GetHostWebClientContext();
                    // Get the current web 
                    Microsoft.SharePoint.Client.Web web = clientContext.Web;
                    clientContext.Load(clientContext.Web);
                    clientContext.ExecuteQuery();
                    // Check to see if SharePoint List 'TaskDocuments' exists
                    Microsoft.SharePoint.Client.ListCollection lists = web.Lists;
                    clientContext.Load<Microsoft.SharePoint.Client.ListCollection>(lists);
                    clientContext.ExecuteQuery();
                    var TaskDocumentsList = (from objTaskDocument in lists.ToList() 
                                             where objTaskDocument.EntityTypeName == "TaskDocuments" 
                                             select objTaskDocument).SingleOrDefault();
                    
                    if (TaskDocumentsList != null)
                    {
                        // List exists - show it
                        settings.Add(new setting()
                        {
                            Type = "TaskDocuments SharePoint List [Exists]",
                            Value = string.Format("Title: {0} - EntityTypeName: {1} - ItemCount: {2}",
                            TaskDocumentsList.Title,
                            TaskDocumentsList.EntityTypeName,
                            TaskDocumentsList.ItemCount)
                        });
                    }
                    else
                    {
                        // List does not exist - Create it
                        Microsoft.SharePoint.Client.ListCreationInformation creationInfo =
                            new Microsoft.SharePoint.Client.ListCreationInformation();
                        creationInfo.Title = "TaskDocuments";
                        creationInfo.TemplateType = (int)Microsoft.SharePoint.Client.ListTemplateType.DocumentLibrary;
                        Microsoft.SharePoint.Client.List lstTasksDocuments = web.Lists.Add(creationInfo);
                        lstTasksDocuments.Description = "Task Documents";
                        clientContext.ExecuteQuery();
                        // Add TaskID field
                        Microsoft.SharePoint.Client.Field fldTaskID =
                            lstTasksDocuments.Fields.AddFieldAsXml(
                            "<Field DisplayName='TaskID' Type='Text' />",
                            true,
                            Microsoft.SharePoint.Client.AddFieldOptions.DefaultValue
                            );
                        Microsoft.SharePoint.Client.FieldNumber fldNumber =
                            clientContext.CastTo<Microsoft.SharePoint.Client.FieldNumber>(fldTaskID);
                        lstTasksDocuments.Update();
                        clientContext.ExecuteQuery();
                        // Show the list 
                        Microsoft.SharePoint.Client.List TaskDocumentsListCreated = web.Lists.GetByTitle("TaskDocuments");
                        clientContext.Load(TaskDocumentsListCreated);
                        clientContext.ExecuteQuery();
                        settings.Add(new setting()
                        {
                            Type = "TaskDocuments SharePoint List [Created]",
                            Value = string.Format("Title: {0} - EntityTypeName: {1} - ItemCount: {2}",
                            TaskDocumentsListCreated.Title,
                            TaskDocumentsListCreated.EntityTypeName,
                            TaskDocumentsListCreated.ItemCount)
                        });
                    }
                }
                else
                {
                    settings.Add(new setting() { Type = "", Value = "You are not authenticated" });
                }
            }
            // Create JavaScriptSerializer
            System.Web.Script.Serialization.JavaScriptSerializer jsonSerializer =
                new System.Web.Script.Serialization.JavaScriptSerializer();
            // Output as JSON
            context.Response.Write(jsonSerializer.Serialize(settings));
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

 

image

So that the System.Web.Script.Serialization.JavaScriptSerializer code will work, right-click on References for the project, and add a reference to System.Web.Extensions.

Build And Deploy

Follow the directions in the article: Creating A LightSwitch SharePoint 2013 Multi-Tenant Provider-Hosted Application to build and deploy the project.

Download Code

The LightSwitch project is available at http://lightswitchhelpwebsite.com/Downloads.aspx

(you must have Visual Studio 2013 (or higher) installed and a SharePoint Developer site to run the code)

Special Thanks

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

Links – Microsoft

Integrating Documents in Cloud Business Apps

Using SharePoint Lists as LightSwitch Entities and with CSOM (Chris Rummel)

Incident manager: A cloud business app tutorial

How to: Associate a document library with an entity

How Do I: Incorporate Document Libraries in a Cloud Business App?

Troubleshooting document libraries

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)

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

Embedding Your LightSwitch Cloud Business App Inside SharePoint As a App Part

2 comment(s) so far...


Gravatar

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

Michael, is your event handler for creating the SharePoint list necessary anymore? Or can the list be created and deployed without code in current versions of Visual Studio? I would like to understand the pros and cons of each method.

By ThoroughbredTech on   12/10/2014 10:25 AM
Gravatar

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

@ThoroughbredTech - I was unable to get the no code list creation to work. Also, you don't need that code if you create the list manually. However, if you have an app in the app store you don't want to require your customers to have to carefully create any needed lists :)

By Michael Washington on   12/10/2014 10:32 AM

Your name:
Gravatar Preview
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Title:
Comment:
Security Code
CAPTCHA image
Enter the code shown above in the box below
Add Comment   Cancel 
Microsoft Visual Studio is a registered trademark of Microsoft Corporation / LightSwitch is a registered trademark of Microsoft Corporation