Provisioning Content Types in SharePoint 2010

Overview

Provisioning in SharePoint has always been not the simplest part, especially if it concerns the Content Type provision.

It is known that in SharePoint 2010, you can declare content types in a feature or you can create them programmatically. Programmatically created content types are more flexible and provide more granular control over how and when updates to the content type are made during upgrades. In contrast, you cannot change the declarative definition of a content type that was created by using Collaborative Application Markup Language (CAML) after the content type is activated—instead, you must update the content type programmatically.

Given the Pros and Cons, it is up to you to decide which way is better suits your needs.

How to create a field based on the specified schema

There is one method that allows to create a field based on the specified schema, see AddFieldAsXml method for details . It means that you could declare a field once (CAML), but to provision it either via feature activation or programmatically. As for me, I find this technique very useful for curtain cases. But what about content types?

For content type there is no such capability that allows to create a content type based on the specified schema. And the goal of this post is to demonstrate how it could be achieved.

How to create a content type based on the specified schema

Listing 1.  AddContentTypeAsXml method implementation for creating a content type based on the specified schema

namespace Deployment.ContentType
{
/// <summary>
/// Content Type
/// </summary>
public static class SPContentTypeExtensions
{
/// <summary>
/// Creates a content type based on the specified schema.
/// </summary>
/// <returns>
/// An instance of the new content type.
/// </returns>
/// <param name="contentTypes">Content Type collection</param>
/// <param name="schemaXml">A Collaborative Application Markup Language (CAML) string that contains the schema.</param>
public static SPContentType AddContentTypeAsXml(this SPContentTypeCollection contentTypes, string schemaXml)
{
SPContentType contentType;
using (var xrdr = new XmlTextReader(new StringReader(schemaXml)))
{
xrdr.ProhibitDtd = true;
contentType = contentTypes.CreateContentType();
LoadXmlInternal(contentType, xrdr);
contentTypes.Add(contentType);
}
return contentType;
}
/// <summary>
/// Create content type
/// </summary>
/// <param name="contentTypes"></param>
/// <returns></returns>
private static SPContentType CreateContentType(this SPContentTypeCollection contentTypes)
{
var constructor = (typeof(SPContentType)).GetConstructor(
BindingFlags.NonPublic | BindingFlags.Instance,
null,
Type.EmptyTypes,
null);
var contentType = (SPContentType)constructor.Invoke(new object[0]);
contentType.SetWeb(contentTypes.GetWeb());
return contentType;
}
/// <summary>
/// Load schema for content type
/// </summary>
/// <param name="contentType"></param>
/// <param name="xmlReader"></param>
private static void LoadXmlInternal(SPContentType contentType, XmlReader xmlReader)
{
var loadMethod = contentType.GetType().GetMethod("Load",
BindingFlags.NonPublic | BindingFlags.Instance,
null,
new[] { typeof(XmlReader) },
null);
loadMethod.Invoke(contentType, new object[] { xmlReader });
}
private static SPWeb GetWeb(this SPContentTypeCollection contentTypes)
{
var webProp = typeof(SPContentTypeCollection).GetProperty("Web", BindingFlags.NonPublic | BindingFlags.Instance);
return (SPWeb)webProp.GetValue(contentTypes, null);
}
private static void SetWeb(this SPContentType contentType,SPWeb web)
{
var webProp = typeof(SPContentType).GetProperty("Web", BindingFlags.NonPublic | BindingFlags.Instance);
webProp.SetValue(contentType, web, null);
}
}
}

Listing 2.  AddContentTypeAsXml method implementation for creating a content type based on the specified schema via Managed Client Object Model

namespace Deployment.Client
{
/// <summary>
/// Creates a content type based on the specified schema (CSOM)
/// </summary>
public static class ContentTypeExtensions
{
/// <summary>
/// Creates a content type based on the specified schema.
/// </summary>
/// <returns>
/// A newly created client object of a content type.
/// </returns>
/// <param name="clientContext">Client Context </param>
/// <param name="schemaXml">A Collaborative Application Markup Language (CAML) string that contains the schema.</param>
public static ContentType AddContentTypeAsXml(ClientContext clientContext, string schemaXml)
{
ContentType contentType;
using (var xmlTextReader = new XmlTextReader(new StringReader(schemaXml)))
{
xmlTextReader.ProhibitDtd = true;
contentType = Load(clientContext, clientContext.Web.ContentTypes, xmlTextReader);
}
return contentType;
}
private static ContentType Load(ClientContext clientContext, ContentTypeCollection cts, XmlReader xrdr)
{
var contentTypeCreation = new ContentTypeCreationInformation { };
xrdr.MoveToContent();
if (xrdr.MoveToAttribute("Name"))
contentTypeCreation.Name = xrdr.Value;
if (xrdr.MoveToAttribute("Group"))
contentTypeCreation.Group = xrdr.Value;
if (xrdr.MoveToAttribute("Description"))
contentTypeCreation.Description = xrdr.Value;
contentTypeCreation.ParentContentType = GetParentContentType(clientContext, xrdr.GetAttribute("ID"));
var contentType = cts.Add(contentTypeCreation);
//Additional properties
if (xrdr.MoveToAttribute("Hidden"))
contentType.Hidden = xrdr.Value == "TRUE";
bool flagReadOnly = xrdr.MoveToAttribute("ReadOnly");
contentType.ReadOnly = flagReadOnly && xrdr.Value == "TRUE";
xrdr.Read();
while (xrdr.LocalName != "ContentType")
{
switch (xrdr.LocalName)
{
case "FieldRefs":
LoadFieldLinks(clientContext, contentType, xrdr);
break;
}
if (!xrdr.Read())
break;
}
return contentType;
}
private static void LoadFieldLinks(ClientContext clientContext, ContentType contentType, XmlReader xrdr)
{
xrdr.Read();
while (xrdr.LocalName == "FieldRef" || xrdr.LocalName == "RemoveFieldRef")
{
if (xrdr.LocalName == "RemoveFieldRef")
{
xrdr.Read();
}
else
{
LoadFieldLink(clientContext, contentType.FieldLinks, xrdr);
contentType.Update(false);
clientContext.ExecuteQuery();
}
}
}
internal static FieldLink LoadFieldLink(ClientContext clientContext, FieldLinkCollection fieldLinks, XmlReader xrdr)
{
var linkCreationInfo = new FieldLinkCreationInformation();
var hostField = GetField(clientContext, xrdr);
linkCreationInfo.Field = hostField;
var fieldLink = fieldLinks.Add(linkCreationInfo);
xrdr.MoveToContent();
if (xrdr.MoveToAttribute("Required"))
{
fieldLink.Required = xrdr.Value == "TRUE" || xrdr.Value == "-1";
}
if (xrdr.MoveToAttribute("Hidden"))
{
fieldLink.Hidden = xrdr.Value == "TRUE" || xrdr.Value == "-1";
}
xrdr.Read();
if (xrdr.LocalName == "Default")
{
xrdr.Read();
}
return fieldLink;
}
/// <summary>
///
/// </summary>
/// <param name="clientContext"></param>
/// <param name="xrdr"></param>
/// <returns></returns>
private static Field GetField(ClientContext clientContext, XmlReader xrdr)
{
var field = clientContext.Web.AvailableFields.GetById(new Guid(xrdr["ID"]));
clientContext.Load(field);
clientContext.ExecuteQuery();
return field;
}
private static ContentType GetParentContentType(ClientContext clientContext, string id)
{
var ctId = new SPContentTypeId(id);
var parentCtId = ctId.Parent.ToString();
return GetContentTypeById(clientContext, parentCtId);
}
public static ContentType GetContentTypeById(ClientContext clientContext, string ctId)
{
var ct = clientContext.Web.AvailableContentTypes.GetById(ctId);
clientContext.Load(ct);
clientContext.ExecuteQuery();
return ct;
}
public static ContentType GetContentTypeByName(ClientContext clientContext, string name)
{
var cts = clientContext.Web.ContentTypes;
clientContext.Load(cts);
clientContext.ExecuteQuery();
foreach (var ct in cts)
{
if (ct.Name == name)
return ct;
}
return null;
}
}
}

The following list summarizes the limitations for Client OM approach:

  • Not the all content type attributes could be specified via Client OM
  • In particular it is not supported to specify Content Type Id, only parent Content Type could be specified

References

Bringing Map functionality into SharePoint 2010: Rendering Map List View

Overview

SharePoint 2013 introduces functionality to integrate location information and maps in SharePoint lists and location-based web and mobile apps for SharePoint with the following capabilities:

  • new field type named Geolocation that enables you to annotate SharePoint lists with location information. The built-in Geolocation field can render only with Bing Maps. However, you can create a custom field by using the Geolocation field as a parent field type, for example see my blog post about using Google Maps as map service.
  • Map View that displays a map (with data obtained from the Bing Maps service), using longitude and latitude entries from the Geolocation field type

Client-side rendering for Map List View in SharePoint 2013

Regarding Map View, SharePoint 2013 utilizes client side rendering framework for List View that allows to define the rendering logic of SharePoint list views using HTML/JavaScript. There is already predefined rendering template in SharePoint 2013  for Binq Maps service that is used when Map View is created, for more details see Create a map view for the Geolocation field in SharePoint 2013.

Map List View in SharePoint 2010

But what about SharePoint 2010? Let’s discuss one approach related with customizing List View for  XSLTListViewWebPart (XLV) . So, in proposed solution  geographical locations are stored in Custom List and custom View is used to render data on Map using Google Maps service For example, list items GeoMapDefaultView

will be represented in Map View as shown below

GeoMapView

Implementation of Map List View in SharePoint 2010

As was noted earlier for storing geographical location on a map and visualizing it in Map View we will define Custom List named GeoMap List.

GeoMap Content Type

For storing geographical locations we define the following Content Type

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<!– Parent ContentType: Item (0x01) –>
<ContentType ID="0x010087e1abb3659f42f6ad024894ec514f93"
Name="GeoMap"
Group="GeoMap"
Description="GeoMap Content Type"
Inherits="TRUE"
Version="0">
<FieldRefs>
<FieldRef ID="{F3252F03-F69E-40fb-91F7-8BD364D0882B}" Name="MapAddress1"/>
<FieldRef ID="{FBCDD54F-21AA-4eab-A376-4BC531FF264F}" Name="MapAddress2"/>
<FieldRef ID="{638D5C28-6DFC-4642-AC7C-5377E478F5CC}" Name="MapCity"/>
<FieldRef ID="{1966B506-0642-4b00-8B56-5B872C725B6A}" Name="MapState"/>
<FieldRef ID="{594036C6-29C6-4c71-A271-6721C171E675}" Name="MapZip"/>
<FieldRef ID="{6A85673B-2EE1-483d-AD5D-57161DFE8237}" Name="MapCountry"/>
<FieldRef ID="{EBFA40F7-A21A-4f4c-B941-036F5A360E0C}" Name="MapLatitude"/>
<FieldRef ID="{ADDBDAC0-123C-46d5-9BA0-0D7EA29E5711}" Name="MapLongitude"/>
<FieldRef ID="{CDF90965-628A-4cf0-91E3-D6F3DBE233CC}" Name="MapAdditionalInfo"/>
</FieldRefs>
</ContentType>
<Field Type="Text" DisplayName="Address1" Required="FALSE" ID="{F3252F03-F69E-40fb-91F7-8BD364D0882B}" SourceID="http://schemas.microsoft.com/sharepoint/v3" StaticName="MapAddress1" Name="MapAddress1" Group="GeoMap" />
<Field Type="Text" DisplayName="Address2" Required="FALSE" ID="{FBCDD54F-21AA-4eab-A376-4BC531FF264F}" SourceID="http://schemas.microsoft.com/sharepoint/v3" StaticName="MapAddress2" Name="MapAddress2" Group="GeoMap" />
<Field Type="Text" DisplayName="City" Required="FALSE" ID="{638D5C28-6DFC-4642-AC7C-5377E478F5CC}" SourceID="http://schemas.microsoft.com/sharepoint/v3" StaticName="MapCity" Name="MapCity" Group="GeoMap" />
<Field Type="Text" DisplayName="State" Required="FALSE" ID="{1966B506-0642-4b00-8B56-5B872C725B6A}" SourceID="http://schemas.microsoft.com/sharepoint/v3" StaticName="MapState" Name="MapState" Group="GeoMap" />
<Field Type="Text" DisplayName="Zip" Required="FALSE" ID="{594036C6-29C6-4c71-A271-6721C171E675}" SourceID="http://schemas.microsoft.com/sharepoint/v3" StaticName="MapZip" Name="MapZip" Group="GeoMap" />
<Field Type="Text" DisplayName="Country" Required="FALSE" ID="{6A85673B-2EE1-483d-AD5D-57161DFE8237}" SourceID="http://schemas.microsoft.com/sharepoint/v3" StaticName="MapCountry" Name="MapCountry" Group="GeoMap" />
<Field Type="Number" DisplayName="Latitude" Required="TRUE" ID="{EBFA40F7-A21A-4f4c-B941-036F5A360E0C}" SourceID="http://schemas.microsoft.com/sharepoint/v3" StaticName="MapLatitude" Name="MapLatitude" Group="GeoMap" />
<Field Type="Number" DisplayName="Longitude" Required="TRUE" ID="{ADDBDAC0-123C-46d5-9BA0-0D7EA29E5711}" SourceID="http://schemas.microsoft.com/sharepoint/v3" StaticName="MapLongitude" Name="MapLongitude" Group="GeoMap" />
<Field Type="Note" DisplayName="Additional Info" Required="FALSE" EnforceUniqueValues="FALSE" NumLines="6" RichText="FALSE" ID="{CDF90965-628A-4cf0-91E3-D6F3DBE233CC}" SourceID="http://schemas.microsoft.com/sharepoint/v3" StaticName="MapAdditionalInfo" Name="MapAdditionalInfo" Group="GeoMap" />
</Elements>

GeoMap List

GeoMap List is based on Generic List with GeoMap Content Type and with custom View

XSLT stylesheet for Map List View

<xsl:stylesheet xmlns:x="http://www.w3.org/2001/XMLSchema"
xmlns:d="http://schemas.microsoft.com/sharepoint/dsp"
version="1.0" exclude-result-prefixes="xsl msxsl ddwrt x d asp __designer SharePoint ddwrt2"
xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime"
xmlns:asp="http://schemas.microsoft.com/ASPNET/20"
xmlns:__designer="http://schemas.microsoft.com/WebParts/v2/DataView/designer"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
xmlns:SharePoint="Microsoft.SharePoint.WebControls"
xmlns:ddwrt2="urn:frontpage:internal">
<xsl:import href="/_layouts/xsl/main.xsl"/>
<xsl:output method="html" indent="no"/>
<xsl:template match="View[@BaseViewID='80']" mode="full" ddwrt:ghost="always">
<tr class="ms-viewheadertr"></tr>
<tr>
<td>
<div id="map_canvas" style="width:100%; height:480px"></div>
</td>
</tr>
<xsl:apply-templates mode="footer" select="." />
</xsl:template>
<xsl:template name="GeoMapViewOverride" mode="RootTemplate" match="View[List/@TemplateType=10488]" ddwrt:dvt_mode="root">
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&amp;sensor=false"></script>
<script src="/_layouts/spgeomap.js"></script>
<script type="text/javascript">
ExecuteOrDelayUntilScriptLoaded(initSPGeoMap, "sp.js");
</script>
<xsl:call-template name="View_Default_RootTemplate"/>
</xsl:template>
</xsl:stylesheet>

view raw
GeoMap.xsl
hosted with ❤ by GitHub

GeoMap rendering control

SP.GeoMapControl=function()
{
var _listId;
this.Init=function(listId)
{
_listId = listId;
loadMapData(function(entries){
if (entries==null)
{
alert('No Map data was found');
}
else
{
initMapControl(entries);
}
});
}
function initMapControl(mapEntries, params) {
var mapOptions = {
center: new google.maps.LatLng(34.397, 150.644),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),mapOptions);
var infowindow = new google.maps.InfoWindow();
var bounds = new google.maps.LatLngBounds;
var i,marker;
for (i = 0; i < mapEntries.length; i++) {
var mapEntry = mapEntries[i];
var pos = new google.maps.LatLng(mapEntry.lat,mapEntry.lng);
marker = new google.maps.Marker({
map: map,
position: pos
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(mapEntries[i].content);
infowindow.open(map, marker);
}
})(marker, i));
bounds.extend(pos);
}
map.fitBounds(bounds);
}
function loadMapData(fnCallback) {
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var listMap = web.get_lists().getById(_listId);
var viewXml = '<View><RowLimit>1200</RowLimit></View>';
var query = new SP.CamlQuery();
query.set_viewXml(viewXml);
var mapItems = listMap.getItems(query);
context.load(mapItems);
context.add_requestSucceeded(onMapLoaded);
context.add_requestFailed(onMapFailure);
context.executeQueryAsync();
function onMapLoaded() {
var mapsEntries=[];
var count=mapItems.get_count();
for (i=0 ; i < count; i++)
{
var mapItem=mapItems.itemAt(i);
var dataValues=mapItem.get_fieldValues();
var mapContent = '';
if(dataValues['MapAdditionalInfo'] != null)
mapContent = dataValues['MapAdditionalInfo'];
mapsEntries.push({ mapId: dataValues['ID'], title: dataValues['Title'], lat: dataValues['MapLatitude'], lng: dataValues['MapLongitude'],content: mapContent});
}
fnCallback(mapsEntries);
}
function onMapFailure() {
fnCallback(null);
}
}
};
function initSPGeoMap() {
var mapCtl = new SP.GeoMapControl();
mapCtl.Init(ctx.listName);
}

view raw
SPGeoMap.js
hosted with ❤ by GitHub

References

  • Google Maps JavaScript API v3
  • How to: Customize the Rendering of a Field on a List View in SharePoint 2010 on MSDN
  • How to: Customize a list view in apps for SharePoint using client-side rendering on MSDN

Customize the rendering of a List View in Sharepoint 2010: Displaying List Items in Accordion

Overview

The creation of non standard presentations for Lists/Libraries  is a fairly common  scenario and using the XSLT List View Web Part (XLV) possibilities that can be achieved pretty easily.
Let’s take a look how to render list of question and answers using Accordion Menu in SharePoint. Actually the idea for this post appeared after posting  of corresponding question on StackOverflow.
So, let’s discuss how it could be accomplished using XLV. For Accordion we will utilize jQuery UI library.

Accordion

Implementation

FAQ Custom List

First of all, let us define where  the questions and answers (FAQ) we’ll be stored. For this we will use Custom List with Content Type.

<ContentType ID="0x0100fb1027dc96a44bf280f6cb823a8da5ae"
Name="FAQ"
Group="SE"
Description="FAQ Content Type"
Inherits="TRUE"
Version="0">
<FieldRefs>
<FieldRef Name="LinkTitle" ID="{82642ec8-ef9b-478f-acf9-31f7d45fbc31}" DisplayName="Question" Sealed="TRUE"/>
<FieldRef Name="LinkTitleNoMenu" ID="{bc91a437-52e7-49e1-8c4e-4698904b2b6d}" DisplayName="Question" Sealed="TRUE"/>
<FieldRef Name="Title" ID="{fa564e0f-0c70-4ab9-b863-0177e6ddd247}" DisplayName="Question" Sealed="TRUE"/>
<FieldRef ID="{b0747420-54bc-41b2-a1b3-8432f2dbdc70}" Name="Answer"/>
</FieldRefs>
</ContentType>

view raw
FAQContentType.xml
hosted with ❤ by GitHub

Custom View for arranging items using jQuery UI Accordion

After creating Custom List we add new View for displaying Accordion for FAQ items

<View BaseViewID="10" Type="HTML" WebPartZoneID="Main" DisplayName="Accordion" DefaultView="FALSE" SetupPath="pages\viewpage.aspx" ImageUrl="/_layouts/images/generic.png" Url="Accordion.aspx">
<Toolbar Type="Standard" />
<XslLink Default="TRUE">FAQ.xsl</XslLink>
<RowLimit Paged="TRUE">30</RowLimit>
<ViewFields>
<FieldRef Name="Title" ID="{fa564e0f-0c70-4ab9-b863-0177e6ddd247}" DisplayName="Question" Sealed="TRUE"/>
<FieldRef Name="Answer" ID="{b0747420-54bc-41b2-a1b3-8432f2dbdc70}"></FieldRef>
</ViewFields>
<Query>
<OrderBy>
<FieldRef Name="ID"></FieldRef>
</OrderBy>
</Query>
<ParameterBindings/>
</View>

view raw
FAQAccordionView.xml
hosted with ❤ by GitHub

XSLT style sheet for rendering Accordion View

XSLT style sheet for FAQ List is intended for the following purposes:

  • loading jQuery Core and UI Libraries
  • rendering list items using layout as specified for Accordion menu
  • initializing and rendering Accordion for List items
<xsl:stylesheet xmlns:x="http://www.w3.org/2001/XMLSchema"
xmlns:d="http://schemas.microsoft.com/sharepoint/dsp"
version="1.0" exclude-result-prefixes="xsl msxsl ddwrt x d asp __designer SharePoint ddwrt2"
xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime"
xmlns:asp="http://schemas.microsoft.com/ASPNET/20"
xmlns:__designer="http://schemas.microsoft.com/WebParts/v2/DataView/designer"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
xmlns:SharePoint="Microsoft.SharePoint.WebControls"
xmlns:ddwrt2="urn:frontpage:internal">
<xsl:import href="/_layouts/xsl/main.xsl"/>
<xsl:output method="html" indent="no"/>
<xsl:template match="View[@BaseViewID='10']" mode="full" ddwrt:ghost="always">
<tr class="ms-viewheadertr"></tr>
<tr>
<td>
<div id="accordionFAQ">
<xsl:apply-templates select="." mode="RenderView" />
</div>
</td>
</tr>
<xsl:apply-templates mode="footer" select="." />
</xsl:template>
<xsl:template mode="Item" match="Row[../../@BaseViewID='10']" ddwrt:ghost="always">
<xsl:param name="Fields" select="."/>
<xsl:param name="Collapse" select="."/>
<xsl:param name="Position" select="1"/>
<xsl:param name="Last" select="1"/>
<xsl:variable name="thisNode" select="."/>
<h3>
<xsl:value-of select="$thisNode/@Title" />
</h3>
<div>
<xsl:value-of select="$thisNode/@Answer" disable-output-escaping="yes" />
</div>
</xsl:template>
<xsl:template name="FAQViewOverride" mode="RootTemplate" match="View[List/@TemplateType=11999]" ddwrt:dvt_mode="root">
<link rel="stylesheet" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/themes/redmond/jquery-ui.css" />
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.22/jquery-ui.js"></script>
<script>
$(function() {
$( "#accordionFAQ" ).accordion();
});
</script>
<xsl:call-template name="View_Default_RootTemplate"/>
</xsl:template>
</xsl:stylesheet>

view raw
FAQ.xsl
hosted with ❤ by GitHub

Using jQuery UI Accordion

jQuery Core and UI libraries are injected during XSLT style sheet processing. After JavaScript files which hosted on Microsoft CDN are loaded, jQuery UI Accordion is initialized for items.

<xsl:template name="FAQViewOverride" mode="RootTemplate" match="View[List/@TemplateType=11999]" ddwrt:dvt_mode="root">
<link rel="stylesheet" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/themes/redmond/jquery-ui.css" />
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.22/jquery-ui.js"></script>
<script>
$(function() {
$( "#accordionFAQ" ).accordion();
});
</script>
<xsl:call-template name="View_Default_RootTemplate"/>
</xsl:template>

view raw
FAQViewOverride.xsl
hosted with ❤ by GitHub

Results

FAQ List Accordion View rendered in XLV is shown below on picture

FAQ Accordion View

References

Embedding and Sharing Video in SharePoint. Part Two: Posting embedded code, support for different Video Providers, Preview view

Introduction

In previous post we have discussed  approach on how to embed video into SharePoint from YouTube. Custom List Video Links were used for storing embedded video properties and Computed Field for rendering Video player.
This time we will extend our solution with the following capabilities:

  • Support for different video providers listed in  oEmbed
  • Preview view for displaying video arranged in list
  • Alternative mode for posting the embed code for video into SharePoint

Support for different video providers

In addition to embed code using iframe, another options also available now. Some providers listed in oEmbed specification use object element for embedding code.

Table 1. Support for Video Providers listed in oEmbed specification

Provider Name Embedded Mode
YouTube IFrame, Object(YouTube)
Viddler
Qik Object(Qik)
Revision3 IFrame
Hulu IFrame
Vimeo IFrame
CollegeHumor Object(CollegeHumor)
Jest Object(Jest)
CircuitLab

Alternative mode for posting embedded code

Additionally to existing mode for embedding video code, the approach described below allows to paste the embed code as it was generated by Provider. Let’s take a look at the common usage scenario:

  • Generate and copy the embed code on the Provider website
  • Select Embed Code from New Item for Video Links List

  • In New Form for Video Links List paste the embed code and fill in comments if needed as shown below

For displaying video player the same (see previous post for details) Computed Field EmbeddedVideoOnForm field is used

Preview view for displaying video

In addition to default view (video player items with details), Preview view is intended to display items arranged by columns as shown below

Implementation

To paste the embed code we define Embed Code Content Type

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<!– Parent ContentType: Link (0x0105) –>
<ContentType ID="0x010503"
Name="Embed Code"
Group="$Resources:List_Content_Types"
Description="Embed Code Content Type"
Inherits="FALSE"
Version="0">
<FieldRefs>
<FieldRef ID="{c29e077d-f466-4d8e-8bbe-72b66c5f205c}" Name="URL" Required="FALSE" Hidden="TRUE"/>
<FieldRef ID="{9F79BBE2-19A3-4341-96F6-BFDC024DEAB3}" Name="EmbedCode" Required="TRUE" />
</FieldRefs>
</ContentType>
</Elements>

where field EmbedCode for storing the embed code  is used

<Field ID="{9F79BBE2-19A3-4341-96F6-BFDC024DEAB3}"
Name="EmbedCode"
SourceID="http://schemas.microsoft.com/sharepoint/v3"
StaticName="EmbedCode"
Group="Media Columns"
Type="Note"
DisplayName="Embed Code"
Hidden="FALSE"
Sortable="FALSE">
</Field>

view raw
EmbedCode Field.xml
hosted with ❤ by GitHub

As was noted earlier, for displaying video player the same (see previous post for details) Computed Field EmbeddedVideoOnForm field is used, below is presented complete XSLT style sheet for  rendering of a field on a List View

<xsl:stylesheet xmlns:x="http://www.w3.org/2001/XMLSchema"
xmlns:d="http://schemas.microsoft.com/sharepoint/dsp"
version="1.0" exclude-result-prefixes="xsl msxsl ddwrt"
xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime"
xmlns:asp="http://schemas.microsoft.com/ASPNET/20"
xmlns:__designer="http://schemas.microsoft.com/WebParts/v2/DataView/designer"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
xmlns:SharePoint="Microsoft.SharePoint.WebControls"
xmlns:ddwrt2="urn:frontpage:internal">
<xsl:template name ="RenderEmbeddedPlayer" match ="FieldRef[@Name='EmbeddedVideoOnForm']" mode="Computed_body" >
<xsl:param name="thisNode" select="."/>
<xsl:variable name="width">
<xsl:call-template name="ensureVideoPlayerSize">
<xsl:with-param name="videoSize" select="$thisNode/@VideoWidth"/>
<xsl:with-param name="defaultSize" select="560"/>
</xsl:call-template>
</xsl:variable>
<xsl:variable name="height">
<xsl:call-template name="ensureVideoPlayerSize">
<xsl:with-param name="videoSize" select="$thisNode/@VideoHeight"/>
<xsl:with-param name="defaultSize" select="315"/>
</xsl:call-template>
</xsl:variable>
<xsl:variable name="frameborder">
<xsl:value-of select="$thisNode/@FrameBorder"/>
</xsl:variable>
<xsl:variable name="src">
<xsl:value-of select="$thisNode/@URL"/>
</xsl:variable>
<xsl:choose>
<xsl:when test="$thisNode/@EmbeddingMode ='IFrame'">
<iframe width="{$width}" height="{$height}" src="{$src}" frameborder="{$frameborder}" allowfullscreen=""></iframe>
</xsl:when>
<xsl:when test="$thisNode/@EmbeddingMode ='Object(YouTube)'">
<object width="{$width}" height="{$height}">
<param name="movie" value="{$src}"></param>
<param name="allowFullScreen" value="true"></param>
<param name="allowscriptaccess" value="always"></param>
<embed src="{$src}" type="application/x-shockwave-flash" width="{$width}" height="{$height}" allowscriptaccess="always" allowfullscreen="true"></embed>
</object>
</xsl:when>
<xsl:when test="$thisNode/@EmbeddingMode ='Object(Qik)'">
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,115,0" width="{$width}" height="{$height}" align="middle">
<param name="allowScriptAccess" value="sameDomain" />
<param name="allowFullScreen" value="true" />
<param name="movie" value="{$src}" />
<param name="quality" value="high" />
<param name="bgcolor" value="#000000" />
<param name="FlashVars" value="streamID=9d0242b2912a444e84a31c2ca3249268&amp;autoplay=false" />
<embed src="{$src}" quality="high" bgcolor="#000000" width="{$width}" height="{$height}" name="qikPlayer" align="middle" allowScriptAccess="sameDomain" allowFullScreen="true" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" FlashVars="streamID=9d0242b2912a444e84a31c2ca3249268&amp;autoplay=false"></embed>
</object>
</xsl:when>
<xsl:when test="$thisNode/@EmbeddingMode ='Object(CollegeHumor)'">
<object type="application/x-shockwave-flash" data="{$src}" width="{$width}" height="{$height}">
<param name="allowfullscreen" value="true"/>
<param name="wmode" value="transparent"/>
<param name="allowScriptAccess" value="always"/>
<param name="movie" quality="best" value="{$src}"/>
<embed src="{$src}" type="application/x-shockwave-flash" wmode="transparent" width="{$width}" height="{$height}" allowScriptAccess="always"></embed>
</object>
</xsl:when>
<xsl:when test="$thisNode/@EmbeddingMode ='Object(Jest)'">
<object type="application/x-shockwave-flash" data="{$src}" width="{$width}" height="{$height}">
<param name="allowfullscreen" value="true"/>
<param name="wmode" value="transparent"/>
<param name="allowScriptAccess" value="always"/>
<param name="movie" quality="best" value="{$src}"/>
<embed src="{$src}" type="application/x-shockwave-flash" wmode="transparent" width="{$width}" height="{$height}" allowScriptAccess="always"></embed>
</object>
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="renderEmbeddedCodeAsHtml">
<xsl:with-param name="embedId" select="$thisNode/@ID" />
<xsl:with-param name="embeddedCode" select="$thisNode/@EmbedCode" />
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match ="FieldRef[@Name='EmbedCode']" ddwrt:dvt_mode="body" mode="Note_body">
<xsl:param name="thisNode" select="."/>
<div class="videolink-embedcode">
<xsl:value-of select="$thisNode/@EmbedCode" disable-output-escaping="yes" />
</div>
</xsl:template>
<xsl:template name="ensureVideoPlayerSize">
<xsl:param name="videoSize"/>
<xsl:param name="defaultSize"/>
<xsl:choose>
<xsl:when test="$videoSize &gt; 0">
<xsl:value-of select="$videoSize"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$defaultSize"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template name="renderEmbeddedCodeAsHtml">
<xsl:param name="embedId"/>
<xsl:param name="embeddedCode"/>
<xsl:variable name="embeddedCodeUrl">
<xsl:value-of select="substring-before(substring-after($embeddedCode,'&gt;'),'&lt;/a&gt;')"/>
</xsl:variable>
<xsl:variable name="embeddedCodeFixed">
<xsl:value-of select="substring-before($embeddedCode,'&lt;a')"/>
<xsl:value-of select="$embeddedCodeUrl" />
<xsl:value-of select="substring-after($embeddedCode,'&lt;/a&gt;')"/>
</xsl:variable>
<xsl:variable name="embeddedCodeHtml">
<xsl:value-of select="$embeddedCodeFixed" disable-output-escaping="yes" />
</xsl:variable>
<div id="embeddedPlayerContainer{$embedId}">
</div>
<!–<xsl:value-of select="$embeddedCodeHtml" />–>
<script type="text/javascript">
var playerHost = 'embeddedPlayerContainer<xsl:value-of select="$embedId" />';
var player = '<xsl:value-of select="$embeddedCodeFixed" />';
<![CDATA[
player = player.replace(/&quot;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">");
document.getElementById(playerHost).innerHTML = player;
]]>
</script>
</xsl:template>
</xsl:stylesheet>

References

Embedding and Sharing Video in SharePoint

Introduction

The solution described here allows to embed video hosted on YouTube into SharePoint. The same approach may be applied for embedding video from another video hosting sites, for example from Vimeo.

The main idea here to store embedded video properties and not the embedded code itself.
For storing embedded video properties we will use Custom  List, see implementation section for description. Page for Video Links list (default view with embedded player)  is shown below

Usage

In order to embed a video into SharePoint:

  • On YouTube site click the Share button located under the video.
  • Click the Embed button.
  • Copy at least src attribute value provided in the expanded box (see table 1 for supported attributes).

  • Create new Video Link item  and paste attribute values for embedded code into Video Links item. Save it.

Table 1. Mapping between embedded code iframe attributes and Video Link item

Attribute name Video Links field name
src URL
width Video Width
height Video Height
allowfullscreen Allow Fullscreen
frameborder Frame Border

Video Links implementation

As was mentioned earlier only properties for embedded video code are stored and not the embedded code itself. For storing embedded video code properties is used Custom List that extends OOB Links List (TemplateType = 103)

For embedded video properties we create Video Link Content Type that inherits from Link CT (0x0105)

where we define the following fields

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<Field Type="Number"
DisplayName="Frame Border"
Required="FALSE"
EnforceUniqueValues="FALSE"
Group="Media Columns"
ID="{594e551f-180d-47ec-90e5-9195225c5932}"
StaticName="FrameBorder"
Name="FrameBorder"
Percentage="FALSE"
Hidden="FALSE"
SourceID="http://schemas.microsoft.com/sharepoint/v3">
<Default>0</Default>
</Field>
<Field Type="Number"
DisplayName="Video Height"
Required="FALSE"
EnforceUniqueValues="FALSE"
Group="Media Columns"
ID="{a1e94df1-eb6e-4fd2-aef7-bf0cc175c760}"
StaticName="VideoHeight"
Name="VideoHeight"
Percentage="FALSE"
Hidden="FALSE"
SourceID="http://schemas.microsoft.com/sharepoint/v3"/>
<Field Type="Number"
DisplayName="Video Width"
Required="FALSE"
EnforceUniqueValues="FALSE"
Group="Media Columns"
ID="{e0406eee-7432-47d8-9080-8c1c4db23170}"
StaticName="VideoWidth"
Name="VideoWidth"
Percentage="FALSE"
Hidden="FALSE"
SourceID="http://schemas.microsoft.com/sharepoint/v3"/>
<Field Type="Boolean"
DisplayName="Allow FullScreen"
EnforceUniqueValues="FALSE"
Group="Media Columns"
ID="{b6ba6c8f-81d6-478a-a303-3b18687ec934}"
StaticName="AllowFullScreen"
Name="AllowFullScreen"
Required="FALSE"
Hidden="FALSE"
SourceID="http://schemas.microsoft.com/sharepoint/v3">
<Default>0</Default>
</Field>
<Field Type="Choice"
DisplayName="Embedding Mode"
Required="FALSE"
EnforceUniqueValues="FALSE"
Format="Dropdown"
FillInChoice="FALSE"
Group="Media Columns"
ID="{5836ef4c-c440-4cb8-a471-0ee918bfc710}"
StaticName="EmbeddingMode"
Name="EmbeddingMode"
Hidden="FALSE"
SourceID="http://schemas.microsoft.com/sharepoint/v3">
<Default>IFrame</Default>
<CHOICES>
<CHOICE>IFrame</CHOICE>
<CHOICE>Object</CHOICE>
</CHOICES>
</Field>
<Field
ID="{C1D8C50A-2146-41f6-80CC-02C7691392A3}"
Type="Computed"
Name="EmbeddedVideoOnForm"
StaticName="EmbeddedVideoOnForm"
DisplaceOnUpgrade="TRUE"
ShowInNewForm="FALSE"
ShowInDisplayForm="FALSE"
ShowInEditForm="FALSE"
ShowInFileDlg="FALSE"
DisplayName="Embedded Video"
SourceID="http://schemas.microsoft.com/sharepoint/v3/fields"
Sealed="TRUE"
Sortable="FALSE"
Filterable="FALSE">
<FieldRefs>
<FieldRef Name="URL" />
<FieldRef Name="FileLeafRef" />
<FieldRef Name="FileRef" />
<FieldRef Name="FSObjType" />
<FieldRef Name="EmbeddingMode" />
<FieldRef Name="VideoWidth" />
<FieldRef Name="VideoHeight" />
<FieldRef Name="FrameBorder" />
</FieldRefs>
<DisplayPattern>
<IfEqual>
<Expr1>
<Column Name="EmbeddingMode" />
</Expr1>
<Expr2>IFrame</Expr2>
<Then>
<HTML><![CDATA[<iframe width=']]></HTML>
<Field Name="VideoWidth"/>
<HTML><![CDATA[' height=']]></HTML>
<Field Name="VideoHeight"/>
<HTML><![CDATA[' src=']]></HTML>
<Field Name="URL"/>
<HTML><![CDATA[' frameborder=']]></HTML>
<Field Name="FrameBorder"/>
<HTML><![CDATA[' allowfullscreen']]></HTML>
<HTML>
<![CDATA['></iframe>]]>
</HTML>
</Then>
<Else>
<HTML>
<![CDATA[Not supported yet]]>
</HTML>
</Else>
</IfEqual>
</DisplayPattern>
</Field>
</Elements>

Pay attention, for rendering YouTube player Computed Field EmbeddedVideoOnForm is intended.
For rendering of a field on a List View the following XSLT style sheet is used

And finally, we create List Definition Video Links from Content Type Video Link. List schema and Template files for Video Links including whole project  may be found on GitHub.

References

  • Video Links project on GitHub
  • How to embed Vimeo player see here
  • How to embed YouTube player  see here
  • How to customize the rendering of a field in List View see here