You are here:   Blog
Register   |  Login

 

Jun 1

Written by: Michael Washington
6/1/2014 8:45 AM  RssIcon

image

A Cloud Business App is simply a Visual Studio LightSwitch application configured to run on SharePoint 2013 (or higher). However, enabling the SharePoint framework adds a lot of functionality:

It is the SharePoint Web / User that we will explore here.

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

Create A Cloud Business App

image

Create a New Project.

image

Create a Cloud Business App.

image

Next enter the destination to your development SharePoint site, or click the link to take you to the website that shows you where we can sign up for a SharePoint developer site (this is recommended).

image

The Solution will be created.

Create The Screen to Display The SharePoint Information

image

We want to create a screen that will display SharePoint information about the current user.

Right-click on the Screens folder in the HTMLClient project, and select Add Screen.

image

Create a Browse Data Screen called Main.

image

Select the Rows Layout element, then select Add then New Custom Control.

image

Click OK.

image

In the Properties for the control, set the Display Name and click the Edit Render Code link.

Use the following code for the method:

 

myapp.Main.ScreenContent_render = function (element, contentItem) {
    $.ajax({
        type: 'post',
        data: {},
        url: '../UserPermissions.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.permissions = jQuery.parseJSON(result);
            var strHeader = "";
            // Loop through each row returned
            $.each(myapp.permissions, 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/>");
            });
        }
    });
};

 

Create The Code to Display The SharePoint Information

image

We will now create a Generic Handler (.ashx) that will supply information to the screen we just created.

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

image

Create a Generic Handler.

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.

We will use ServerApplicationContext to connect to the LightSwitch service layer.

Use the following code for the Generic 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 perm
    {
        public string Type { get; set; }
        public string Value { get; set; }
    }
    public class UserPermissions : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            List<perm> perms = new List<perm>();
            using (ServerApplicationContext ctx = ServerApplicationContext.CreateContext())
            {
                var currentUser = ctx.Application.User;
                if (currentUser.IsAuthenticated)
                {
                    // Identities for current User
                    perms.Add(new perm() { 
                        Type = "LightSwitch User", Value = String.Format("{0} - {1}", "Id", currentUser.Id.ToString()) });
                    perms.Add(new perm() { 
                        Type = "LightSwitch User", Value = String.Format("{0} - {1}", "LoginName", currentUser.LoginName) });
                    perms.Add(new perm() { 
                        Type = "LightSwitch User", Value = String.Format("{0} - {1}", "PersonId", currentUser.PersonId) });
                    perms.Add(new perm() { 
                        Type = "LightSwitch User", Value = String.Format("{0} - {1}", "SIPAddress", currentUser.SIPAddress) });
                    perms.Add(new perm() { 
                        Type = "LightSwitch User", Value = String.Format("{0} - {1}", "Title", currentUser.Title) });
                    perms.Add(new perm() { 
                        Type = "LightSwitch User", Value = String.Format("{0} - {1}", "Department", currentUser.Department) });
                    perms.Add(new perm() { 
                        Type = "LightSwitch User", Value = String.Format("{0} - {1}", "Email", currentUser.Email) });
                    perms.Add(new perm() { 
                        Type = "LightSwitch User", Value = String.Format("{0} - {1}", "Name", currentUser.Name) });
                    perms.Add(new perm() { 
                        Type = "LightSwitch User", Value = String.Format("{0} - {1}", "FullName", currentUser.FullName) });
                    perms.Add(new perm() { 
                        Type = "LightSwitch User", Value = String.Format("{0} - {1}", "Identity.Name", currentUser.Identity.Name) });
                    perms.Add(new perm() { 
                        Type = "LightSwitch User", Value = String.Format("{0} - {1}", "Identity.AuthenticationType", currentUser.Identity.AuthenticationType) });
                    perms.Add(new perm() { 
                        Type = "LightSwitch User", Value = String.Format("{0} - {1}", "IsAnonymous", currentUser.IsAnonymous.ToString()) });
                    perms.Add(new perm() { 
                        Type = "LightSwitch User", Value = String.Format("{0} - {1}", "IsAuthenticated", currentUser.IsAuthenticated.ToString()) });
                    perms.Add(new perm() { 
                        Type = "LightSwitch User", Value = String.Format("{0} - {1}", "IsAuthorized", currentUser.IsAuthorized.ToString()) });
                    perms.Add(new perm() { 
                        Type = "LightSwitch User", Value = String.Format("{0} - {1}", "Mobile", currentUser.Mobile) });
                    perms.Add(new perm() { 
                        Type = "LightSwitch User", Value = String.Format("{0} - {1}", "NameIdentifier", currentUser.NameIdentifier) });
                    perms.Add(new perm() { 
                        Type = "LightSwitch User", Value = String.Format("{0} - {1}", "NameIdentifierIssuer", currentUser.NameIdentifierIssuer) });
                    
                }
                else
                {
                    perms.Add(new perm() { 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(perms));
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

image

Run the application.

image

You will be required to log into your SharePoint developer website.

image

You will 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

The information for the current user will display.

Accessing The SharePoint CSOM API

The LightSwitch SharePoint object exposed by ServerApplicationContext also gives you a method: GetHostWebClientContext() which allows you to make any SharePoint client object model (CSOM) call back into the SharePoint host. This is important because the API is constantly changing as new features are added.

We add the following code to the Generic Handler:

 

                    // Call the SharePoint CSOM API
                    var clientContext = ctx.Application.SharePoint.GetHostWebClientContext();
                    //Load the properties for the web object. 
                    Microsoft.SharePoint.Client.Web web = clientContext.Web;
                    // Get the current web 
                    clientContext.Load(web);
                    clientContext.ExecuteQuery();
                    //Get the site name. 
                    string siteName = web.Title;
                    perms.Add(new perm()
                    {
                        Type = "siteName",
                        Value = siteName
                    });

 

When we run the application we get the following result:

image

Group Membership Of The Current User

We can get the groups the current user belongs to using the following code:

 

                    // Groups for current User
                    Microsoft.SharePoint.Client.GroupCollection UserGroups = web.CurrentUser.Groups;
                    clientContext.Load<Microsoft.SharePoint.Client.GroupCollection>(UserGroups);
                    clientContext.ExecuteQuery();
                    foreach (var item in UserGroups)
                    {
                        perms.Add(new perm()
                        {
                            Type = "Groups for current User",
                            Value = string.Format("Title: {0} - Description: {1}", 
                            item.Title, item.Description)
                        });
                    }

 

image

We can add the current user to a group by running the application and navigating to the site.

image

Navigating to Site settings

image

Selecting Site permissions

image

Selecting a group…

image

Selecting Add users to this group

image

Adding the current user.

image

We can return to the application by selecting Apps in Testing.

image

We then select the application.

We then get the following display:

image

Information About The Current SharePoint Website

We can get additional information about the current SharePoint website using the following code:

 

                    //Load the RoleDefinitions from the Web object. 
                    Microsoft.SharePoint.Client.RoleDefinitionCollection roles = web.RoleDefinitions;
                    clientContext.Load<Microsoft.SharePoint.Client.RoleDefinitionCollection>(roles);
                    clientContext.ExecuteQuery();
                    foreach (var item in roles)
                    {
                        perms.Add(new perm()
                        {
                            Type = "Roles",
                            Value = string.Format("Name: {0} - Description: {1}", item.Name, item.Description)
                        });
                    }
                    //Load the Groups from the Web object. 
                    Microsoft.SharePoint.Client.GroupCollection groups = web.SiteGroups;
                    clientContext.Load<Microsoft.SharePoint.Client.GroupCollection>(groups);
                    clientContext.ExecuteQuery();
                    foreach (var item in groups)
                    {
                        perms.Add(new perm()
                        {
                            Type = "Groups - " + item.Title,
                            Value = string.Format("Description: {0} - Description: {1}", item.Title, item.Description)
                        });
                        // Get Users in Group
                        try
                        {
                            Microsoft.SharePoint.Client.UserCollection users = item.Users;
                            clientContext.Load<Microsoft.SharePoint.Client.UserCollection>(users);
                            clientContext.ExecuteQuery();
                            foreach (var User in users.ToList())
                            {
                                perms.Add(new perm()
                                {
                                    Type = item.Title + " - Users",
                                    Value = string.Format("LoginName: {0} - Title: {1}", User.LoginName, User.Title)
                                });
                            }
                        }
                        catch (Exception ex)
                        {
                            perms.Add(new perm()
                            {
                                Type = item.Title + " - Users",
                                Value = string.Format("Could not get users - {0}", ex.Message)
                            });
                        }
                    }
                    //Load the lists from the Web object. 
                    Microsoft.SharePoint.Client.ListCollection lists = web.Lists;
                    clientContext.Load<Microsoft.SharePoint.Client.ListCollection>(lists);
                    clientContext.ExecuteQuery();
                    foreach (Microsoft.SharePoint.Client.List list in lists)
                    {
                        perms.Add(new perm()
                        {
                            Type = "SharePoint Lists",
                            Value = string.Format("Title: {0} - EntityTypeName: {1} - ItemCount: {2}", 
                            list.Title, list.EntityTypeName, list.ItemCount)
                        });
                    }
                    //Load the current users from the Web object. 
                    Microsoft.SharePoint.Client.UserCollection SiteUsers = web.SiteUsers;
                    clientContext.Load<Microsoft.SharePoint.Client.UserCollection>(SiteUsers);
                    clientContext.ExecuteQuery();
                    foreach (Microsoft.SharePoint.Client.User siteUser in SiteUsers.ToList().OrderBy(x => x.Id))
                    {
                        perms.Add(new perm()
                        {
                            Type = "SharePoint Users",
                            Value = string.Format("Id: {0} - Title: {1} - IsSiteAdmin: {2}", 
                            siteUser.Id, siteUser.Title, siteUser.IsSiteAdmin)
                        });
                    }
                    // Get all the top level folder collection from the website
                    Microsoft.SharePoint.Client.FolderCollection folders = clientContext.Web.Folders;
                    clientContext.Load<Microsoft.SharePoint.Client.FolderCollection>(folders);
                    clientContext.ExecuteQuery();
                    foreach (var item in folders.ToList().OrderBy(x => x.ItemCount))
                    {
                        perms.Add(new perm()
                        {
                            Type = "[Folders]",
                            Value = string.Format("Name: {0} - ItemCount: {1}", item.Name, item.ItemCount)
                        });
                        // Get the Files
                        Microsoft.SharePoint.Client.FileCollection files = item.Files;
                        clientContext.Load<Microsoft.SharePoint.Client.FileCollection>(files);
                        clientContext.ExecuteQuery();
                        foreach (var objFile in files)
                        {
                            perms.Add(new perm()
                            {
                                Type = item.Name + " - Files",
                                Value = string.Format("Name: {0} - TimeLastModified: {1}", 
                                objFile.Name, objFile.TimeLastModified)
                            });
                        }
                    }

 

 

This produces the following result:

image

and:

image

and:

image

See: Implementing Documents in a SharePoint 2013 Cloud Business App (LightSwitch) for more examples of using CSOM for SharePoint list creation.

Special Thanks

A special thanks to Eric Erhardt, Dave Kidder, and Karol Zadora-Przylecki 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)

Customizing the SharePoint Chrome Control in LightSwitch

Walkthrough: Creating an App for SharePoint by Using LightSwitch

Using the Person Business Type

Integrating Documents in Cloud Business Apps

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

Videos – Microsoft (LightSwitch)

How Do I: Build and Deploy My First Cloud Business App on Office 365?

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

How Do I: Use Newsfeeds to Socialize Data in a Cloud Business App?

Links – Microsoft (SharePoint General)

SharePoint 2013: Hello World remote app using CSOM

How to: Complete basic operations using SharePoint 2013 client library code

Microsoft.SharePoint.Client namespace

Sign up for an Office 365 Developer Site, set up your tools and environment, and start deploying apps

How to: Provision a Developer Site using your existing Office 365 subscription

How to: Set up an on-premises development environment for apps for SharePoint

Links – SharePoint E-Book

SharePoint 2013 .Net Client Side Object Model Cookbook (this is a free e-book from C# Corner)

Links – LightSwitch Help Website

Deploy A LightSwitch Application To Office 365 / SharePoint Online

Creating A SharePoint Online Testing Site

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

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

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

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)


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