Pieter van der Westhuizen

Office 365 – SharePoint Online building blocks

Our blog is buzzing with news and updates about Office 365 and I hope you’re following us on Twitter to get up to the minute updates. One of the biggest components of Office 365 is SharePoint Online and from a developer’s point of view it is also one of the most customizable.

We’ve already taken a high level look at what is in SharePoint in my Office 365 from a developer point of view post and in today’s post we’ll have a more in-depth look at the building blocks for SharePoint that are available to developers.

Let’s get started by firing up Visual Studio and starting a new Empty SharePoint Project.

Creating a new SharePoint project in Visual Studio 2010

All SharePoint solutions deployed on Office 365 need to be deployed as sandboxed solutions, so select Deploy as a sandboxed solution when prompted.

Deploying as a sandboxed solution

Content Types

Content types allow you to manage the metadata and behaviours of a document or item type in a reusable way. Content types include the fields and other settings such as custom edit, new and view forms as well as the document template.

Think of a content type as a base class where you declare a number of fields. Any other class that inherits from that class will have the base class fields. You can also add your own.

Create a new content type by adding a new Content Type item to your Visual Studio 2010 project.

Creating a new content type

When prompted, select Item as the base content type.

When prompted, select Item as the base content type.

Next, open the Elements.xml file under the OurCustomersContentType folder and change its mark-up to the following:

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Field SourceID="http://schemas.microsoft.com/sharepoint/v3"
		ID="{70C78B73-9FA3-4DE3-8AF9-1FC811FC2B18}"	Name="CustomerNote"
		DisplayName="Customer Note"	Group="Our Custom Columns" Type="Text"
		DisplaceOnUpgrade="TRUE" />
  <Field SourceID="http://schemas.microsoft.com/sharepoint/v3"
		ID="{36D30B46-37F9-42A0-87E0-125946E12A9B}"	Name="CustomerActive"
		DisplayName="Is Customer Active" Group="Our Custom Columns" Type="Boolean" 
		DisplaceOnUpgrade="TRUE" />
 
  <!-- Parent ContentType: Item (0x01) -->
  <ContentType ID="0x0100a527a5115a1f4c04a113c82bf6e3fa47"
				Name="OurCustomer"
				Group="Custom Content Types"
				Description="Our Content Type"
				Inherits="TRUE"
				Version="0">
    <FieldRefs>
      <FieldRef ID="{70C78B73-9FA3-4DE3-8AF9-1FC811FC2B18}" Name="CustomerNote" />
      <FieldRef ID="{36D30B46-37F9-42A0-87E0-125946E12A9B}" Name="CustomerActive" />
    </FieldRefs>
  </ContentType>
</Elements>

Lists

Next, we need to create a list definition and base it on the Our Customer content type we’ve just created.

SharePoint lists are similar to database tables as it also supports various data types for fields and can have triggers that respond to events like creating, updating or deleting items from the list. Lists can also be sorted, grouped or filtered based on data in the list.

There are 3 ways to create a SharePoint list: (a) via the SharePoint web interface, (b) SharePoint Designer and (c) with Visual Studio. I recommend creating the list using SharePoint Designer as it has a very nice visual designer that makes this a trivial task. However, I’ll show you how you can create a List Definition using Visual Studio too.

Add a new List Definition from content type item to your project.

Adding a new List Definition

When prompted type the display name of the list and select the Our Customer content type, we’ve created earlier, as the list definition type. Keep the Add a list instance for this list definition check box ticked.

Typing the display name of the list and selecting Our Customer content type

Open the Element.xml file under the OurCustomerList folder and change its mark-up to:

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
    <!-- Do not change the value of the Name attribute below. 
    If it does not match the folder name of the List Definition project item, 
    an error will occur when the project is run. -->
    <ListTemplate
        Name="OurCustomerList"
        Type="10001"
        BaseType="0"
        OnQuickLaunch="TRUE"
        SecurityBits="11"
        Sequence="410"
        DisplayName="Our Customers"
        Description="My List Definition"
        Image="/_layouts/images/itgen.png"/>
</Elements>

We’ve only change the Type attribute; it must be a value larger than 10,000 and it must be unique within the feature.

Next, open the Schema.xml file and change its mark-up to:

<?xml version="1.0" encoding="utf-8"?>
<List xmlns:ows="Microsoft SharePoint" Title="Our Customers" FolderCreation="FALSE"
	Direction="$Resources:Direction;" Url="Lists/SPBuildingBlocks-OurCustomerList"
	BaseType="0" xmlns="http://schemas.microsoft.com/sharepoint/">
  <MetaData>
    <ContentTypes>
      <ContentType ID="0x0100a527a5115a1f4c04a113c82bf6e3fa47" Name="OurCustomer"
		Group="Custom Content Types" Description="Our Content Type" Inherits="TRUE"
		Version="0">
        <FieldRefs>  
          <FieldRef ID="{70C78B73-9FA3-4DE3-8AF9-1FC811FC2B18}" Name="CustomerNote" />
          <FieldRef ID="{36D30B46-37F9-42A0-87E0-125946E12A9B}" Name="CustomerActive" />
        </FieldRefs>
      </ContentType>
    </ContentTypes>
    <Fields>
      <Field SourceID="http://schemas.microsoft.com/sharepoint/v3"
		ID="{70c78b73-9fa3-4de3-8af9-1fc811fc2b18}" Name="CustomerNote"
		DisplayName="Customer Note" Group="Our Custom Columns" Type="Text"
		DisplaceOnUpgrade="TRUE" />
    </Fields>
    <Views>
      <View BaseViewID="0" Type="HTML" MobileView="TRUE" TabularView="FALSE">
        <Toolbar Type="Standard" />
        <XslLink Default="TRUE">main.xsl</XslLink>
        <RowLimit Paged="TRUE">30</RowLimit>
        <ViewFields>
          <FieldRef ID="{70C78B73-9FA3-4DE3-8AF9-1FC811FC2B18}" Name="CustomerNote"
			DisplayName="Customer Note" />
          <FieldRef ID="{36D30B46-37F9-42A0-87E0-125946E12A9B}" Name="CustomerActive"
			DisplayName="Is Customer Active" />
          <FieldRef Name="LinkTitleNoMenu">
          </FieldRef>
        </ViewFields>
        <Query>
          <OrderBy>
            <FieldRef Name="Modified" Ascending="FALSE">
            </FieldRef>
          </OrderBy>
        </Query>
        <ParameterBindings>
          <ParameterBinding Name="AddNewAnnouncement"
			Location="Resource(wss,addnewitem)" />
          <ParameterBinding Name="NoAnnouncements"
			Location="Resource(wss,noXinviewofY_LIST)" />
          <ParameterBinding Name="NoAnnouncementsHowTo"
			Location="Resource(wss,noXinviewofY_ONET_HOME)" />
        </ParameterBindings>
      </View>
      <View BaseViewID="1" Type="HTML" WebPartZoneID="Main"
		DisplayName="$Resources:core,objectiv_schema_mwsidcamlidC24;"
		DefaultView="TRUE" MobileView="TRUE" MobileDefaultView="TRUE"
		SetupPath="pages\viewpage.aspx"
		ImageUrl="/_layouts/images/generic.png" Url="AllItems.aspx">
        <Toolbar Type="Standard" />
        <XslLink Default="TRUE">main.xsl</XslLink>
        <RowLimit Paged="TRUE">30</RowLimit>
        <ViewFields>
          <FieldRef Name="Attachments"/>
          <FieldRef Name="LinkTitle"/>
          <FieldRef ID="{70C78B73-9FA3-4DE3-8AF9-1FC811FC2B18}" Name="CustomerNote"
			DisplayName="Customer Note" />
          <FieldRef ID="{36D30B46-37F9-42A0-87E0-125946E12A9B}" Name="CustomerActive"
			DisplayName="Is Customer Active" />
        </ViewFields>
        <Query>
          <OrderBy>
            <FieldRef Name="ID">
            </FieldRef>
          </OrderBy>
        </Query>
        <ParameterBindings>
          <ParameterBinding Name="NoAnnouncements"
			Location="Resource(wss,noXinviewofY_LIST)" />
          <ParameterBinding Name="NoAnnouncementsHowTo"
			Location="Resource(wss,noXinviewofY_DEFAULT)" />
        </ParameterBindings>
      </View>
    </Views>
    <Forms>
      <Form Type="DisplayForm" Url="DispForm.aspx" SetupPath="pages\form.aspx"
		WebPartZoneID="Main" />
      <Form Type="EditForm" Url="EditForm.aspx" SetupPath="pages\form.aspx"
		WebPartZoneID="Main" />
      <Form Type="NewForm" Url="NewForm.aspx" SetupPath="pages\form.aspx"
		WebPartZoneID="Main" />
    </Forms>
  </MetaData>
</List>

All we’ve done is adding the field definitions to the Views section of the file. Rename the ListInstance1 under OurCustomerList to OurCustomers and open Elements.xml under OurCustomers and change its mark-up to:

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <ListInstance Title="OurCustomers"
                OnQuickLaunch="TRUE"
                TemplateType="10001"
                Url="Lists/OurCustomers"
                Description="Our List Instance">
  </ListInstance>
</Elements>

Build and deploy your project and you should see the list and its data in SharePoint.

The list and its data in SharePoint

Web parts

Web parts are probably the most used artefact and one of the core building blocks in SharePoint development. It can be customized to do a large array of different things. Web parts act as containers for any custom functionality (built using ASP.Net) as well as containers for a list or document library.

To create a web part, add a new Web Part item to your SharePoint project.

Adding a new Web Part item to your SharePoint project

Once the web part is added to your project, the Solution Explorer will look similar to the following image:

Solution Explorer

Open the SimpleCalculatorWebPart.cs file and add the following code:

[ToolboxItemAttribute(false)]
public class SimpleCalculatorWebPart : WebPart
{
	Label lblFirstNumber = new Label();
	Label lblSecondNumber = new Label();
	Label lblTotal = new Label();
	TextBox txtFirstNumber = new TextBox();
	TextBox txtSecondNumber = new TextBox();
	Button btnAdd = new Button();
 
	protected override void CreateChildControls()
	{
		lblFirstNumber.Text = "Enter first number:";
		lblSecondNumber.Text = "Enter second number:";
		btnAdd.Text = "Add Numbers";
		btnAdd.Click += btnAdd_Click;
 
		this.Controls.Add(lblFirstNumber);
		this.Controls.Add(txtFirstNumber);
		this.Controls.Add(new LiteralControl("<br />"));
		this.Controls.Add(lblSecondNumber);
		this.Controls.Add(txtSecondNumber);
		this.Controls.Add(new LiteralControl("<br />"));
		this.Controls.Add(lblTotal);
		this.Controls.Add(new LiteralControl("<br />"));
		this.Controls.Add(btnAdd);            
 
		base.CreateChildControls();
	}
 
	void btnAdd_Click(object sender, EventArgs e)
	{
		double total = Convert.ToDouble(txtFirstNumber.Text) +
			Convert.ToDouble(txtSecondNumber.Text);
		lblTotal.Text = "The total is: " + total;
	}
}

This code declaratively adds controls to the web part. To add the web part to a SharePoint page, click on the Edit Page button on the Page tab and click on the Add a Web Part link in the page.

SharePoint will display a list of web parts, click on the Custom folder and select your web part from the list.

Selecting your web part from the list

After you’ve added the web part to the page, click the Stop Editing button to return to the normal page view which should look like follows:

The custom web part added to a SharePoint page

Visual web parts (Sandboxed)

Visual web parts are similar to web part except that instead of having to declaratively add controls to the page you can add it by using a visual designer. To add a visual web part, add a new Visual Web Part (Sandboxed) to your project.

Adding a new Visual Web Part (Sandboxed) to your project

If you don’t see the Visual Web Part (Sandboxed) item template make sure you have the Visual Studio 2010 SharePoint Power Tools installed.

After the item is added to your project, you can open the CustomerVisualWebPart.ascx. Click on the Design button at the bottom of the screen and you will be presented with a visual designer similar to that of ASP.Net. Design your form and add the necessary logic as you would in any ASP.Net application. My web parts’ design looks like this:

Design your form

Add the following code to the buttons’ click event:

protected void btnShow_Click(object sender, EventArgs e)
{
	SPWeb web = SPContext.Current.Web;
	SPList list = web.Lists.TryGetList("OurCustomers");
 
	var cust = (from Microsoft.SharePoint.SPListItem item in list.Items
            where item.Title == txtName.Text
            select item).FirstOrDefault();
	if (cust != null)
		txtNote.Text = cust["CustomerNote"].ToString();
}

The code will retrieve the customer list we’ve created earlier and find the customer whose name the user entered and display their note in the note textbox. After deploying and adding the web part to a SharePoint page, the result should look like the following image:

The web part added to a SharePoint page

Event receivers

Think of event receivers as something similar to triggers in SQL server. They are triggered when either the user or system updates, adds or deletes items from a list or library. Event receivers can be created for a number of SharePoint objects e.g. lists, list items, sites etc. Add a new Event Receiver item to your project.

Adding a new Event Receiver item to your project.

Visual Studio will connect to your SharePoint site and prompt you to choose which type of event receiver you want. Select List Item Events and select the Our Customers list we’ve created earlier from the event source dropdown list.

You’ll notice that there is a multiple selection of events you can subscribe to, for this example only choose An item is being updated.

Choosing Event Receiver settings

Open the MyEventReceiver.cs file. You’ll notice that Visual studio has added an ItemUpdating method to the file. You’ll use this method to respond to the Our Customers list’s update event. Add the following code to the method:

public override void ItemUpdating(SPItemEventProperties properties)
{
	SPListItem listItem = properties.ListItem;
	if (listItem["Title"].ToString().ToLower().Contains("jim"))
	{
		properties.Cancel = true;
		properties.Status = SPEventReceiverStatus.CancelNoError;
	}           
}

The code is pretty simple. It checks whether the Title property contains the value "jim" and if it does, the update is cancelled. By setting the Status property to CancelNoError, no error message is displayed to the user.

As you can see, SharePoint has a very large and rich eco-system for developers and what I’ve shown you here are barely scratching the surface. So many things can be done with just SharePoint web parts that entire books are dedicated to just the one topic. Fortunately, you do not need to feel overwhelmed by the amount of new things you need to learn about SharePoint as there are a vast amount of resources available on the internet and a fantastic collection of brilliant books. Just some sites I can recommend are:

Thank you for reading. Until next time, Merry Christmas everyone!

Available downloads:

C# sample project

You may also be interested in:

Post a comment

Have any questions? Ask us right now!