Click here to Skip to main content
Licence CPOL
First Posted 10 Feb 2012
Views 17,544
Downloads 142
Bookmarked 3 times

Custom Webservices with SharePoint Online for Office 365

By | 14 Feb 2012 | Article
Development of webservices using sandbox solutions

Introduction

Office 365 is the next-generation cloud productivity service that delivers important functionalities for business, investing less than on-premise solution.

It brings together 2010 editions of Exchange Online, Lync Online, Office tools and SharePoint Online as a cloud service for organizations of all sizes.

In particular Sharepoint Online provides a solid business collaboration platform on which developers can build solutions by using standard development tools such as Microsoft SharePoint Designer 2010 and Microsoft Visual Studio 2010. However by developer point of view Sharepoint Online puts many constraints and we need to modify the standard development pattern.

We can only deploy sandboxed solutions, that create secured wrapper around webparts and other elements with some limitation about Sharepoint Object Model. They cannot absolutely modify or add any files to file system and all our code runs in separate worker processes and not in w3wp.exe.
This kind of solutions has pros (it doesn't require Application Pool Recycling!!) and cons (first of all it doesn't support Security Elevation). This article deals with the issue that forbids us to deploy any WCF or "old" asmx service using Sharepoint Sandbox solutions.
The suggested solution overcomes this limitation, simulating a webservice with a simple ASPX page that returns data in JSON format rather than standard text/html.

In details we create:
  • a sandbox webpart to encapsulate business logic of the service
  • a custom master page to eliminate needless content in the output response
  • a web page to simulate webservice endpoint
  • a web page to consume the service and show a typical use of it
Let's go!

Create Sandboxed webpart

It is not the focus of this article create a complex business logic or show the capability of Sharepoint Server-Side Object Model, but try to explain a different approach to consume Sharepoint data.

In the demo we are going to instantiate this simple object with some information about subsites:

public class Stats
{
    public List<Site> Sites { get; set; }
}

public class Site
{
    public string Title { get; set; }
    public int ListsCount { get; set; }
}

The operation is simple using Sharepoint Object Model server-side: we do a for...each iteration to get the title and the number of lists in the site; the same operation in a client-side script could be more complex because of asynchronous calls. For any details on these steps, I suggest to see the source code in attachment (WSWebpart feature)

After we fill the properties of the object, we have to serialize it and create the JSON string to send back to client. There are many way to obtain this, the most simple is to use JavaScriptSerializer, included in .NET Framework 3.5 (in System.Web.Extensions.dll assembly)

Stats stats = new Stats();

...

JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(stats);

Custom Masterpage

The master page must be very simple in order to return only the raw result in JSON format. So we can create a master page with an only placeholder:

<%@ Master language="C#" %>
<asp:ContentPlaceHolder id="PlaceHolderMain" runat="server">
</asp:ContentPlaceHolder>

In this way we have removed all unuseful information such as Javascript, CSS and other contents, obtaining a clean page.

Simple Service Page

Now we can add the custom sandbox webpart with the implementation of service in a new page, forcing to use the our master page. To achieve this, we can use a new control included in Sharepoint 2010 framework: SPUserCodeWebPart. The page on MSDN doesn't contain any example, however the required properties to reference univocally the webpart are :

  • AssemblyFullName: The full name of the user code Web Part assembly (e.g. WebServiceSandbox, Version=1.0.0.0, Culture=neutral, PublicKeyToken=bf13a1a9ef2c3dc4)
  • SolutionId: The ID of the solution
  • TypeFullName: The full name of the sandboxed solution Web Part type
To simplify the process we can use the replaceable parameters included in Visual Studio 2010 solutions. In particular we have $SharePoint.Project.AssemblyFullName$ for the AssemblyFullName and $SharePoint.Package.Id$ for the SolutionId. Instead for the TypeFullName there isn't any specific variable, but as suggested in this detailed MSDN article and in below comments, we can use the generic parameters $SharePoint.Type.<GUID>.FullName$ replacing <GUID> with that added in WebPart declaration. In the sample the code is:
<WebPartPages:SPUserCodeWebPart 
   runat="server" 
   Description="ServiceWP" 
   Title="ServiceWP" 
   AssemblyFullName="$SharePoint.Project.AssemblyFullName$" 
   SolutionId="$SharePoint.Package.Id$" 
   ID="servicewp" 
   TypeFullName="$SharePoint.Type.a2548058-31d8-4364-8043-1ea3a1eb21e1.FullName$" >
</WebPartPages:SPUserCodeWebPart>

Moreover in the declaration of the page we must change the URL of MasterPage in order to reference the custom one.

<%@ Page language="C#" MasterPageFile="~site/_catalogs/masterpage/WSMasterPage.master" ... %>

The ~site parameter is required if the site collection isn't the root of the Web Application (e.g. http://dev/sites/wstest).

After we have created the page, we have to create a feature to deploy this in Sharepoint Document Library. This can be achieved using a module as this (in the solution it is in WSServicePage folder)
<Module Name="WSServicePage">
   <File Path="WSServicePage\WSServicePage.aspx" Url="Documents/WSServicePage.aspx" />
</Module>

Consume webservice with jQuery

The last step is create a page consuming the service; it is quite simple, there is a button that calls our custom webservice and display the well-formed result in a div panel (with id #list)

In order to make easy the development, we use AJAX functionalities of jQuery framework and we can insert the script in a the OOTB Sharepoint Content Editor Webpart or add it directly in the source code of the page.

$(function () {
   $.getJSON("/Documents/WSServicePage.aspx", function(data) {
      $.each(data.Sites, function(i,s) {
        var txt = 'Site ' + s.Title + ' has ' + s.ListsCount + ' lists' ;
        $('<li>').text(txt).appendTo($('#list'));
      });
  });
});

Conclusion

In this article we have analyzed a way to overcome a Office 365 limitation: sandbox solutions can be difficult to use at times because of all the limitations, however there are many new techniques that allows developers to handle these issues exploring new approaches and solutions.

This approach doesn't want to replace other valid and totally supported solutions such as Javascript Client Object Model (JSOM), SPServices or simple calls Sharepoint REST services, instead it just aims to suggest a way to reuse source code developed with server-side object model or simply for users that haven't good practice with Javascript. Moreover I find this approach very useful when we need nested queries using Sharepoint context that require many asynchronous calls using JSOM script.

About the sources

In the solution there are 4 features:
  1. WSWebpart with the webpart with the logic of service
  2. WSMasterPage with the simple masterpage
  3. WSService with the page containing Webpart
  4. WSConsumer with the page that calls the "service"
Solution.png

History

  • 10th February, 2012: Initial version
  • 14th February, 2012: Updated source code

License

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

About the Author

Giorgio Lasala

Software Developer
Infoservice
Italy Italy

Member

Giorgio Lasala is a Software Developer.
He is experienced with designing and developing web and desktop application based on the most recent Microsoft technologies.
He is MCPD Sharepoint Developer 2010

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralGood solution PinmemberMatt Cowan14:42 3 Apr '12  
GeneralRe: Good solution PinmemberGiorgio Lasala0:20 4 Apr '12  

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

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120517.1 | Last Updated 14 Feb 2012
Article Copyright 2012 by Giorgio Lasala
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid