Chapter 12. Customizing the UI

This chapter describes how to extend the UI of Microsoft SharePoint 2013. In particular, you will learn how to customize menus, ribbons, controls, and pages. This chapter is important if you want to be able to provide your users or customers with a custom UI that is compliant with the standard SharePoint behavior, while simultaneously satisfying the requirements of intranet and extranet solutions, as well as Internet publishing sites.

Custom actions

The first area of customization that you will address is creating custom actions in the standard SharePoint UI. Custom actions are features that can extend or change the standard behavior of any of the following items: menu items, link menus of administrative pages, and ribbons. The ribbon is important enough to warrant a dedicated section in this chapter (see “Ribbons”); all other custom actions will be covered here. As you may recall from Chapter 4 the types of custom action features that you can create are

  • CustomAction. Creates a new custom action to define a new control on a ribbon, a new menu item on a standard menu, or a new link on a settings page

  • CustomActionGroup. Creates a new group of custom actions for better usability from the perspective of the end user

  • HideCustomAction. Hides an existing custom action defined by another custom action or implemented by default in SharePoint

The following pages will delve into these items.

The CustomAction element

The definition of a CustomAction element requires the declaration of a feature element manifest, based on the XML structure, as illustrated in The CustomAction element structure.

The CustomAction element is made of a set of attributes and accepts a couple of optional child elements. Table 12-1 describes each available attribute.

Table 12-1. The attributes supported by the CustomAction element

Attribute name

Description

RequiredAdmin

Optional Text attribute that specifies the rights required for the custom action to apply. Supported values are Delegated, Farm, and Machine.

ControlAssembly

Optional Text attribute used to declare a custom assembly full name, hosting a control for rendering the custom action with code running on the server side.

ControlClass

Used to declare a custom class, implementing a control for rendering the custom action with code running on the server side.

ControlSrc

Optional Text attribute that specifies the relative URL of an ASCX file that corresponds to the source of the custom action.

Description

Optional Text attribute with which you can provide a long description for the action.

FeatureId

Optional Text attribute that specifies the ID of the feature associated with the custom action.

GroupId

Optional Text attribute that declares the group that will contain the custom action. For a complete reference of all the available groups and locations, refer to “Default Custom Action Locations and IDs,” on MSDN online at http://msdn.microsoft.com/en-us/library/bb802730.aspx.

Id

Optional Text attribute that specifies the ID of the custom action. This can be a GUID or a string that uniquely identifies the custom action.

ImageUrl

Declares the relative URL of an image that represents an icon for the custom action.

Location

Specifies the location of the custom action. This is a value taken from a predefined list of locations or from a custom set of locations.

RegistrationId

Optional Text attribute that declares the ID of the target list, content type, or file type associated with the custom action.

RegistrationType

Optional Text attribute that declares the type of registration the action is targeting. RegistrationType works together with the RegistrationId attribute, and can assume one of the following values: None, List, ContentType, ProgId, or FileType.

RequireSiteAdministrator

Optional Boolean attribute that specifies whether the action will be displayed to all users or only to site administrators.

Rights

Optional Text attribute that defines the minimum set of rights required to view the current custom action. If it is not specified, the action will be visible to anyone. It can specify one or more rights, comma separated, selected from the list of available rights defined in the standard base permission of SharePoint. Possible values are ViewListItems, ManageAlerts, ManageLists, and so on.<br/>For a complete reference of all the base permissions available in SharePoint, refer to the document “SPBasePermissions Enumeration,” at http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spbasepermissions.aspx.

RootWebOnly

Optional Boolean attribute, valid only for sandboxed solutions, that specifies if the action must be only on root websites.

ScriptSrc

Optional Text attribute that defines the relative URL of a script to download and execute. ScriptSrc works only in conjunction with a Location attribute with a value of ScriptLink. It is very useful whenever you need to reference external JavaScript source files for implementing custom behaviors.

ScriptBlock

Optional Text attribute that defines the ECMAScript source code of a script to execute. ScriptBlock works only in conjunction with a Location attribute with a value of ScriptLink.

Sequence

Optional Integer attribute that defines the ordinal position of the custom action, within its group.

ShowInLists

Deprecated optional Boolean attribute that specifies whether the action will be shown in the page for managing content types.

ShowInReadOnlyContentTypes

Optional Boolean attribute that specifies whether the action will be displayed only for the page for managing read-only content types.

ShowInSealedContentTypes

Optional Boolean attribute that specifies whether the action will be displayed only for the page for managing sealed content types.

Title

Required Text attribute to specify the title of the action. Title will be used in the UI to present the action to the end user.

UIVersion

Optional Integer value to define the version of the UI in which the action will be rendered.

In addition, a CustomAction tag can contain some child elements:

  • UrlAction. Defines a destination URL for when the end user clicks the custom action.

  • CommandUIExtension. Defines a complex UI extension, typically a ribbon. This will be discussed in the next section, “Ribbons.”

The basic and most-used attributes are those for defining the ID, the title, the location (where you want the action to appear), and the registration type, together with the registration ID. For example, if you want your action to be displayed when the end user clicks the contextual menu of a document (also called the Edit Control Block [ECB] menu), you can define a custom action for the document libraries of a site like the one illustrated in A CustomAction targeting the ECB menu of items in a document library.

The Location attribute specifies that the action will be shown in the ECB menu. The RegistrationType attribute targets a specific List, while the RegistrationId explicitly defines the list type (101 = “Document Library”). Notice the child element, UrlAction, which defines a destination URL for when the end user clicks the menu item. In this first example, the custom action simply shows an alert. Figure 12-1 depicts how the action looks in the web browser.

A screen shot depicting the ECB menu of a document item, showing the custom Sample Action command.

Figure 12-1. The custom action shown in the ECB of a document item.

Often, you need to define a custom action targeting not only a list, but also a specific content type, regardless of the list in which it is contained. For example, suppose that you have a custom content type defining a document of type invoice (call it DevLeapInvoice). This content type needs to have an identifying unique ID, which in this example will have a value of 0x010100DFCFE30E0795465F8973EF29B73F1551.

The DevLeapInvoice content type has some custom metadata fields to define the invoice number, a description, and a status that can assume some predefined values (Draft, Approved, Sent, and Archived). Figure 12-2 illustrates the edit form of this kind of document.

A screen shot of the edit form for a document with content type DevLeapInvoice. The available fields are Name, Title, Invoice Number, Description, and Status.

Figure 12-2. The edit form of a DevLeapInvoice item instance.

A CustomAction element targeting the ECB of items with a content type of DevLeapInvoice demonstrates a custom action, still targeting the ECB, that will be shown only in the ECB of items with a content type of DevLeapInvoice. The action allows archiving a single invoice, changing its Status field to a value of Archived.

The only substantial difference between A CustomAction element targeting the ECB of items with a content type of DevLeapInvoice and A CustomAction targeting the ECB menu of items in a document library is the RegistrationType attribute, which now targets a ContentType, as well as the RegistrationId, which now defines the ID of the target content type instead of the ID of a list template. The code sample in A CustomAction element targeting the ECB of items with a content type of DevLeapInvoice also introduces the Rights attribute, with which you can archive invoices only to users who have the ViewListItems and EditListItems permissions assigned.

Additionally, the UrlAction child element defined in A CustomAction element targeting the ECB of items with a content type of DevLeapInvoice declares a URL of a custom application page, instead of a piece of JavaScript, as in A CustomAction targeting the ECB menu of items in a document library. The URL could also link to a custom page provided by a custom SharePoint 2013 app. In the “Application pages” section of this chapter, you will learn how to deploy custom application pages. For now, however, disregard the page itself and focus your attention on the Url attribute of the UrlAction element. This attribute can link to any kind of URL and can contain tokens that will be replaced by the environment during page rendering. These tokens are

  • ~site. Website-relative (SPWeb) link

  • ~sitecollection. Site collection–relative (SPSite) link

  • ~remoteAppUrl. URL of the site hosting a SharePoint 2013 app, which installs a custom action

  • {ItemId}. Integer ID that represents the item within a list

  • {ItemUrl}. URL of the current item; works only for documents in libraries

  • {ListId}. ID (GUID) of the list on which the action is currently working

  • {SiteUrl}. URL of the website (SPWeb)

  • {RecurrenceId}. Recurrence index ID when related to recurring event items

Finally, you can use any valid JavaScript code block.

In A CustomAction element targeting the ECB of items with a content type of DevLeapInvoice, the Url attribute uses the {ItemId} and {ListId} tokens because it targets the ECB menu of a single item, so it passes the item ID and list ID to the target page as QueryString parameters.

The ECB menu isn’t the only location suitable for defining custom actions. Table 12-2 lists the most useful additional locations.

More Info

For a complete list of all the available locations, refer to the document “Default Custom Action Locations and IDs,” at http://msdn.microsoft.com/en-us/library/bb802730.aspx.

Table 12-2. The most useful locations for defining custom actions

Location

Group ID

Description

DisplayFormToolbar

Not applicable

Corresponds to the display form toolbar of lists

EditControlBlock

Not applicable

Corresponds to the per-item ECB menu

EditFormToolbar

Not applicable

Corresponds to the edit form toolbar of lists

Microsoft.SharePoint.SiteSettings

Customization

Look And Feel section of the Site Settings page

 

Galleries

Galleries section of the Site Settings page

 

SiteAdministration

Site Administration section of the Site Settings page

 

SiteCollectionAdmin

Site Collection Administration section of the Site Settings page

 

UsersAndPermissions

Users And Permissions section of the Site Settings page

Microsoft.SharePoint.StandardMenu

ActionsMenu

Actions menu in list and document library views

 

ActionsMenuForSurvey

Site Actions menu for surveys

 

NewMenu

New menu in list and document library views

 

SiteActions

Site Actions menu

NewFormToolbar

Not applicable

Corresponds to the new form toolbar of lists

ViewToolbar

Not applicable

Corresponds to the toolbar in list views

Microsoft also documents the Id values for many of the previously defined custom actions, with which you can override standard menu items with custom items of your own.

The CustomActionGroup element

Another useful element for defining custom actions is CustomActionGroup. Using this element, you can define groups of actions; it is typically used when defining custom sections in the configuration pages, such as the Site Settings page or the pages of the Central Administration. In fact, you can also extend and override administrative pages, not only end-user UI elements. The CustomActionGroup element structure shows the structure of the CustomActionGroup element.

The CustomActionGroup element is mainly descriptive (for the group it defines). It does not have any child elements because the only purpose of this element is to declare a new group, which will be referenced by other custom actions. Table 12-3 presents a brief description of the available attributes.

Table 12-3. The attributes supported by the CustomActionGroup element

Attribute name

Description

RequiredAdmin

Optional Text attribute that specifies the rights required for the custom action group to apply. Values supported are Delegated, Farm, and Machine.

Description

Optional Text attribute with which you can provide a long description for the action group.

Id

Required Text attribute that specifies the ID of the custom action group. It can be a GUID or a string that uniquely identifies the custom action group.

ImageUrl

Optional Text attribute that declares the relative URL of an image representing an icon for the custom action.

Location

Required Text attribute that specifies the location of the custom action group. Location is a value taken from a predefined list of locations or from a custom set of locations.

Sequence

Optional Integer value that defines the ordinal position of the custom action group within the set of groups.

Title

Required Text attribute that specifies the title of the action. Title will be used in the UI to present the action group to the end user.

CustomActionGroup element extending the Site Settings administrative page illustrates how to use the CustomActionGroup element to define a new section in the Site Settings administrative page. Notice the CustomAction element that uses a value of Microsoft.SharePoint.SiteSettings for the Location attribute and the value of the custom action group’s Id for the GroupId attribute.

Figure 12-3 shows the customized Site Settings administrative page in action.

A screen shot illustrating a custom group of actions in the Site Settings page. Within the custom group, named Invoices Management, is a custom action menu item, named Invoices Sample Settings Page.

Figure 12-3. A customized Site Settings administrative page.

The HideCustomAction element

The last element available for customizing UI actions is HideCustomAction. Using this element, you can hide existing actions, regardless of whether they are standard, native actions or custom actions defined by you or someone else. Be aware, though, that not all native actions can be hidden. The HideCustomAction element structure shows you the structure of the HideCustomAction element.

This element simply defines the information about the action to hide. Table 12-4 gives you a brief explanation of the available attributes.

Table 12-4. The attributes supported by the HideCustomAction element

Attribute name

Description

GroupId

Optional Text attribute that specifies the group to which the action to hide belongs

HideActionId

Optional Text attribute that specifies the ID of the action to hide

Id

Optional Text attribute that specifies the ID of the current HideCustomAction element

Location

Optional Text attribute that specifies the location of the custom action to hide

A sample HideCustomAction element declaration presents an example of the HideCustomAction element being used to hide the Quick Launch menu item in the Look And Feel group of the Site Settings page.

In A sample HideCustomAction element declaration, the Location, GroupId, and HideActionId attributes correspond to those identifying the Site Theme action. Figure 12-4 shows the result of this action, comparing the page before applying the customization, and then after.

A screen shot comparing the standard Site Settings menu, which includes the Quick Launch menu item in the Look And Feel group, with the customized Site Settings menu, which lacks that menu item because of the HideCustomAction element.

Figure 12-4. The Look And Feel group before (left) and after (right) hiding the Site Theme action.

Server-side custom actions

You can also create custom actions that define their content dynamically by using server-side code, instead of using an XML declaration. To define this kind of action, you need to declare a CustomAction element within a feature element manifest, providing a value for the ControlAssembly and ControlClass attributes. These attributes must reference the assembly and the full type name of a class inheriting from the base class System.Web.UI.WebControls.WebControl and building a specific set of controls inside the CreateChildControls method override. The custom action referencing a custom ControlClass attribute illustrates an example of a custom action referencing a custom ControlClass attribute.

Note

The values of both the ControlAssembly and the ControlClass attributes in The custom action referencing a custom ControlClass attribute must be defined on a single line of code.

The action targets the Site Actions menu (also known as the gear menu) and allows switching the site to mobile-rendering mode. Of course, you could write this action without a custom class, but this example gives you an idea of what’s possible.

The class referenced by the CustomClass attribute of the custom action of The custom action referencing a custom ControlClass attribute displays the sample implementation of the class, which is referenced in the ControlClass attribute, and which internally generates the menu item.

The class referenced by the CustomClass attribute of the custom action of The custom action referencing a custom ControlClass attribute illustrates that you can instantiate a MenuItemTemplate class, which represents a single menu item. You can then configure its descriptive properties, such as Text, Description, ImageUrl, and so on. However, the fundamental properties are those related to the behavior of the menu item within the UI. You can configure the ClientOnClickNavigateUrl property if you simply need to define a URL to navigate to when the user clicks the menu. Additionally, you can configure the ClientOnClickScript property to configure an ECMAScript code block to execute when the menu entry is clicked. Lastly, to set the control ID and parameter for a postback event, you can assign the ClientOnClickUsingPostBackEvent property. In this last scenario, you should handle the postback event yourself; for example, by implementing the System.Web.UI.IPostBackEventHandler interface in the control class. You can also configure the ClientOnClickPostBackConfirmation property to provide a confirmation message that will be displayed to the end user, just before handling the post-back event. Figure 12-5 shows the result of the sample in The class referenced by the CustomClass attribute of the custom action of The custom action referencing a custom ControlClass attribute.

A screen shot illustrating the new Switch To Mobile View item in the Settings gear menu.

Figure 12-5. The custom action defined using a MenuItemTemplate class on the server side.

Another type of menu that you can instantiate within custom code is SubMenuTemplate, which represents the parent of a hierarchical menu.

Regardless of the type of menu items you define within your CustomClass implementation, it is mandatory to define the class as a SafeControl object for SharePoint. (Details about using SafeControl elements in web.config files were presented at the end of Chapter 11)

Note

While working with Microsoft Visual Studio 2012, Web Parts are automatically configured in the solution’s manifest file as SafeControl items. However, the custom class shown in The class referenced by the CustomClass attribute of the custom action of The custom action referencing a custom ControlClass attribute, as well as any other control class that is not a Web Part, will not be automatically registered as a SafeControl. To force registration of the class as a SafeControl—using Visual Studio 2012—you can open the Feature Designer of any feature element of your package, such as the one defining the custom actions. There, in the property grid panel, you will find a Safe Control Entries property of type collection that will support you in configuring one or more custom SafeControl entries.

Ribbons

For end users, the ribbon is one of the most visible and evident features of SharePoint 2013. Having a web-based solution with a command bar that makes use of ribbons, such as Microsoft Office clients do, is a great way to support and involve users who are already accustomed to using such tools.

SharePoint 2013 provides a native set of ribbons, but any developer can define specific CustomAction elements to define his or her own ribbon commands, groups, and tabs. In this section, you will learn how.

Ribbon commands

Ribbon commands represent single items to place in a previously existing ribbon tab and group. For example, think about the code sample in A CustomAction element targeting the ECB of items with a content type of DevLeapInvoice. The goal of that custom action was to allow archiving a single invoice, changing its Status field to a value of Archived. A better option, however, would be to give users the opportunity to archive multiple invoices at the same time. The ECB menu extended with A CustomAction element targeting the ECB of items with a content type of DevLeapInvoice applies only to a single item, while a ribbon command could be applied to multiple items simultaneously, improving usability and overall user experience.

To get familiar with ribbons, start with a simple example. A sample ribbon that shows an alert upon being clicked presents a ribbon that displays an alert when it is clicked.

The CustomAction element is almost the same as in the previous section, but the Location attribute targets a location with a value of CommandUI.Ribbon.ListView, which corresponds to the ribbon menu of a ListView control. Then the action targets the DevLeapInvoice content type through its content type ID, as with the ECB custom action defined earlier. Thus, the ribbon command will show up only while DevLeapInvoice  items are being worked on. However, instead of a UrlAction child element, now there is a CommandUIExtension element, which defines a ribbon item. In particular, it defines a set of CommandUIDefinition elements, wrapped in a CommandUIDefinitions parent element, together with one or more CommandUIHandler elements, wrapped by a CommandUIHandlers parent tag. A CommandUIDefinition element defines the UI behavior of the command with its Location attribute, which in the code sample has a value of Ribbon.Documents.Manage.Controls._children and declares that its child elements will be children of the Manage group of the Documents tab of the ribbon. In A sample ribbon that shows an alert upon being clicked, the command is represented as a Button element with a title, a description, a couple of images sized 16×16 pixels and 32×32 pixels, and so on. Also in A sample ribbon that shows an alert upon being clicked, the Button element has a Sequence attribute with a value of 25, which means it will render between the second and third button of the target ribbon group (Manage). For standard and native buttons, the Sequence attribute has a value that is a multiple of 10. Thus, the first button has a Sequence value of 10, the second has a Sequence value of 20, and so on.

Another interesting Button attribute is TemplateAlias, which defines the rendering behavior of the control. Native available templates are o1, which renders the 32×32 image form of the button, and o2, which renders the 16×16 image form. However, you can also define your own templates. Additionally, the CommandUIHandler element declares the code to execute when the commands are clicked. For example, in A sample ribbon that shows an alert upon being clicked, the CommandAction attribute of the CommandUIHandler element invokes a client-side window.alert method based on JavaScript. For mapping the Button to its handler, there is a Command attribute whose value corresponds to the Command attribute of the CommandUIHandler element. Figure 12-6 shows the results of A sample ribbon that shows an alert upon being clicked in action.

A screen shot depicting the ribbon while a document with a content type of DevLeapInvoice is being selected. The image highlights the custom ribbon button created by .

Figure 12-6. The custom ribbon command to show an alert in action.

The CommandUIDefinition element can host a rich set of child elements. Table 12-5 presents a quick list of all the supported child elements, taken from the official product documentation on MSDN (http://msdn.microsoft.com/en-us/library/ff458373.aspx).

Table 12-5. The child elements of the CommandUIDefinition element

Attribute name

Description

Button

Defines a push-button control. The main attributes are Alt, for alternate text; the Command to execute on click; Description and LabelText, for the UI; the various attributes to define 16×16 and 32×32 images, eventually cropped from an image map; the TemplateAlias and the Sequence position of the button in the owner group; and the various attributes to define tooltip text and images.

CheckBox

Defines a CheckBox control. CheckBox also has a Command attribute to execute when clicked, as well as layout attributes regarding description, images, and so on.

ColorPicker

Defines a ColorPicker control.

ComboBox

Defines a ComboBox control. ComboBox supports attributes for defining autocompletion; the command to execute on click; and the command to execute on open, close, and preview.

ContextualGroup

Defines a group of tabs that are presented when they are relevant. ContextualGroup allows defining a specific color to use while showing the group.

ContextualTabs

Contains groups of tabs that are conditionally present. ContextualTabs is the container of one or more ContextualGroup elements.

Controls

Contains elements that define controls. Controls can contain elements of type Button, CheckBox, ComboBox, DropDown, FlyoutAnchor, GalleryButton, Label, MRUSplitButton, Spinner, SplitButton, TextBox, and ToggleButton.

DropDown

Defines a control with which a user can select from a drop-down list. Supports most of the same attributes as the ComboBox element.

FlyoutAnchor

Defines the anchor point for a flyout menu. Supports attributes for defining the command to execute when the control is clicked, the various attributes for declaring images and tooltips, and the command to invoke for populating the menu dynamically.

Gallery

Defines a gallery. Supports attributes to define the dimensions of child items. Gallery is made up of a set of GalleryButton child elements.

GalleryButton

Defines a gallery button. These are almost like standard buttons, except that they allow defining the dimensions, according to the parent Gallery, and they support an InnerHTML attribute to define the HTML markup that illustrates the choice that the button represents.

Group

Defines a group of controls. Supports attributes for defining the description, the various images, and the command to execute when clicked.

Groups

Defines the groups of controls on a tab. Simply contains a set of child Group elements.

GroupTemplate

Defines the scaling behavior for controls in a Group element. GroupTemplate can host Layout child elements and offers a ClassName attribute for defining a CSS style sheet to apply to the group.

InsertTable

Defines a menu control for inserting a table that contains a variable number of cells. Provides a Command attribute for defining the code to execute when the table has to be inserted, as well as CommandPreview and CommandRevert attributes to preview and revert the effect of the command.

Label

Defines a Label control. Label supports a ForId attribute to declare the ID of the target control of the label, and some other attributes to define the images as well as the LabelText attribute.

MaxSize

Specifies the maximum size for a group of controls. MaxSize offers a Size attribute to define the maximum allowed size for the group of controls.

Menu

Defines a menu control. Menu supports only a MaxWidth attribute.

MenuSection

Defines a section of a menu. MenuSection can host child elements of type Controls and Gallery. It also offers a DisplayMode attribute to define the sizing of the items, and a Scrollable attribute to declare if the menu section can be scrolled.

MRUSplitButton

Defines a control that combines a button and a drop-down menu to display a list of the most recently used items. Provides some attributes to declare the code to execute for the purpose of populating the most recently used list, as well as to use when the user previews or reverts the selection, or effectively selects an item.

QAT

Defines a quick-access toolbar. QAT supports some attributes to declare images and CSS classes, and hosts a Controls child element.

Ribbon

Contains elements that define the Server ribbon UI. Ribbon is the container of Tabs and ContextualTabs child elements. It supports many appearance attributes.

Scale

Defines how a group of controls on a tab is sized. Scale is the child of a Scaling element and supports Size and PopupSize attributes.

Scaling

Defines tab scaling. Scaling contains child elements of type MaxSize and Scale.

Spinner

Defines a spinner control. Spinner can contain a Unit child element and supports some appearance attributes, as well as a command to execute when the control is clicked.

SplitButton

Defines a control that combines a button and a drop-down menu. SplitButton can host a Menu child element. Supports many attributes to define various images, tooltips, and commands related to the drop-down menu.

Tab

Represents a Tab control. Tab defines a CssClass attribute to use while rendering the tab and the title to show in the tab. It is the container of the Scaling and Groups child elements.

Tabs

Contains elements that define tab controls. Tabs can host a set of Tab child elements.

TextBox

Defines a TextBox control. TextBox supports attributes for defining the appearance of the control, as well as a command to execute when it is clicked, and MaxLength to define the maximum length in characters.

ToggleButton

Defines a button that is used to switch states. ToggleButton supports attributes for defining the appearance of the control, as well as a command to execute when it is clicked.

Recall that the goal of this particular section is to have a ribbon with which a user can archive multiple items with content type DevLeapInvoice at the same time. Source code for a ribbon that archives one or more items with a content type of DevLeapInvoice shows the source code necessary.

Although Source code for a ribbon that archives one or more items with a content type of DevLeapInvoice is not short, it is actually quite simple. In fact, it takes advantage of the JavaScript Client-Side Object Model (JSOM)—which was presented in Chapter 7—within the code of the CommandAction attribute of the CommandUIHandler element. It creates a ClientContext, retrieves the selected items by using the SP.ListOperation.Selection class, and then updates them with a Status field value of Archived, invoking the asynchronous operation via the executeQueryAsync method of the ClientContext.

It is interesting to note that the ribbon is entirely defined in XML and JavaScript, without the need for any kind of server-side code. Thus, it will work asynchronously in the web browser without requiring a postback to the server. The only postback is required at the end of the update process, to refresh the list of items and reflect the applied changes. You can see the invocation of the SP.UI.ModalDialog.RefreshPage method in the onUpdateSucceeded method. You can also include the JavaScript code in an external JS file and reference it using a custom action with the Location attribute with a value of ScriptLink. Last but not least, remember that you can deploy such commands while working within a custom SharePoint 2013 app as well.

Another interesting aspect of Source code for a ribbon that archives one or more items with a content type of DevLeapInvoice is the attribute EnabledScript of the element CommandUIHandler. This attribute is invoked on the client side, and it contains another JavaScript script block to determine if the ribbon command must be enabled or disabled. Internally, the script checks the number of selected items and returns true only if there is at least one invoice selected in the result of the SP.ListOperation.Selection.getSelectedItems() method. As the sample code illustrates, the SP.ListOperation.Selection.getSelectedItems() method returns only the IDs of the selected items, not the items themselves.

To complete the example, the Location attribute of the CommandUIDefinition element declares where to locate the new ribbon. In this example, the ribbon is in the Open & Check Out group of the Documents tab, which has a location of Ribbon.Documents.EditCheckout.Controls. Thus, the new command has a Location value of Ribbon.Documents.EditCheckout.Controls._children to instruct the environment to show the item as a child of the Open & Check Out group.

Note

You can find the complete list of locations in the document “Default Server Ribbon Customization Locations,” which is available on MSDN at http://msdn.microsoft.com/en-us/library/ee537543.aspx.

The sample code of Source code for a ribbon that archives one or more items with a content type of DevLeapInvoice also uses the new notification area of SharePoint 2010, which will be discussed in the “Status bar and notification area” section. Figure 12-7 shows the ribbon command in action.

A screen shot highlighting the new Archive Invoices ribbon button, which is available in the Open & Check Out group when one or more documents of type DevLeapInvoice are selected.

Figure 12-7. The custom ribbon command to archive multiple invoices simultaneously.

Finally, consider that inside the code of the CommandAction attribute, you can use substitution tokens that are replaced by the environment before executing the script. The available tokens are

  • {ItemId}. ID (GUID) taken from the list view

  • {ItemUrl}. Web-relative URL of the list item

  • {RecurrenceId}. ID of a recurrent item

  • {SiteUrl}. The fully qualified URL to the site

  • {ListId}. ID (GUID) of the list

  • {ListUrlDir}. Server-relative URL of the site plus the list’s folder

  • {Source}. Fully qualified request URL

  • {SelectedListId}. ID (GUID) of the list that is currently selected from a list view

  • {SelectedItemId}. ID of the item that is currently selected from the list view

One last scenario to consider is the creation of a custom ribbon tab. In fact, if you have multiple commands to support your custom content, it is good habit to define a ribbon tab of your own, instead of extending an existing one. To define a new tab of ribbons, you need to use the Tab, Scaling, Groups, and Group elements. A custom tab of ribbons for a content type of DevLeapInvoice demonstrates the declaration of a custom tab, which will show up only when selecting items with a content type of DevLeapInvoice. The tab will host three buttons that, for the sake of simplicity, just show an alert with a welcome message.

A custom tab of ribbons for a content type of DevLeapInvoice first creates a new ribbon tab that declares a Location value of Ribbon.Tabs._children, with a Title value of Invoices. It also declares some scaling information, indicating how the ribbon will behave when the window is resized. Specifically, you must define a MaxSize element for each ribbon group, describing the rendering behavior at the maximum size. You also need to define at least one Scale element for each ribbon group, providing information about how to scale the contents of the group. Both the MaxSize and Scale elements use a Size attribute with a value that references the Title attribute of the Layout elements defined in the CommandUIDefinition element, with a Location value of Ribbon.Templates._children. In the current example, the OneLargeTwoSmall sizing layout describes a first Section element with one row, and a second Section element with two rows. The Row elements defined in the Section elements also declare a TemplateAlias, which the Button elements will reference. It is also important to notice the value of the Location attribute of the two CommandUIDefinition elements.

Notice the way that the images of the buttons are defined. For performance reasons, SharePoint 2013 uses CSS image sprites, which use images that are maps of multiple icons, rendered using CSS cropping. For example, there are two image files, named formatmap16x16.png and formatmap32x32.png, that contain a rich set of icons used for rendering buttons of ribbons and menus with a size of 16×16 pixels and 32×32 pixels, respectively. If you want to render a specific image, you need to reference the proper picture in the Image16by16 or Image32by32 attribute, depending on the size of the image you are looking for. Then you need to provide the location of the top and left corners of the image to crop, using the attributes Image16by16Top and Image16by16Left, or Image32by32Top and Image32by32Left. These attributes require a negative value for the offset. In A custom tab of ribbons for a content type of DevLeapInvoice, the image URLs include the reference to the proper culture code, determined by querying the core resource strings. Figure 12-8 displays the output of A custom tab of ribbons for a content type of DevLeapInvoice as it appears in the web browser.

A screen shot with the new custom ribbon tab highlighted. The ribbon tab contains three custom ribbon commands: the larger First Sample Command on the left, and two smaller icons on the right.

Figure 12-8. The custom tab of ribbons targeting the content type DevLeapInvoice.

Custom content

In the previous sections, some of the code listings referenced custom images and pages that were deployed on the farm together with the features that use them. In this section, you will learn how to use features to deploy this kind of custom content.

Images and generic content

The first types of content that you will probably need to deploy are custom images. By default, SharePoint stores images in the SharePoint15_RootTEMPLATEIMAGES folder and makes them available through a virtual directory named _layouts/15/images/.

Note

SharePoint15_Root refers to the SharePoint root folder, which is typically located at C:Program FilesCommon FilesMicrosoft SharedWeb Server Extensions15.

Working with Visual Studio 2012, you can deploy custom images in the proper folder by right-clicking the project to open the menu shown in Figure 12-9, and then selecting Add | SharePoint “Images” Mapped Folder. This creates a folder named Images in your project. When you add an image file to this folder, the file will be automatically deployed in the SharePoint Images folder. To better organize files in the SharePoint folders, Visual Studio 2012 automatically creates a subfolder that uses the name of the current project and places the images there. For example, if your project name is MyCustomProject, and you add an image file with the name MyImage.jpg, then the image will be deployed under the path SharePoint15_RootTEMPLATEIMAGESMyCustomProjectMyImage.jpg, and will be available through the relative URI ./_layouts/15/images/MyCustomProject/MyImage.jpg.

A screen shot of the Visual Studio 2012 UI containing the menu for adding the Images mapped folder to the current project. Two selections are highlighted: Add and SharePoint “Images” Mapped Folder.

Figure 12-9. The menu item to add an image to the SharePoint15_RootTEMPLATEIMAGES folder.

If you need to deploy other kinds of generic content, such as ASCX controls, CSS files, JS files, and so on, select Add | SharePoint Mapped Folder from the project’s contextual menu. You will be prompted with a pop-up window like the one shown in Figure 12-10. From there, you will be able to select any of the folders available under the SharePoint15_Root path.

A screen shot of the Add SharePoint Mapped Folder window, which lists the standard folders available in the SharePoint15_Root folder.

Figure 12-10. The pop-up window to select a SharePoint mapped folder.

Important

Keep in mind that you can deploy files on the target server’s file system only while on-premises and working with full-trust solutions. Thus, this deployment technique is not available while working with Microsoft Office 365 or SharePoint Online.

Application pages

Application pages are ASPX files that are available for all sites of a farm and deployed in the SharePoint15_RootTEMPLATELAYOUTS folder. SharePoint makes them available through a virtual directory named _layouts. In general, these pages are defined to provide the UI for administrative tasks or to implement custom application pages that will be used to support custom solutions, which in this case do not include SharePoint apps that use a different page model (as discussed in Chapter 8). For example, A CustomAction element targeting the ECB of items with a content type of DevLeapInvoice contains a UrlAction element referencing a custom application page called DevLeapInvoiceChangeStatus.aspx.

To create such pages using Visual Studio 2012, you can simply add a new item to the project and then select an item of type Application Page, which is an ASPX file. A folder named Layouts will be added to the project, if it does not already exist. Within that folder, a subfolder will be created, using the name of your project. The new ASPX file will be placed in that subfolder. The ASPX file will define a standard ASP.NET page, which you will be able to define using standard ASP.NET controls, custom SharePoint controls, or custom controls of your own. By default, the page will have a DynamicMasterPageFile attribute with a value of ~masterurl/default.master, but you can freely change this behavior. In addition, the CodeBehind attribute of the page will reference a code file declaring a custom ASP.NET page that will inherit from the LayoutsPageBase class, which is defined in the Microsoft.SharePoint.WebControls namespace and defines the base and common behavior for every application page. The LayoutsPageBase base class provides some useful properties to directly access the SPWeb and SPSite instances of the current context.

In A CustomAction element targeting the ECB of items with a content type of DevLeapInvoice, the custom application page used in the UrlAction element was capable of changing the Status field of a single item with a content type of DevLeapInvoice, reading the target ListId, ItemId, and Status from the QueryString. The source code behind the DevLeapInvoiceChangeStatus.aspx page used in A CustomAction element targeting the ECB of items with a content type of DevLeapInvoice reveals the source code behind that page.

The ASPX code of the DevLeapInvoiceChangeStatus.aspx page is not terribly interesting because it has no content. However, a classic custom application page should define only the content regions to fill out the content placeholders defined in the master page used by the target site.

Important

Application pages cannot be personalized or customized by the end user because they are defined on the file system. If you need to define custom pages that are also customizable, you need to refer to the next section.

Content pages, Web Part pages, and galleries

Sometimes you need to deploy pages that do not need to be shared and available on any site of your farm. Instead, you simply need to deploy a custom page or Web Part page to a single target site, eventually supporting customization by the end user or by using SharePoint Designer 2013.

To accomplish this task, you can use the Module feature element, which enables you to deploy an item into the content database of a target site. The structure of the Module feature element, together with its child elements shows the structure of the Module element, together with its child elements.

The code in The structure of the Module feature element, together with its child elements is made up of a small set of attributes, while the core part is made of the child File element. Table 12-6 provides explanations of the main attributes of the Module element.

Table 12-6. The main attributes of the Module element

Attribute

Description

HyperlinkBaseUrl

Optional Text attribute that specifies an absolute URL to use as the base URL for hyperlinks.

List

Optional Integer attribute that specifies the type of the target list. The possible values are defined in the onet.xml file of the site template (more about this in Chapter 13).

Name

Required Text attribute that specifies the name of the module.

Path

Optional Text attribute that specifies the path of the physical files, relative to the feature’s folder: SharePoint15_RootTEMPLATEFEATURESFeatureName.

RootWebOnly

Required Boolean attribute that specifies whether the files will be installed only on the top-level website of the current site collection.

SetupPath

Optional Text attribute that specifies the physical path to a folder within the SharePoint15_RootTEMPLATEFEATURESFeatureName folder that contains a file to include in the module.

Url

Optional Text attribute that specifies the virtual path of the folder in which to include the files to deploy. If Path is not specified, the value of Url will be used. If you provide a value that corresponds to a folder that does not exist, the folder will be created upon activation of the feature.

Moreover, Table 12-7 provides explanations of each attribute available for the File element.

Table 12-7. The attributes supported by the File element in a Module element

Attribute

Description

IgnoreIfAlreadyExists

Optional Boolean attribute that specifies whether to overwrite an already existing item (true) or not (false).

Name

Optional Text attribute that specifies the virtual path name for the file in the target site.

NavBarHome

Optional Boolean attribute that specifies whether to use the current content, in case it is a page, as the home link in the top navigation bar. In general it is used while defining custom site templates. For further details, see Chapter 13.

Path

Optional Text attribute that specifies the path of the physical file, relative to the feature’s folder: SharePoint15_RootTEMPLATEFEATURESFeatureName.

Type

Optional Text attribute that specifies whether the file will be stored in a document library (GhostableInLibrary) or outside a document library (Ghostable).

Url

Required Text attribute that specifies the virtual path of the file in the target site. If the value of the Name attribute is specified, then it will be used as the virtual path. If the value of the Path attribute is not specified, the value of Url will be used instead.

A Module feature to deploy an image into the Site Assets library of a SharePoint site shows how to deploy a custom image into the Site Assets library of a SharePoint site by using the Module feature.

You can also use the Module feature for deploying a content page, eventually to be made up of Web Parts. If you need to deploy an ASPX content page only, you can use an element manifest file, such as the one shown in A Module feature used to deploy a content page on a SharePoint site.

The code in A Module feature used to deploy a content page on a SharePoint site provisions a page with a URL value of SampleContentPage.aspx under the root of the target site, reading the page content from a file stored in the feature’s folder, under the relative path SampleContentPageSampleContentPage.aspx. The source code of the page SampleContentPage.aspx provisioned in A Module feature used to deploy a content page on a SharePoint site presents the source code of that page.

If the page you are going to provision is a Web Part page, that means it is made up of Web Parts; the File element supports some child elements specifically available for including Web Parts in a Web Part page. Now consider the ASPX page illustrated in A Web Part page provisioned through a Module feature. It defines a page that includes a WebPartZone control with an ID of MainWebPartZone placed in the PlaceHolderMain content region.

Note

The @Register directives at the top of A Web Part page provisioned through a Module feature must have the Assembly attribute defined on their own line.

The Module element defined in The feature element manifest used to provision a Web Part page, together with some Web Parts automatically provisions the page from A Web Part page provisioned through a Module feature into the library Site Pages, adding two Web Parts into the WebPartZone with ID MainWebPartZone. The key point is the inclusion of the AllUsersWebPart child elements in the File element. The first one defines an instance of the standard ImageWebPart of SharePoint. The second child element references the HelloWorldWebPart that was defined at the beginning of Chapter 11.

Notice also that the syntax for declaring the two Web Parts is different. In fact, the former is a legacy Web Part that supports the old-style DWP Web Part deployment technique available since SharePoint 2003, while the latter uses the syntax of the new WEBPART deployment files available since SharePoint 2010.

Important

You can insert and configure a Web Part instance within a Web Part page and then export it via the standard UI of SharePoint. The resulting file will contain all the XML information to support the configuration made through the UI. Now you can copy and paste this XML into an XML element file, having your Web Part properly configured in the project, without manually writing all the elements and attributes.

The File element supports some other child elements. For example, it supports the View child element, which can be used to instantiate a ListView into the target Web Part page. Additionally, it supports the WebPartConnection element to connect Web Parts directly during the provisioning process.

Keep in mind that extending a site using custom pages and custom content directly deployed into the content database is a habit that Microsoft started to discourage with SharePoint 2013. In fact, you should use the new app model available in SharePoint 2013, which Part III of this book, “Developing SharePoint apps,” discusses.

Status bar and notification area

Found in the default master pages of SharePoint, the status bar and the notification area features are based on JavaScript code and a bit of extra markup. You can implement these tools within your pages easily with two JSOM classes. The SP.UI.Notify class manages the notification area, and the SP.UI.Status class manages the status bar. Table 12-8 describes the methods of the SP.UI.Notify class.

Table 12-8. The methods offered by the SP.UI.Notify class

Method

Description

addNotification

Used to add a notification to the notification area. Requires the text of the notification and a Boolean argument to specify if the notification will stay on the page until explicitly removed. addNotification returns an ID identifying the notification.

removeNotification

Removes a notification from the notification area. Requires the ID of the notification to remove.

To add a notification to the notification area, use the following:

var notifyId = SP.UI.Notify.addNotification("This is a Notification!", true);

To remove the notification, use this:

SP.UI.Notify.removeNotification(notifyId);

Table 12-9 describes the methods provided by the SP.UI.Status class.

Table 12-9. The methods offered by the SP.UI.Status class

Method

Description

addStatus

Adds a status to the status bar. Returns an ID identifying the status.

appendStatus

Appends text to an existing status message in the status bar.

removeAllStatus

Removes all the status messages from the status bar and hides the status bar.

removeStatus

Removes a status message from the status bar. Requires the ID of the status message that is being removed.

setStatusPriColor

Configures the color of the status bar.

updateStatus

Updates a status message. Requires the ID of the status message that is being updated.

To add a status message and turn the status bar red, for example, use the following code:

var statusId = SP.UI.Status.addStatus("Critical Status!");
SP.UI.Status.setStatusPriColor(statusId, 'red'),

To remove the status message, you use this:

SP.UI.Status.removeStatus(statusId);

You can use these classes and methods whenever you need to interact with the end user, using the standard notification tools provided by SharePoint 2013. For example, the code in Source code for a ribbon that archives one or more items with a content type of DevLeapInvoice used the notification area to inform the end user about the process of archiving invoices. In The code of a custom ribbon tab that uses the SP.UI.Notify and SP.UI.Status classes, a custom ribbon tab provides four commands to show and hide a notification message, as well as to show and hide a status message.

Take a look again at the last CustomAction element with a value of ScriptLink for the Location attribute. Notice that it instructs the SharePoint environment to include into the page the scripting code declared in the ScriptBlock attribute. As mentioned in Table 12-1, you can also reference an external script file, declaring the ScriptSrc attribute instead of the ScriptBlock attribute.

Dialog framework

Finally, you can extend the UI using the dialog framework of SharePoint 2013, which is provided by the class SP.UI.ModalDialog of the JSOM. Through this class, you can show pages inside modal dialog windows, and you can also pass information between the dialog window and the main window. Remember, the dialog framework was introduced with SharePoint 2010 and now is available mainly for backward compatibility. In fact, the new UI of SharePoint 2013 is almost free of dialogs, for a better user experience. Table 12-10 presents the main methods of the SP.UI.ModalDialog class.

Table 12-10. The main methods of the SP.UI.ModalDialog class

Method

Description

close

Closes the current dialog window and returns a result value of type SP.UI.DialogResult. The SP.UI.DialogResult type can assume a value of invalid, cancel, or OK.

commonModalDialogClose

Closes a modal dialog and returns a result value of type SP.UI.DialogResult and a custom return value of type Object. The SP.UI.DialogResult type can assume value of invalid, cancel, or OK.

commonModalDialogOpen

Opens a modal dialog and provides some input arguments, such as the URL of the content to show in the dialog, some options of type SP.UI.DialogOptions, a callback to a return function of type SP.UI.DialogCallback, and some extra arguments of type Object.

OpenPopUpPage

Opens a pop-up dialog page that provides some input arguments, such as the URL of the content to show in the pop-up page, a callback to a return function of type SP.UI.DialogCallback, and the width and height of the pop-up window.

RefreshPage

Reloads the current page for refreshing purposes.

showModalDialog

Shows a modal dialog that provides an input argument of type SP.UI.DialogOptions.

ShowPopupDialog

Shows a pop-up dialog that provides the URL of the content to show in the pop-up window.

showWaitScreenSize

Shows a wait screen that provides some input arguments, such as the title of the window, the message to show while waiting, a callbackFunc delegate to a return function, and the width and height of the window.

showWaitScreenWithNoClose

Does the same thing as showWaitScreenSize but without a close button in the upper-right corner of the window. This kind of window must be closed by custom code.

Take a look at how some of these methods work. Suppose that you want to extend the list of invoices, providing a custom ribbon command to open a pop-up window for changing the status of an item. Aside from the ribbon command definition, which by now should be familiar to you, consider the scripting code defined in The scripting code used to show a modal dialog for changing the status of an invoice that shows a custom application page to manage the invoice status.

The scripting code used to show a modal dialog for changing the status of an invoice demonstrates that the custom function openChangeStatusDialog creates a variable of type SP.UI.DialogOptions and provides it to the SP.UI.ModalDialog.showModalDialog method. The SP.UI.DialogOptions class is made of some members that are useful when creating a dialog window. These members are

  • url. The URL of the resource to load in the dialog window.

  • html. Used this to include HTML content that you want to display in the dialog window (in case you don’t want to provide a URL). The content must be provided as a DOM graph of nodes and not as a simple text value.

  • title. The title of the dialog window.

  • args. Optional arguments that can be passed to the dialog window.

  • width. The width of the dialog window.

  • height. The height of the dialog window.

  • x. The x-coordinate location of the upper-left corner of the dialog window.

  • y. The y-coordinate location of the upper-left corner of the dialog window.

  • autoSize. A Boolean value that specifies whether the dialog framework will handle autosizing of the dialog window, based on its content.

  • allowMaximize. A Boolean value that specifies whether the dialog window can be maximized.

  • showMaximized. A Boolean value that specifies whether the dialog window will be opened maximized or not.

  • showClose. A Boolean value that specifies whether the Close button will be shown or not.

  • dialogReturnValueCallback. A delegate to a callback function to invoke when the dialog window will be closed.

The callback function receives a result argument that allows determining whether the end user clicked the Cancel button or the OK button to close the dialog. In addition, it also takes a returnValue argument, in case the dialog window returns something to the main window. Notice that the code in The scripting code used to show a modal dialog for changing the status of an invoice defines the target URL of the dialog window, including in that URL the value of the ListId property of the current list and the ItemId property of the currently selected item, read using the Client-Side Object Model (CSOM). Figure 12-11 shows the dialog window in action.

A screen shot of the dialog window for changing the status of the currently selected invoice. The dialog window, which was automatically sized based on its content, is centered on the screen with all the other content grayed out in the background.

Figure 12-11. The dialog window to change the Status field of an invoice.

The target page is available in the source code samples, but it will not be explained here in detail because it is a standard application page, just like the one in The source code of the page SampleContentPage.aspx provisioned in A Module feature used to deploy a content page on a SharePoint site However, one particularly interesting piece of code of the DevLeapInvoiceChangeStatusDialog.aspx page opened in the dialog window is the script used to close the dialog window itself, which gives feedback to the parent page. The scripting code used to show a modal dialog for changing the status of an invoice illustrates that code excerpt.

Notice that the current SPContext provides a property named IsPopUI to check if the current page is loaded in a pop-up dialog environment. If it is, the page writes to the ASP.NET Response object a small piece of JavaScript code to close the dialog, returning a status of SP.UI.DialogResult.OK (which has a value of 1) and the value selected by the end user for the Status field.

Summary

This chapter covered a lot of information about how to customize and extend the native SharePoint UI, and focused mainly on on-premises solutions. In particular, it described how to create features of type CustomAction, CustomActionGroup, and HideCustomAction. It discussed how to create custom ribbon commands and tabs using the new ribbon model provided by SharePoint 2010. It also discussed using the JSOM to implement the logic of your custom commands. You learned how to deploy content by using Module features so you can provision images, custom content pages, and custom application pages, as well as Web Part pages and items in galleries. Finally, you saw how to work with the notification area, the status bar, and the dialog framework. You can also use some of these techniques while developing SharePoint 2013 apps, in particular when they use the JSOM.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset