20489B ENU TrainerHandbook
20489B ENU TrainerHandbook
20489B ENU TrainerHandbook
20489B
Developing Microsoft® SharePoint® Server
2013 Advanced Solutions
MCT USE ONLY. STUDENT USE PROHIBITED
ii Developing Microsoft SharePoint Server 2013 Advanced Solutions
Information in this document, including URL and other Internet Web site references, is subject to change
without notice. Unless otherwise noted, the example companies, organizations, products, domain names,
e-mail addresses, logos, people, places, and events depicted herein are fictitious, and no association with
any real company, organization, product, domain name, e-mail address, logo, person, place or event is
intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the
user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in
or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical,
photocopying, recording, or otherwise), or for any purpose, without the express written permission of
Microsoft Corporation.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property
rights covering subject matter in this document. Except as expressly provided in any written license
agreement from Microsoft, the furnishing of this document does not give you any license to these
patents, trademarks, copyrights, or other intellectual property.
The names of manufacturers, products, or URLs are provided for informational purposes only and
Microsoft makes no representations and warranties, either expressed, implied, or statutory, regarding
these manufacturers or the use of the products with any Microsoft technologies. The inclusion of a
manufacturer or product does not imply endorsement of Microsoft of the manufacturer or product. Links
may be provided to third party sites. Such sites are not under the control of Microsoft and Microsoft is not
responsible for the contents of any linked site or any link contained in a linked site, or any changes or
updates to such sites. Microsoft is not responsible for webcasting or any other form of transmission
received from any linked site. Microsoft is providing these links to you only as a convenience, and the
inclusion of any link does not imply endorsement of Microsoft of the site or the products contained
therein.
© 2013 Microsoft Corporation. All rights reserved.
Released: 11/2013
MCT USE ONLY. STUDENT USE PROHIBITED
MICROSOFT LICENSE TERMS
MICROSOFT INSTRUCTOR-LED COURSEWARE
These license terms are an agreement between Microsoft Corporation (or based on where you live, one of its
affiliates) and you. Please read them. They apply to your use of the content accompanying this agreement which
includes the media on which you received it, if any. These license terms also apply to Trainer Content and any
updates and supplements for the Licensed Content unless other terms accompany those items. If so, those terms
apply.
BY ACCESSING, DOWNLOADING OR USING THE LICENSED CONTENT, YOU ACCEPT THESE TERMS.
IF YOU DO NOT ACCEPT THEM, DO NOT ACCESS, DOWNLOAD OR USE THE LICENSED CONTENT.
If you comply with these license terms, you have the rights below for each license you acquire.
1. DEFINITIONS.
a. “Authorized Learning Center” means a Microsoft IT Academy Program Member, Microsoft Learning
Competency Member, or such other entity as Microsoft may designate from time to time.
b. “Authorized Training Session” means the instructor-led training class using Microsoft Instructor-Led
Courseware conducted by a Trainer at or through an Authorized Learning Center.
c. “Classroom Device” means one (1) dedicated, secure computer that an Authorized Learning Center owns
or controls that is located at an Authorized Learning Center’s training facilities that meets or exceeds the
hardware level specified for the particular Microsoft Instructor-Led Courseware.
d. “End User” means an individual who is (i) duly enrolled in and attending an Authorized Training Session
or Private Training Session, (ii) an employee of a MPN Member, or (iii) a Microsoft full-time employee.
e. “Licensed Content” means the content accompanying this agreement which may include the Microsoft
Instructor-Led Courseware or Trainer Content.
f. “Microsoft Certified Trainer” or “MCT” means an individual who is (i) engaged to teach a training session
to End Users on behalf of an Authorized Learning Center or MPN Member, and (ii) currently certified as a
Microsoft Certified Trainer under the Microsoft Certification Program.
g. “Microsoft Instructor-Led Courseware” means the Microsoft-branded instructor-led training course that
educates IT professionals and developers on Microsoft technologies. A Microsoft Instructor-Led
Courseware title may be branded as MOC, Microsoft Dynamics or Microsoft Business Group courseware.
h. “Microsoft IT Academy Program Member” means an active member of the Microsoft IT Academy
Program.
i. “Microsoft Learning Competency Member” means an active member of the Microsoft Partner Network
program in good standing that currently holds the Learning Competency status.
j. “MOC” means the “Official Microsoft Learning Product” instructor-led courseware known as Microsoft
Official Course that educates IT professionals and developers on Microsoft technologies.
k. “MPN Member” means an active silver or gold-level Microsoft Partner Network program member in good
standing.
MCT USE ONLY. STUDENT USE PROHIBITED
l. “Personal Device” means one (1) personal computer, device, workstation or other digital electronic device
that you personally own or control that meets or exceeds the hardware level specified for the particular
Microsoft Instructor-Led Courseware.
m. “Private Training Session” means the instructor-led training classes provided by MPN Members for
corporate customers to teach a predefined learning objective using Microsoft Instructor-Led Courseware.
These classes are not advertised or promoted to the general public and class attendance is restricted to
individuals employed by or contracted by the corporate customer.
n. “Trainer” means (i) an academically accredited educator engaged by a Microsoft IT Academy Program
Member to teach an Authorized Training Session, and/or (ii) a MCT.
o. “Trainer Content” means the trainer version of the Microsoft Instructor-Led Courseware and additional
supplemental content designated solely for Trainers’ use to teach a training session using the Microsoft
Instructor-Led Courseware. Trainer Content may include Microsoft PowerPoint presentations, trainer
preparation guide, train the trainer materials, Microsoft One Note packs, classroom setup guide and Pre-
release course feedback form. To clarify, Trainer Content does not include any software, virtual hard
disks or virtual machines.
2. USE RIGHTS. The Licensed Content is licensed not sold. The Licensed Content is licensed on a one copy
per user basis, such that you must acquire a license for each individual that accesses or uses the Licensed
Content.
2.1 Below are five separate sets of use rights. Only one set of rights apply to you.
2.2 Separation of Components. The Licensed Content is licensed as a single unit and you may not
separate their components and install them on different devices.
2.3 Redistribution of Licensed Content. Except as expressly provided in the use rights above, you may
not distribute any Licensed Content or any portion thereof (including any permitted modifications) to any
third parties without the express written permission of Microsoft.
2.4 Third Party Programs and Services. The Licensed Content may contain third party programs or
services. These license terms will apply to your use of those third party programs or services, unless other
terms accompany those programs and services.
2.5 Additional Terms. Some Licensed Content may contain components with additional terms,
conditions, and licenses regarding its use. Any non-conflicting terms in those conditions and licenses also
apply to your use of that respective component and supplements the terms described in this agreement.
a. Pre-Release Licensed Content. This Licensed Content subject matter is on the Pre-release version of
the Microsoft technology. The technology may not work the way a final version of the technology will
and we may change the technology for the final version. We also may not release a final version.
Licensed Content based on the final version of the technology may not contain the same information as
the Licensed Content based on the Pre-release version. Microsoft is under no obligation to provide you
with any further content, including any Licensed Content based on the final version of the technology.
b. Feedback. If you agree to give feedback about the Licensed Content to Microsoft, either directly or
through its third party designee, you give to Microsoft without charge, the right to use, share and
commercialize your feedback in any way and for any purpose. You also give to third parties, without
charge, any patent rights needed for their products, technologies and services to use or interface with
any specific parts of a Microsoft software, Microsoft product, or service that includes the feedback. You
will not give feedback that is subject to a license that requires Microsoft to license its software,
technologies, or products to third parties because we include your feedback in them. These rights
survive this agreement.
c. Pre-release Term. If you are an Microsoft IT Academy Program Member, Microsoft Learning
Competency Member, MPN Member or Trainer, you will cease using all copies of the Licensed Content on
the Pre-release technology upon (i) the date which Microsoft informs you is the end date for using the
Licensed Content on the Pre-release technology, or (ii) sixty (60) days after the commercial release of the
technology that is the subject of the Licensed Content, whichever is earliest (“Pre-release term”).
Upon expiration or termination of the Pre-release term, you will irretrievably delete and destroy all copies
of the Licensed Content in your possession or under your control.
MCT USE ONLY. STUDENT USE PROHIBITED
4. SCOPE OF LICENSE. The Licensed Content is licensed, not sold. This agreement only gives you some
rights to use the Licensed Content. Microsoft reserves all other rights. Unless applicable law gives you more
rights despite this limitation, you may use the Licensed Content only as expressly permitted in this
agreement. In doing so, you must comply with any technical limitations in the Licensed Content that only
allows you to use it in certain ways. Except as expressly permitted in this agreement, you may not:
access or allow any individual to access the Licensed Content if they have not acquired a valid license
for the Licensed Content,
alter, remove or obscure any copyright or other protective notices (including watermarks), branding
or identifications contained in the Licensed Content,
modify or create a derivative work of any Licensed Content,
publicly display, or make the Licensed Content available for others to access or use,
copy, print, install, sell, publish, transmit, lend, adapt, reuse, link to or post, make available or
distribute the Licensed Content to any third party,
work around any technical limitations in the Licensed Content, or
reverse engineer, decompile, remove or otherwise thwart any protections or disassemble the
Licensed Content except and only to the extent that applicable law expressly permits, despite this
limitation.
5. RESERVATION OF RIGHTS AND OWNERSHIP. Microsoft reserves all rights not expressly granted to
you in this agreement. The Licensed Content is protected by copyright and other intellectual property laws
and treaties. Microsoft or its suppliers own the title, copyright, and other intellectual property rights in the
Licensed Content.
6. EXPORT RESTRICTIONS. The Licensed Content is subject to United States export laws and regulations.
You must comply with all domestic and international export laws and regulations that apply to the Licensed
Content. These laws include restrictions on destinations, end users and end use. For additional information,
see www.microsoft.com/exporting.
7. SUPPORT SERVICES. Because the Licensed Content is “as is”, we may not provide support services for it.
8. TERMINATION. Without prejudice to any other rights, Microsoft may terminate this agreement if you fail
to comply with the terms and conditions of this agreement. Upon termination of this agreement for any
reason, you will immediately stop all use of and delete and destroy all copies of the Licensed Content in
your possession or under your control.
9. LINKS TO THIRD PARTY SITES. You may link to third party sites through the use of the Licensed
Content. The third party sites are not under the control of Microsoft, and Microsoft is not responsible for
the contents of any third party sites, any links contained in third party sites, or any changes or updates to
third party sites. Microsoft is not responsible for webcasting or any other form of transmission received
from any third party sites. Microsoft is providing these links to third party sites to you only as a
convenience, and the inclusion of any link does not imply an endorsement by Microsoft of the third party
site.
10. ENTIRE AGREEMENT. This agreement, and any additional terms for the Trainer Content, updates and
supplements are the entire agreement for the Licensed Content, updates and supplements.
12. LEGAL EFFECT. This agreement describes certain legal rights. You may have other rights under the laws
of your country. You may also have rights with respect to the party from whom you acquired the Licensed
Content. This agreement does not change your rights under the laws of your country if the laws of your
country do not permit it to do so.
13. DISCLAIMER OF WARRANTY. THE LICENSED CONTENT IS LICENSED "AS-IS" AND "AS
AVAILABLE." YOU BEAR THE RISK OF USING IT. MICROSOFT AND ITS RESPECTIVE
AFFILIATES GIVES NO EXPRESS WARRANTIES, GUARANTEES, OR CONDITIONS. YOU MAY
HAVE ADDITIONAL CONSUMER RIGHTS UNDER YOUR LOCAL LAWS WHICH THIS AGREEMENT
CANNOT CHANGE. TO THE EXTENT PERMITTED UNDER YOUR LOCAL LAWS, MICROSOFT AND
ITS RESPECTIVE AFFILIATES EXCLUDES ANY IMPLIED WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
14. LIMITATION ON AND EXCLUSION OF REMEDIES AND DAMAGES. YOU CAN RECOVER FROM
MICROSOFT, ITS RESPECTIVE AFFILIATES AND ITS SUPPLIERS ONLY DIRECT DAMAGES UP
TO US$5.00. YOU CANNOT RECOVER ANY OTHER DAMAGES, INCLUDING CONSEQUENTIAL,
LOST PROFITS, SPECIAL, INDIRECT OR INCIDENTAL DAMAGES.
It also applies even if Microsoft knew or should have known about the possibility of the damages. The
above limitation or exclusion may not apply to you because your country may not allow the exclusion or
limitation of incidental, consequential or other damages.
Please note: As this Licensed Content is distributed in Quebec, Canada, some of the clauses in this
agreement are provided below in French.
Remarque : Ce le contenu sous licence étant distribué au Québec, Canada, certaines des clauses
dans ce contrat sont fournies ci-dessous en français.
EXONÉRATION DE GARANTIE. Le contenu sous licence visé par une licence est offert « tel quel ». Toute
utilisation de ce contenu sous licence est à votre seule risque et péril. Microsoft n’accorde aucune autre garantie
expresse. Vous pouvez bénéficier de droits additionnels en vertu du droit local sur la protection dues
consommateurs, que ce contrat ne peut modifier. La ou elles sont permises par le droit locale, les garanties
implicites de qualité marchande, d’adéquation à un usage particulier et d’absence de contrefaçon sont exclues.
EFFET JURIDIQUE. Le présent contrat décrit certains droits juridiques. Vous pourriez avoir d’autres droits
prévus par les lois de votre pays. Le présent contrat ne modifie pas les droits que vous confèrent les lois de votre
pays si celles-ci ne le permettent pas.
Acknowledgments
Microsoft Learning wants to acknowledge and thank the following for their contribution toward
developing this title. Their effort at various stages in the development has ensured that you have a good
classroom experience.
Contents
Module 1: Creating Robust and Efficient Apps for SharePoint
Lesson 1: Apps for SharePoint 1-2
Lesson 2: Communicating with SharePoint from an App 1-9
Lesson 3: Authenticating and Authorizing Apps for SharePoint 1-21
Lesson 4: Designing Apps for Performance 1-32
Lab: Monitoring SharePoint Health Scores 1-37
Course Description
This course teaches students how to apply their core SharePoint development skills to more advanced
SharePoint development projects. Students learn how to develop solutions and apps that interact with the
key SharePoint 2013 workloads, including the search service, enterprise content management
functionality, Business Connectivity Services, social functionality and user profiles, and web content
management features. Students also learn more advanced SharePoint development techniques such as
how to optimize SharePoint code and how to monitor and troubleshoot custom SharePoint components.
Audience
This course is intended for professional developers who develop solutions for SharePoint products and
technologies in a team-based, medium-sized to large development environment. The course is ideally
suited to SharePoint developers who have gained some experience with SharePoint 2013 and who are
looking to build on their existing skills.
The ideal candidate is a technical lead with at least four two years of SharePoint and web development
experience. The candidate is responsible for designing custom code for projects that are deployed to or
interact with SharePoint environments. This includes:
Student Prerequisites
This course requires that you meet the following prerequisites:
A basic understanding of how to create, deploy, and manage apps for SharePoint.
A working knowledge of using Visual Studio 2010 or Visual Studio 2012 to develop solutions.
A basic working knowledge of client-side web technologies including HTML, CSS, and JavaScript.
Course Objectives
After completing this course, students will be able to:
Build solutions and apps that leverage Managed Metadata Service functionality.
Build and execute search queries from client-side and server-side code.
Customize how search queries are processed and how search results are presented.
Interact with Business Connectivity Services (BCS) data from custom SharePoint solutions.
Configure user profile properties and interact with user profile data.
Course Outline
The course outline is as follows:
Module 1, "Creating Robust and Efficient Apps for SharePoint"
Course Materials
The following materials are included with your kit:
Course Handbook: a succinct classroom learning guide that provides the critical technical
information in a crisp, tightly-focused format, which is essential for an effective in-class learning
experience.
Lessons: guide you through the learning objectives and provide the key points that are critical to
the success of the in-class learning experience.
Labs: provide a real-world, hands-on platform for you to apply the knowledge and skills learned
in the module.
Module Reviews and Takeaways: provide on-the-job reference material to boost knowledge
and skills retention.
Course Companion Content: searchable, easy-to-browse digital content with integrated premium
online resources that supplement the Course Handbook.
Modules: include companion content, such as questions and answers, detailed demo steps and
additional reading links, for each lesson. Additionally, they include Lab Review questions and
answers and Module Reviews and Takeaways sections, which contain the review questions and
answers, best practices, common issues and troubleshooting tips with answers, and real-world
issues and scenarios with answers.
Resources: include well-categorized additional resources that give you immediate access to the
most current premium content on TechNet, MSDN®, or Microsoft® Press®.
Student Course files: includes the Allfiles.exe, a self-extracting executable file that contains all
required files for the labs and demonstrations.
Note: For this version of the Courseware, the Allfiles.exe file is not available. However, this file will be
published when the next (B) version of this course is released, and students who have taken this
course will be able to download the Allfiles.exe at that time from the
http://www.microsoft.com/learning/companionmoc site.
Course evaluation: at the end of the course, you will have the opportunity to complete an online
evaluation to provide feedback on the course, training facility, and instructor.
Important: At the end of each lab, you must revert the virtual machines to a snapshot.
You can find the instructions for this procedure at the end of each lab
The following table shows the role of each virtual machine that is used in this course:
Software Configuration
The following software is installed on each VM:
SQL Server 2012 SP1, with the following features installed:
Visio 2013
Course Files
The files associated with the labs in this course are located in the E:\Labfiles folder on the student
computers.
Classroom Setup
Each classroom computer will have the same virtual machine configured in the same way.
Hardware Level 7
64 bit Intel Virtualization Technology (Intel VT) or AMD Virtualization (AMD-V) processor (2.8 GHz
dual core or better recommended)
Dual 500 GB hard disks 7200 RPM SATA or faster (striped)
16GB RAM
DVD drive (dual layer recommended)
Network adapter
Sound card
Dual SVGA 17-inch or larger monitors supporting 1440x900 minimum resolution
Microsoft Mouse or compatible pointing device
In addition, the instructor computer must be connected to a projection display device that supports SVGA
1024 x 768 pixels, 16 bit colors.
At this minimum specification, students may experience some delays when completing tasks on the virtual
machine. You can achieve the biggest improvements in performance by running the virtual machine on
solid-state drives (SSDs).
MCT USE ONLY. STUDENT USE PROHIBITED
MCT USE ONLY. STUDENT USE PROHIBITED
1-1
Module 1
Creating Robust and Efficient Apps for SharePoint
Contents:
Module Overview 1-1
Module Overview
Apps for Microsoft® SharePoint® provide a completely new way of developing and distributing custom
functionality for Microsoft SharePoint 2013 deployments. In this module, you will review key aspects of
the apps for SharePoint development platform, including capabilities, packaging and infrastructure, client-
side programming for SharePoint, and app security. You will also learn how to optimize the performance
of your apps.
Objectives
After completing this module, you will be able to:
Describe the apps for SharePoint development platform.
Use the client-side object models and the REST API to communicate with SharePoint.
Lesson 1
Apps for SharePoint
One of the key reasons for creating apps for SharePoint is that they enable you to provide custom
functionality to the widest possible range of SharePoint deployments. Apps for SharePoint are compatible
with both SharePoint Online and on-premises deployments of SharePoint 2013. Apps are also largely self-
contained and are unlikely to have unintended interactions with other SharePoint customizations, which
makes them attractive to both administrators and business users.
If you plan to distribute apps for SharePoint, you need a solid understanding of the platform that
underpins your custom functionality. In this lesson, you will review the hosting models, the packaging
process, and the infrastructure behind apps for SharePoint.
Lesson Objectives
After completing this lesson, you will be able to:
Describe key aspects of the apps for SharePoint development platform.
server—instead, SharePoint-hosted apps must rely on running JavaScript code on the client browser
to drive any custom functionality.
Auto-hosted apps. In an auto-hosted app, the remote web app runs on Windows Azure™. Auto-
hosted apps automatically provision and install any server-side components on Windows Azure every
time the app is installed, and each app installation has its own dedicated instance of the web
application on Azure. An auto-hosted app can also deploy declarative components to SharePoint, in
the same way as a SharePoint-hosted app. Such apps are referred to as hybrid apps.
Provider-hosted apps. In a provider-hosted app, the web application associated with the app runs on
a remote server, which is either hosted by or at least sourced by the organization that provides the
app. As a result, provider-hosted apps can use any platform as the basis for the web application.
However, the app provider must manage how client data is isolated and managed on the server-side
web application. A provider-hosted app can also deploy declarative components to SharePoint, in the
same way as a SharePoint-hosted app.
To summarize, although users access apps through a SharePoint web page, the app logic actually runs
anywhere except on the SharePoint server.
Additional Reading: For more information on hosting models, see Choose patterns for
developing and hosting your app for SharePoint at
http://go.microsoft.com/fwlink/?LinkId=320734
When you install an app on a particular SharePoint site, the app web is created as a subsite of the current
site. The current site is then referred to as the host web. By default, an app has full control over all content
in the app web. However, the app must explicitly request permissions to access content in the host web or
elsewhere in the SharePoint farm.
Additional Reading: For more information on app webs and host webs, including app
prefixes and app IDs, see Host webs, app webs, and SharePoint components in SharePoint 2013 at
http://go.microsoft.com/fwlink/?LinkId=320735
Launching an App
You can make app functionality available to users in three different ways:
Through a full page app. In this case, users launch the app from the Site Contents page on the host
web or from a link elsewhere on the SharePoint site.
Through an app part. In this case, users can add the app to a SharePoint page as a web part.
SharePoint displays content from the app in an iFrame.
Through a custom action. In this case, users launch the app from a custom action. The custom action
is deployed on the host web, and consists of either a button on the ribbon or a menu item on the Edit
Control Block (ECB). You can use this option to display an app page in a SharePoint dialog box.
MCT USE ONLY. STUDENT USE PROHIBITED
1-4 Creating Robust and Efficient Apps for SharePoint
All apps implement a full-page user interface, but app parts and custom actions are optional.
The start page URL for the app. This is the page that SharePoint will display when a user launches the
app. This could be a page hosted on the app web (in the case of SharePoint-hosted apps) or on a
remote server (in the case of auto-hosted or provider-hosted apps).
The properties of the app. These properties include the title, the version number, and supported
locales.
The permissions required by the app. The app manifest must explicitly define the level of access it
requires to any SharePoint content or services beyond the app web.
A list of prerequisites. The app manifest must identify any SharePoint services and features that it
requires in order to operate.
An app principal identifier. If the app is auto-hosted or provider-hosted, the app manifest must
include an identifier that enables SharePoint to authenticate and authorize the app principal.
Any pages and resources that must be deployed to the app web.
Any web-scoped features that must be deployed to the host web to provision custom actions or app
parts.
In auto-hosted SharePoint apps, Web Deploy packages and Data Tier Application Packages
(DACPACs) for deployment to Windows Azure.
Essentially, the app package contains only those components of the complete solution that SharePoint
requires. For example, if you create a provider-hosted app, the app package would contain no
components of your server-side web application.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 1-5
Demonstration Steps
1. Demonstrate the contents of the SiteSuggestionsApp project to the students. Point out the
following features:
Site Columns
Content Types
Lists
2. Show the students the contents of the app manifest file. Highlight the Start page setting.
3. Start the app in debugging mode and then log on with the following credentials:
Password: Pa$$w0rd
4. Create a new suggestion and like your new suggestion.
9. Point out that, among other things, the app package contains an app manifest file (AppManifest.xml)
and a SharePoint solution package (SiteSuggestionsApp.wsp).
App Catalogs
An App Catalog is a specialized SharePoint 2013
site collection. By default, an App Catalog contains
two document libraries: one for apps for
SharePoint, and one for apps for Office. In an on-
premises installation of SharePoint 2013, you can
create one App Catalog for each web application in
your deployment. In Office 365, each tenancy includes a single App Catalog. You publish an app to the
App Catalog by uploading the app package to the relevant document library. Users of sites within the
same web application (SharePoint 2013 on-premises) or the same tenancy (Office 365) can browse the
App Catalog and install apps, providing the user has been granted sufficient permissions.
Uniquely identifiable app installations. Because multiple installations of the same app may coexist in
one SharePoint deployment, SharePoint must be able to identify which specific app installation
submitted any given request.
Apps for SharePoint achieve this isolation by associating a unique security identifier and a unique DNS
domain with each individual app installation.
Installation Scopes
The apps for SharePoint framework relies on the concept of tenancy. In hosted environments, such as
Office 365, multiple customers, or tenants, share the same physical platform and the same collection of
services. The tenancy provides a logical isolation between the sites and data that belong to different
customers, to ensure that sensitive data belonging to one customer is not shared inadvertently with
another customer. In Office 365, the tenancy is the scope of your subscription—it encompasses all of your
site collections. If you deploy SharePoint 2013 on premises for the exclusive use of your own organization,
SharePoint creates a single tenancy that encompasses the entire farm.
When an administrator installs an app for SharePoint, he or she can install the app at the following scopes:
Site scope. When you install an app into a site, there is a single host web. The app web is created as a
sub-site of the host web. The app is available only from within that host web. If you want to use the
app in another host web, you must install it a second time. Each installation of the app has a unique
security identity and is granted separate access permissions.
Tenancy scope. When you install an app at the tenancy scope, the app web is created within the App
Catalog site collection. The app installation can be accessed from any site in the tenancy. The app has
the same security identity and access permissions, regardless of from which site the app is launched.
App Domains
SharePoint creates a unique DNS domain for each installation of an app. This DNS domain takes the
following form:
For example:
http://contosotenant-aa46c3ffd61233.contosoapps.com
The app prefix. This is configured at the tenancy scope, either through PowerShell or through the
Central Administration website.
The unique app ID. SharePoint generates a unique ID for each installation of an app.
The app web hosting domain. This is a global, top-level domain for all your app installations.
To support isolation and prevent cross-site scripting, Microsoft recommends that you create a unique top-
level domain for your apps. For example, if your top-level domain for SharePoint is contoso.com, you
might create a top-level domain for your SharePoint apps of contosoapps.com.
MCT USE ONLY. STUDENT USE PROHIBITED
1-8 Creating Robust and Efficient Apps for SharePoint
In an Office 365 subscription, these service applications are provisioned and available by default. In an on-
premises installation, an administrator must set up these service applications as part of the farm
configuration process.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 1-9
Lesson 2
Communicating with SharePoint from an App
When you develop apps for SharePoint, you can use three main approaches to communicate with the
SharePoint server. These approaches are the JavaScript object model, the managed client object model,
and the REST API. All of these approaches rely on a web service, client.svc, which SharePoint exposes on
every site. When you use the REST API, you communicate with the client.svc service directly. By contrast,
the JavaScript object model and the managed client object model work by providing client-side proxies
for the client.svc service.
In this lesson, you will review the core programming techniques that you can use with the JavaScript
object model, the managed client object model, and the REST API. You will also review where you can use
each approach, and consider the advantages and disadvantages of these programming models in various
scenarios.
Lesson Objectives
After completing this lesson, you will be able to:
Describe the core concepts behind the SharePoint 2013 REST API.
Perform create, retrieve, update, delete, and query (CRUDQ) operations with the REST API.
Key Concepts
The SharePoint 2013 REST API has various
characteristics that are common to all REST/OData web services:
Data entities are represented by URIs. You identify the object or collection you want to work with by
constructing a URI within the web service URL. For example, to select a list called Discussion you could
use the URI /_api/web/lists/getbytitle('Discussion').
Data operations are mapped to HTTP verbs. You specify the data operation you want to perform (such
as create, retrieve, update, or delete) by using the corresponding HTTP verb (POST, GET, PUT, and
DELETE).
MCT USE ONLY. STUDENT USE PROHIBITED
1-10 Creating Robust and Efficient Apps for SharePoint
Data is exchanged in an OData-compliant format. You can use OData query operators such as $select,
$order, and $filter within your request URLs. The service returns data in either Atom Publishing
Protocol (AtomPub) or JavaScript Object Notation (JSON) format.
You can build on this root service URL to identify specific SharePoint objects and collections. The
following table shows examples of common REST URLs:
URL Description
/_api/web/lists/getbytitle("Invoices")/items?$select=Title,Amount
The following URL skips the first 10 items in the Invoices list and returns the next 10 (for example to
implement paged results):
/_api/web/lists/getbytitle("Invoices")/items?$skip=10&$top=10
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 1-11
Reading Data
To use the REST API to retrieve data, you submit an HTTP GET request. There are two jQuery functions
that are useful when you want to retrieve data from the REST API in JavaScript code:
The $.getJSON() function. This provides a simple and easy-to-use way of requesting and receiving
JSON data.
The $.ajax() function. This provides a more sophisticated way of constructing REST URLs and
submitting requests, for when you need more control over how the request is created.
The following code example shows how to create REST requests and handle the responses by using
JavaScript and jQuery. The first request uses the getJSON() function to retrieve details of the current
website. The second request uses the ajax() function to retrieve details of the current user.
POST. Use the POST verb when you want to create a new item.
PUT. Use the PUT verb when you want to overwrite an existing item. If you use the PUT verb, you
must specify all the properties of the item—both the properties that have changed and the properties
that remain the same.
PATCH. Use the PATCH verb when you want to modify an existing item. If you use the PATCH verb,
you need only specify the properties that you want to change.
MERGE. The MERGE verb performs a similar role to the PATCH verb, but PATCH is used more
frequently by convention.
DELETE. Use the DELETE verb when you want to delete an existing item.
If you want to use anything other than a GET verb, you must use the $.ajax() function to construct your
request.
To perform a create, update, or delete operation, you must include a form digest with your request. The
form digest is a hash of the page content, and is used to prove that the request comes from the original
page as sent from the SharePoint server. To include the form digest with your request, you must:
2. Add the contents of the digest to the X-RequestDigest header in your request.
The following code example shows how to create, update, and delete list items from a Suggestions list on
the SharePoint site:
Whenever you use the JavaScript object model, your first task is to create a client context object. The client
context object—SP.ClientContext in the JavaScript object model—represents the current location of the
user within SharePoint, and is conceptually similar to the server-side SPContext object. You can
instantiate a client context object by calling the SP.ClientContext.get_current method:
The client context object provides the entry point for all JavaScript object model operations. For example:
You use the context.load method to specify objects that you want to retrieve from the server.
You use the context.loadQuery method to specify a LINQ to objects query that you want to execute
on the server.
You use the context.executeQueryAsync method to send the operations you have performed to the
server.
Like most JavaScript functions, the functions in the JavaScript object model use an asynchronous
programming model. None of your operations are sent to the server until you call the
executeQueryAsync method. When you call the executeQueryAsync method, you specify callback
functions to handle the response from the server.
The following code example shows how to load an object into the client context, execute the operation
asynchronously, and then display the results:
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 1-15
You retrieve a reference to the current site collection from the client context object.
You use the context.load method to specify that you want to retrieve the Title and
ServerRelativeUrl properties of the site collection object from the server.
You use the executeQueryAsync method to send the query to the server.
You use the onSuccess and onFailure callback functions to handle the response from the server.
You use the $(document).ready function to run your code when the page has finished loading.
Note: The code example in this topic uses the module pattern for encapsulating JavaScript
code. The module pattern is described in the next topic.
Strict JavaScript
Strict JavaScript was introduced in version 5 of the ECMAScript language specification. Essentially, strict
JavaScript is a more robust variant of JavaScript that prevents a wide range of common programming
errors. It achieves this by enforcing more rigorous programming rules and by throwing errors where code
would otherwise fail silently.
Script scope. To apply strict mode to an entire JavaScript file, add the statement 'use strict'; as the
first line of the script.
Function scope. To apply strict mode to an individual function, add the statement 'use strict'; in the
body of the function before any other statements.
Note: Although invoking strict mode at the script scope is less time-consuming, it can
cause unexpected behaviors if you concatenate strict mode scripts and non-strict mode scripts.
Strict mode changes the syntax and execution of JavaScript in a variety of ways. For example, strict mode
will:
Prevent the value of the this keyword from defaulting to the global window object.
Prevent you from using reserved keywords as names for functions or variables.
Additional Reading: For more information on strict mode, see Strict Mode (JavaScript) at
http://go.microsoft.com/fwlink/?linkId=320736
Encapsulating Code
By default, JavaScript functions and variables are added to the global namespace. The global namespace is
a container for all the JavaScript associated with a web page, and is represented by the window object.
When you write JavaScript code, you should avoid adding functions or variables to the global namespace.
This can lead to naming conflicts when pages are rendered and can make code difficult to debug. Instead,
you should create a custom namespace within the global namespace, and add your functions and
variables to the custom namespace. The following code shows how to create a custom namespace:
Within your custom namespace, there are various patterns you can use to encapsulate your code. In
object-oriented programming, encapsulation refers to the concept of creating a container or object that
represents both a data entity and the methods or functions that operate on the data entity. Encapsulation
is especially important for JavaScript developers. A web page will often load multiple scripts, in many
cases created by different people or different organizations, and encapsulation helps to reduce
unexpected interactions or conflicts.
One of the most popular encapsulation patterns for JavaScript is the module pattern. When you use the
module pattern, you use a function to encapsulate an entity and any logic associated with the entity. You
can use the module pattern to associate both private and public members with your entity, and to create
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 1-17
multiple instances of the same entity. This makes the programming experience familiar to users of object-
oriented programming languages such as Visual C#.
The following code example shows how to use the module pattern to encapsulate operations on a
Suggestions list on a SharePoint site:
Contoso.SuggestionsList = function () {
createSuggestion = function (subject, feedback) {
//Get the client context and suggestions list
var context = new SP.ClientContext.get_current();
var list = context.get_web().get_lists().getByTitle("Suggestions");
context.load(list);
//Create the new item and set fields.
var listItemCreationInfo = new SP.ListItemCreationInformation();
var newItem = list.addItem(listItemCreationInfo);
newItem.set_item("Subject", subject);
newItem.set_item("Feedback", feedback);
//Remember to call update before executing the query
newItem.update();
context.executeQueryAsync(onSuccess, onError);
},
updateSuggestion = function (id, subject, feedback) {
//Get the client context and suggestions list
var context = new SP.ClientContext.get_current();
var list = context.get_web().get_lists().getByTitle("Suggestions");
context.load(list);
var itemToUpdate = list.getItemById(id);
itemToUpdate.set_item("Subject", subject);
itemToUpdate.set_item("Feedback", feedback);
//Remember to call update before executing the query
newItem.update();
context.executeQueryAsync(onSuccess, onError);
},
removeItem = function (id) {
//Get the client context and suggestions list
var context = new SP.ClientContext.get_current();
var list = context.get_web().get_lists().getByTitle("Suggestions");
context.load(list);
//Get the item from its ID
var itemToDelete = list.getItemById(id);
//delete it before executing the query
itemToDelete.deleteObject();
context.executeQueryAsync(onSuccess, onError);
},
onSuccess = function () {
alert("The operation completed successfully);
},
onError = function (sender, args) {
alert("The operation caused an unexpected error);
};
return {
Create: createSuggestion,
Update: updateSuggestion,
Delete: removeSuggestion
};
} ();
In the previous example, all the logic is encapsulated in a function named SuggestionsList within the
Contoso namespace. The return values of the function map public members to internal members. For
example, to add a new suggestion to the list, you could use the following code:
MCT USE ONLY. STUDENT USE PROHIBITED
1-18 Creating Robust and Efficient Apps for SharePoint
For a more sophisticated approach to error handling, the JavaScript object model provides a mechanism
that you can use to send error handling instructions to the server. This mechanism is provided by the
ExceptionHandlingScope object. The ExceptionHandlingScope object enables you to present your
query logic as a try-catch-finally block. When your query is submitted to the server:
1. The server will first try to execute the instructions in the try block.
2. If an exception occurs, the server will execute the instructions in the catch block.
3. Regardless of whether or not an exception occurred, the server will execute the instructions in the
finally block.
The following code example shows how to structure a query by using the ExceptionHandlingScope
object:
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 1-19
Like the JavaScript object model, the first task whenever you use the managed client object model is to
retrieve a client context object. The following code example shows how to create and use a client context
object by using the managed client object model in C#:
MCT USE ONLY. STUDENT USE PROHIBITED
1-20 Creating Robust and Efficient Apps for SharePoint
You use the appWebUrl token to instantiate the client context object. For remote-hosted apps,
SharePoint provides the value of the appWebUrl token in the SPAppWebUrl page request
parameter.
You retrieve a reference to the current site collection from the client context object.
You use the context.load method to specify that you want to retrieve the Title and
ServerRelativeUrl properties of the site collection object from the server, by providing a lambda
expression.
You use the ExecuteQuery method to send the query synchronously to the server.
You can access resources in the app web from .NET managed client object model in the remote web
without using tokens and without permission requests to resources in the host web.
Like the JavaScript object model, the managed client object model enables you to use exception-handling
scope objects to send error-handling instructions to the server with your queries.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 1-21
Lesson 3
Authenticating and Authorizing Apps for SharePoint
As your apps for SharePoint become more sophisticated, the authentication and authorization
requirements of your apps are likely to become more demanding. If your app needs access to SharePoint
data beyond the app web, you will need to configure permission requests in the app manifest file. If you
create an auto-hosted or provider-hosted app, you will need to register an app principal and configure a
trust relationship with the SharePoint server farm. You will also need to work with tokens and token
helper classes when you communicate with SharePoint. Finally, if you want to access data across domain
boundaries from code running in a browser window, you will need to understand how SharePoint can
help you to circumvent browser restrictions designed to prevent cross-site scripting (XSS) attacks.
Lesson Objectives
After completing this lesson, you will be able to:
Describe the security model for apps for SharePoint.
Describe how to register an app principal for auto-hosted and provider-hosted apps.
Configure an app manifest file to request SharePoint permissions.
Use the cross-domain library and the web proxy to communicate across domain boundaries.
Client secret. If the app is remote-hosted, the app principal will contain an encryption key for
encrypting security tokens.
MCT USE ONLY. STUDENT USE PROHIBITED
1-22 Creating Robust and Efficient Apps for SharePoint
Remote host domain. If the app is remote-hosted, the app principal will contain the DNS domain of
the remote host.
Redirect URL. This is an optional setting that enables remote-hosted apps to request permissions
during operations.
When you install a SharePoint app, the app principal is registered with the SharePoint tenancy. This
creates an app identifier, which is a unique string that includes the app client ID and the tenancy ID. When
SharePoint assigns a permission to your app, it stores the permission with the app identifier. This means
that each app permission in SharePoint is specific to one installation of one app.
In a SharePoint hosted app or an auto-hosted app, SharePoint automatically creates an app principal and
an app identifier every time a user installs your app. Although you must understand app principals for
these types of apps, you do not need to create them yourself.
App Permissions
When you install an app, the app automatically has full control permissions on the app web. However, the
app does not have any permissions on the host web. If you are creating an app that requires access to
content or services on SharePoint, you must add permission requests to the app manifest file. When a user
installs the app, SharePoint will prompt them to grant the requested permissions to the app. This is an all
or nothing choice: The user must either grant all the requested permissions, or abort the installation.
A user can only grant permissions to an app if they have the requested permissions themselves. For
example, if a user has read-only access to a list, he or she cannot grant an app write access to the list.
App Authentication
Typically, when SharePoint receives a request, it
must first authenticate the user. It uses an
authentication provider (such as Active Directory
Domain Services) to verify the credentials of the
user, and it issues a security assertion markup
language (SAML) token to the user. The client
browser or application submits the SAML token
with subsequent requests as proof of the user's
identity.
The request targets a service endpoint within an app domain. This indicates that the request originates
from an app, as cross-site scripting restrictions will prevent service calls from outside the app domain.
The request includes an app-specific type of security token—an access token—instead of a SAML token.
This indicates that the request originates from a remote-hosted app.
SharePoint uses three different authentication techniques for apps for SharePoint. The three types of app
authentication are:
Note: App authentication is only required for calls to the client.svc service—in other words,
calls that originate from the client-side object model (CSOM) or the REST API. Regular user
authentication is used in the case of standard HTTP requests.
The service call targets a service endpoint within an app web domain, and
The service call includes a SAML token for an authenticated user.
In this case, SharePoint can establish the identity of the app internally. The identity of the app is added to
the call context, along with the identity of the user, where it can be used for authorization.
In these scenarios, you must configure the app to use external authentication. When an app is configured
to use external authentication, an external system must verify the identity of the user and the app. This
external system generates a context token that is sent to SharePoint with the service call. The context
token states both the identity of the user and the identity of the app (or less commonly, just the identity
of the app).
External authentication relies on a trust relationship between the SharePoint server and the external
system that issues context tokens. One approach to providing this trust relationship is to use Windows
Azure Access Control Service (ACS), which is an OAuth provider. In this case, you must register your app
security principal with ACS so that your app can request access tokens. ACS issues an access token that
contains both the app ID and the user ID, and the app sends this token to SharePoint with the service call.
External authentication with OAuth is typically used for auto-hosted apps. In this case, the trust
relationship between Office 365 and ACS is configured automatically, which makes this approach simple
and effective.
SharePoint-Hosted Apps
When you create a SharePoint-hosted app, the app
will be preconfigured to use internal authentication.
You do not have to change this configuration.
However, you should understand how the
configuration is represented in the app manifest file.
The following code example shows how SharePoint-hosted apps are configured to use internal
authentication in the app manifest file:
Auto-Hosted Apps
When you create an auto-hosted app for SharePoint, the app principal is created and registered with
SharePoint automatically. The app tells SharePoint to create and register an app principal automatically by
including an AutoDeployedWebApplication element in the app manifest file.
The following code example shows how auto-hosted apps are configured to create and register an app
principal automatically:
When you create an auto-hosted app in Visual Studio 2012, Visual Studio adds two configuration settings
to the web.config file for the remote web. These are the client ID and the client secret. The values in the
web.config file must match the corresponding values in the app principal.
The following example shows how the client ID and the client secret are configured in the remote
web.config file:
Provider-Hosted Apps
When you create a provider-hosted app, you must register the app principal manually with the SharePoint
farm. You can do this in two ways:
Use the AppRegNew.aspx page. This is an application page that SharePoint exposes on every site
through the LAYOUTS directory. The page prompts you for a client ID, a client secret, a title, an app
domain, and an optional redirect URL. The page can also generate a client ID and a client secret for
you, if required.
Use Windows PowerShell. You can use the Register-SPAppPrincipal cmdlet to register your app
principal with SharePoint.
You must also have configured a S2S trust relationship between the SharePoint server and the remote app
host, as described earlier in this lesson.
When you configure the app manifest file for a provider-hosted app, you must add a
RemoteWebApplication element to the AppPrincipal element. The RemoteWebApplication element
must also include the client ID of the app principal.
The following code example shows how to configure the app principal in the app manifest file for a
provider-hosted app:
You must also add the ClientId and ClientSecret settings to the remote web.config file, in the same way
as you would for an auto-hosted app.
Requesting Permissions
Any app that creates an app web, such as a
SharePoint-hosted app, has full access to all the
resources in that app web. However, to access
resources in the host web or elsewhere on
SharePoint, the app must request the required
permissions during installation. These permissions
are explained to the user, who can choose to trust
the app and grant all the requested permissions, or
to cancel the installation.
You can use the following Scope values to request access to SharePoint data:
The lists on the host web http://sharepoint/content/sitecoll Read, Write, Manage, FullControl
ection/web/list
You can use the following Scope values to request access to SharePoint services:
Additional Reading: For a comprehensive list of Scope URI values and the corresponding
available rights, see App permissions in SharePoint 2013 at
http://go.microsoft.com/fwlink/?LinkId=320738
The following code example shows how to use AppPermissionRequest elements to request permissions in
the app manifest file:
<!-- This element requests write access to all lists in the host web -->
<AppPermissionRequest
Right="Write"
Scope="http://sharepoint/content/sitecollection/web/lists" />
<!-- This element requests read access to the properties of the tenancy -->
<AppPermissionRequest
Right="Read"
Scope="http://sharepoint/content/tenant" />
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 1-27
<!-- This element requests search access without authenticating as the app -->
<AppPermissionRequest
Right="QueryAsUserIgnoreAppPrincipal"
Scope="http://sharepoint/search" />
<!-- This element requests write access to a user's social networking microfeed -->
<AppPermissionRequest
Right="Write"
Scope="http://sharepoint/social/microfeed" />
</AppPermissionRequests>
The following code example shows how to use Property elements to refine a permission request:
In this example, the permission request is constrained to only those lists with a base template ID of 101, or
in other words to document libraries, within the host web.
Token Types
SharePoint uses the following types of security
tokens when it communicates with an app:
Context Tokens. Context Tokens are issued by Windows Azure ACS and include user identity, the
tenancy identity, and the URL of the host web. ACS first sends the context token to the SharePoint
host environment. SharePoint then passes the token to the remote web, by including the token in a
form variable named SPAppToken as part of the HTTP POST. Context tokens are issued only by
OAuth providers (in this case, Windows Azure ACS) and are not used in S2S trusts.
Access Tokens. An access token is issued when a client is authenticated. When you submit a request
from a remote app, you must include the access token in the HTTP header to prove that your client is
authenticated. In Visual Studio 2012, the App for SharePoint project template includes a class named
TokenHelper that can help you to work with access tokens.
Refresh Tokens. Like context tokens, refresh tokens are specific to OAuth providers. When ACS issues a
context token, the context token includes a refresh token. When an app needs to authenticate, it
submits the refresh token to ACS. ACS validates the refresh token and issues an access token. An
access token expires 12 hours after it is issued, whereas a refresh token is valid for six months. As such,
you may wish to store refresh tokens—for example, in a database associated with the remote web—
to expedite the authentication process.
The following code example shows how to retrieve a context token and then use it to create a client
context that includes an access token:
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 1-29
// Store the host web URL, which is in the SPHostUrl request parameter.
var hostURL = Page.Request["SPHostUrl"];
The cross-domain library is contained in a file named SP.RequestExecutor.js, which is available from the
SharePoint LAYOUTS directory. You can add this file directly to remote web projects when you want to
use the cross-domain library. The functionality of the library is provided by the SP.RequestExecutor
object. For example, it includes a method named executeAsync that you can use to submit cross-domain
service calls in a similar way to how you would use the jQuery $.ajax method.
The following code example shows how to use the cross-domain library to access SharePoint task list data
from an external domain:
MCT USE ONLY. STUDENT USE PROHIBITED
1-30 Creating Robust and Efficient Apps for SharePoint
Contoso.CDL = function () {
getTasks = function () {
var appweb = // get URL of app web, for example from a query string parameter.
var executor = new SP.RequestExecutor(appweb);
executor.executeAsync(
{
url: appweb +
"/_api/SP.AppContextSite(@target)/web/title?@target='" + hostWebUrl + "'",
method: "GET",
headers: {"Accept": "application/json;odata=verbose"},
success: onSuccess,
error: onError
}
)
},
return {
GetTasks: getTasks
}
} ();
$(document).ready(function () {
Contoso.CDL.GetTasks;
});
The cross-domain library works by using a SharePoint page named AppWebProxy.aspx, which SharePoint
exposes on every site through the LAYOUTS directory. Essentially, the SP.RequestExecutor object creates a
hidden iFrame in the remote web page and loads the AppWebProxy page. It passes the query operations
to the AppWebProxy page in the iFrame, which in turn executes the commands against the app web.
Before you can use the web proxy, you must register the domain of the external service as a trusted
domain in the app manifest file. For example, suppose you want to use a stock pricing service provided by
a partner organization, Northwind Traders. Northwind exposes the service at the URL
http://northwindtraders.com/stock/feed/. Your first task would be to use a RemoteEndpoint element
to register the northwindtraders.com domain as trusted in the app manifest file:
<RemoteEndpoints>
<RemoteEndpoint Url="http://northwindtraders.com" />
</RemoteEndpoints>
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 1-31
When you have registered the domain in the app manifest file, you can then use the web proxy to call the
service from pages in your app.
The following code example shows how to use the web proxy to call a RESTful web service from a web
page:
Contoso.StockProxy = function () {
getData = function () {
var context = SP.ClientContext.get_current();
var proxyRequest = new SP.WebRequestInfo();
proxyRequest.set_url("http://northwindtraders.com/stock/feed/getByClient('Contoso')");
proxyRequest.set_method("GET");
window.Contoso.ResponseDocument = SP.WebProxy.invoke(context, request);
context.executeQueryAsync(onSuccess, onError);
},
return {
GetData: getData
}
} ();
$(document).ready(function () {
Contoso.StockProxy.GetData();
});
MCT USE ONLY. STUDENT USE PROHIBITED
1-32 Creating Robust and Efficient Apps for SharePoint
Lesson 4
Designing Apps for Performance
Because apps for SharePoint are not permitted to run any code on SharePoint servers, app developers can
often be less concerned about how their code impacts the performance of the SharePoint environment.
However, performance and efficiency are still important. Executing queries from client-side code adds to
the demand for server-side resources, and you should avoid overloading servers that are already
experiencing high load. At the same time, you can optimize the user experience by ensuring that your
calls to the server are efficient and minimal. In this lesson, you will learn about a range of techniques that
you can use to improve the performance of apps for SharePoint.
Lesson Objectives
After completing this lesson, you will be able to:
When you develop apps for SharePoint (or any other application that sends requests to SharePoint), a
good practice is to check the server health score before you submit any performance-intensive
operations. SharePoint makes health scores available to clients by including a header named X-
SharePointHealthScore in every HTTP response.
The following code example shows how to retrieve the health score of a SharePoint web application by
using JavaScript and jQuery:
Notice that in this example we request the blank.htm page from the LAYOUTS folder. You can retrieve the
health score by sending an HTTP GET request or an HTTP HEAD request for any SharePoint resource. The
blank.htm page was chosen because it is very small, it does not need to be compiled by the server, and it
is available on every site through the _layouts virtual directory.
http://team.contoso.com/_api/lists/getByTitle('Invoices')/items
The first time your app sends this request, the query is sent to the server. The server responds by
providing a list of items from the Invoices list in JavaScript Object Notation (JSON) format. If the app
sends the same GET request again, the server sends a HTTP 304 (Not Modified) response. This means that
the data has not changed since the last time the browser sent the request, and the browser should
retrieve the data from its local cache.
The following screen capture illustrates how the browser uses a local cache to store responses to AJAX
requests. In this example, an app for SharePoint uses the jQuery ajax method to request a page every five
seconds. On the first request, the server sends an HTTP 200 response that includes the requested page. On
all subsequent requests, the server sends an HTTP 304 response that indicates that the browser already
has the current version of the page.
http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.js
MCT USE ONLY. STUDENT USE PROHIBITED
1-34 Creating Robust and Efficient Apps for SharePoint
This approach provides two key benefits. First, it reduces the load on the SharePoint server (or the remote
web server, in the case of provider-hosted apps), because you no longer need to host or serve the jQuery
library. Second, because many websites share the same CDNs, the jQuery library is more likely to be in the
browser cache already, which further reduces load times.
If you subscribe to a CDN provider, such as the Windows Azure CDN, you can use the CDN to serve your
own static content, such as binary large objects (BLOBs) and CSS files. CDNs typically provide a globally
distributed hosting platform, which means that end users should experience fast load times regardless of
their geographical location.
If you are using the managed client object model, you can use lambda expressions to specify the
properties that you want to retrieve:
// Retrieve only the Title and Description properties of the Web object.
context.Load(web, w => w.Title, w => w.Description);
context.ExecuteQuery();
When you use this approach, your code will throw a null reference exception if you attempt to use the
values of any properties other than those that you have explicitly requested.
If you are using the JavaScript object model, you can specify the properties that you want to retrieve as
string arguments in the load method:
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 1-35
// Retrieve only the Title and Description properties of the Web object.
context.load(this.teamWeb, 'Title', 'Description');
context.executeQueryAsync(onGetPropertiesSucceeded, onGetPropertiesFailed);
}
When you use the REST API to retrieve data, you can use OData operators to specify the properties you
want to retrieve and to apply filters to the data. Any filters that you specify are applied on the server, so
that the server returns the filtered data to the client, rather than the entire data set. For example, suppose
you have a document library that contains invoices on your SharePoint site. You might want to retrieve
the Customer and Amount fields for every item in which the Status field has a value of Outstanding.
Rather than retrieving every item and performing filtering on the client, you can build the filters into the
query URL such that only relevant data is returned:
http://team.contoso.com/_api/web/lists/getbytitle('Invoices')/items$select=C
ustomer,Amount&filter=Status eq 'Outstanding'
If you use collaborative application markup language (CAML) queries to retrieve list items, you can specify
properties and include filtering as part of the CAML expression. When you do this, the filtering takes place
on the server and you are thereby reducing the amount of data you return to the client.
Batching Requests
Both the JavaScript object model and the managed client object model work by sending requests to the
server in batches. Nothing is sent to the server until you call an ExecuteQuery or an ExecuteQueryAsync
method. You can use this behavior to batch several operations into a single request, thereby minimizing
the number of round trips to the server.
The following code example illustrates how you can batch several operations into a single server request:
// Specify that you want to load the title and description of each list.
context.Load(invoices, list => list.Title, list => list.Description);
context.Load(customer, list => list.Title, list => list.Description);
localStorage. You can use this object to store data indefinitely. Data is stored according to origin
(protocol, hostname, and port number) and will not be removed when the window is closed.
sessionStorage. You can use this object to store data for the duration of a session. Data is stored
according to origin, and also by window. For example, if the user browses your app in two different
windows, the browser will use two different session stores. Any data in session storage is deleted
when the user closes the browser window.
In browsers that support HTML5 Web Storage, the localStorage object and the sessionStorage object
are declared in the global namespace. In both the localStorage object and the sessionStorage object,
data is stored as key-value pairs. You can get and set data by using simple getItem and setItem methods
in JavaScript.
The following code example shows how to store and retrieve data by using HTML5 Web Storage with
JavaScript:
Objectives
After completing this lab, you will be able to:
Lab Setup
Estimated Time: 60 minutes
Virtual Machine: 20489B-LON-SP-01
Password: Pa$$w0rd
A warm-up script named WarmUp.ps1 runs automatically when you start the virtual machine. This script
helps to improve the performance of the virtual machine by downloading the home page of the root site
in each site collection on the server. Occasionally this script displays timeout errors; you can ignore these
errors. You should ensure this script has finished running before you start the lab.
3. In Visual Studio 2012, create a new project with the following settings:
a. Use the App for SharePoint 2013 project template.
MCT USE ONLY. STUDENT USE PROHIBITED
1-38 Creating Robust and Efficient Apps for SharePoint
4. In the New app for SharePoint dialog box, configure the app with the following settings:
Note: The Visual Studio 2012 template for an app part is named Client Web Part (Host
Web).
4. Set the description of the app part to Displays the current health score for the SharePoint web
application.
3. Delete the Sample.txt file from the SiteAssets folder in the project.
4. Add the jquery-ui.css file from the E:\Labfiles\Starter\CSS folder to the SiteAssets folder in the
project.
6. Add all the image files from the E:\Labfiles\Starter\CSS\Images folder to the Images folder in the
project.
2. Within the head element, use a link element to reference the style sheet at the project-relative URL
../SiteAssets/jquery-ui.css.
3. Use a script element to reference the JavaScript file at the project-relative URL ../Scripts/jquery-
ui.js.
Note: Because jQuery UI depends on jQuery, ensure that the script element that loads
jquery-ui.js occurs after the script element that loads jquery-1.7.1.min.js.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 1-39
5. Set the text of the p element to Click Start Polling to poll the server for health scores.
3. Create an anonymous function that executes when the document object model (DOM) is ready.
b. Call the jQuery progressbar method on the element with an id value of healthBar.
c. Set the maximum value of the progress bar to 10 and the current value to 5.
6. In the HealthScoresWebPart.aspx page, add a script tag to reference the HealthScores.js file.
7. Save your work.
2. In Internet Explorer, when the page has finished loading, click Contoso Development Site.
3. On the Contoso Development Site home page, remove the Get started with Apps for Office and
SharePoint web part from the page.
Results: After completing this exercise, you should have created, configured, and deployed an app part.
MCT USE ONLY. STUDENT USE PROHIBITED
1-40 Creating Robust and Efficient Apps for SharePoint
Task 1: Use the Revealing Module Pattern to Structure the JavaScript code
1. In the HealthScores.js file, delete everything except the use strict declaration.
3. Within the Contoso namespace, create a member named HealthScores and set it to a self-executing
anonymous function. All subsequent code should be created within this anonymous function.
4. At the top of the anonymous function, call the jQuery button method on elements of type button.
5. Declare a variable named healthScore. You will use this variable to store the latest health score from
the server.
6. Declare a variable named pollInterval. You will use this variable to provide a handle for JavaScript
timing functions.
11. Within the return statement, return the startPolling variable as StartPolling.
2. Configure the ajax method to submit a HEAD request to the URL at _layouts/15/blank.htm.
3. Add a success handler to the ajax method.
a. Set the healthScore variable to the value of the X-SharePointHealthScore header provided by
the server.
b. Set the text of the healthPara paragraph to Server health score: plus the value of the
healthScore variable.
c. Use the jQuery progressbar method to set the value of the healthBar progress bar to the value
of the healthScore variable.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 1-41
5. Within the function associated with the startPolling variable, use the jQuery progressbar method to
initialize the healthBar element as a progress bar.
6. Set the maximum value of the progress bar to 10, and the initial value to 0.
8. Use a JavaScript timing function to call the getHealthScore function every five seconds. Use the
pollInterval variable to store the handle for the timer.
9. Within the function associated with the stopPolling variable, clear the timer that calls the
getHealthScore function.
10. Set the text of the healthPara paragraph back to its original value of Click Start Polling to poll the
server for health scores.
2. Locate the button element that displays the text Start Polling.
3. Configure the click event handler for the button to call the Contoso.HealthScores.StartPolling
function.
4. Locate the button element that displays the text Stop Polling.
5. Configure the click event handler for the button to call the Contoso.HealthScores.StopPolling
function.
2. In Internet Explorer, when the page has finished loading, click Contoso Development Site.
3. On the Contoso Development Site home page, on the SharePoint Health Scores web part, click
Start Polling.
4. Verify that the web part displays a server health score and a progress bar indicator.
Note: The health score is likely to remain static at 0 at this point, as the server is under very little
load.
5. Without closing Internet Explorer, open a File Explorer window and browse to E:\Labfiles\Starter.
Note: If the PowerShell window displays an Execution Policy Change message, type Y,
and then press Enter.
7. Switch back to Internet Explorer, and verify that the web part displays an increased server health
score.
MCT USE ONLY. STUDENT USE PROHIBITED
1-42 Creating Robust and Efficient Apps for SharePoint
Note: It may take several seconds before the increase in load is reflected by the health score.
8. Click Stop Polling, and verify that the progress bar is removed from the web part.
Results: After completing this exercise, you should have configured an app part to poll the server for
health scores.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 1-43
Review Question(s)
Question: Which two service applications must be installed on a SharePoint 2013 server farm
before you can deploy and use apps for SharePoint?
Verify the correctness of the statement by placing a mark in the column to the right.
Statement Answer
Question: When you install an app for SharePoint, you must grant it all of the permissions it
requests or cancel the installation. Why does SharePoint not allow you to grant permissions
selectively to apps?
Question: When you develop an app for SharePoint, at what points in your code should you
consider requesting a health score from the SharePoint server?
MCT USE ONLY. STUDENT USE PROHIBITED
MCT USE ONLY. STUDENT USE PROHIBITED
2-1
Module 2
Developing Managed Metadata Solutions
Contents:
Module Overview 2-1
Module Overview
Microsoft® SharePoint® 2013 manages content, and a company's content can become extremely large
and difficult to manage. A flexible and consistent system that enables users to label and categorize
content consistently makes a large corpus of content much easier to navigate, search, follow, and present
to browsers. The SharePoint managed metadata features provide such a labeling system. Managed
metadata consists of a centrally managed set of terms and keywords that users can apply to items,
documents, and assets to describe them. The values of managed metadata fields help users to locate and
understand the huge quantity of content that can be available. SharePoint uses the values of managed
metadata fields in many other features, including search, web publishing, enterprise content
management, and social networking feeds.
Objectives
After completing this module, you will be able to:
Interact with managed metadata term sets and fields from client-side and server-side code.
MCT USE ONLY. STUDENT USE PROHIBITED
2-2 Developing Managed Metadata Solutions
Lesson 1
Understanding Managed Metadata
Before you can write code that works with managed metadata, you must understand the components of
the managed metadata system as well as the objects that appear in the managed metadata hierarchy. The
Managed Metadata service application provides a centralized database of managed metadata terms and
keywords that can be re-used throughout the SharePoint farm. The service application can store a
hierarchy of terms in a term store. In this lesson you will see all these objects and how they are used to
categorize items so that, in subsequent lessons, you can understand how to work with them in code.
Lesson Objectives
After completing this lesson, you will be able to:
Describe how managed metadata helps users to label and categorize content consistently.
You encourage users to choose the same terms rather than synonyms, which can confuse the
categorization. For example, if you provide the term "Cake", you discourage users from tagging with
the synonym "Bun". Users searching for "Cake" would not receive results tagged with "Bun", even
though these results are relevant to the search.
You can re-use the same terms in multiple hierarchies. For example, the term "Cake" may appear
under the term "Food". Simultaneously the term "Cake" can appear under the term "Product Types".
Spelling mistakes are less likely, because most users choose from pre-existing terms rather than
creating a new term.
You can use terms to provide a categorization of content that is independent of the site, list, library,
or folder that contains the content.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 2-3
Terms. Terms are organized into hierarchies called term sets. Each term can have child terms. For
example, the term "Bike" may have child terms "Racing Bike" and "Mountain Bike". The terms in a
term set are usually managed by a restricted group of users. These may be administrators or power
users. Terms provide a preconfigured taxonomy of content with which to tag items.
Keywords. Keywords are similar to terms but are not stored in a hierarchy. Any user can create a new
keyword and use it to tag content. Once a keyword exists, other users can choose it to tag their items.
Keywords provide a more dynamic way to tag items, which any user can expand. If a keyword
becomes widely used, a term set contributor can add it to a term set to make it part of the
preconfigured taxonomy.
Hashtags. SharePoint 2013 is the first version of SharePoint to support hashtags. These tags enable
users to categorize items by typing a tag such as #Cake instead of choosing from a term set or
keywords. This is a very immediate way to create tags and is familiar to many users from social
networking. You can choose to follow hashtags in your user profile.
Managed metadata fields can be single-valued or multi-valued. If a field is single-valued, the user can
apply only one term or keyword to the item. If a field is multi-valued, the user can tag the item with as
many terms or keywords as necessary.
The tag cloud web part is a helpful way to enable users to access content that is tagged. The web part
displays all the tags that have been used in the local site. The size of each tag in the web part indicates
how often a tag has been used; popular tags are displayed in a larger font.
In Search. Managed metadata terms can be indexed and used to improve search results. Managed
metadata fields can be used to provide refinements. These help users to refine generalized searches
and obtain the content that they seek.
In Web Publishing. In SharePoint 2013 you can create a web site navigation hierarchy that is based on
the managed metadata terms applied to each web page. In this way, you can create a site structure
that is independent of the lists, libraries, and folders in your site.
In Enterprise Content Management. You can use managed metadata fields to create document sets,
which can be declared as a single record and locked.
In Social Networking. By following a term or keyword, you can keep track of all the activity in the
organization on a subject that interests you.
You will learn more about the way managed metadata enables other SharePoint features in subsequent
modules in this course.
MCT USE ONLY. STUDENT USE PROHIBITED
2-4 Developing Managed Metadata Solutions
Often, administrators create a single Managed Metadata service application for all web applications in the
farm. However SharePoint developers should bear in mind that sometimes there may be multiple
instances of the service application in the farm and that access to a particular instance may be restricted.
The Managed Metadata service application can also be used to share content types between site
collections. When you create a content type in a SharePoint site, it is usually only available within the
same site. However, by publishing the content type to the Managed Metadata service application, you can
re-use a single content type in many different sites and site collections in your farm. When you configure
a Managed Metadata service application instance, you can designate a site collection as the Content Type
Hub for the service application. The service application will then propagate content types and site
columns from the hub site collections to any other site collections that subscribe to the service application
proxy.
The Managed Metadata service application uses a database to store terms, keywords, and other
information. This database is named when an administrator creates the service application and may be
located on the server that runs the Managed Metadata web service or on a dedicated SQL Server® that
hosts other SharePoint databases such as the content database.
Finally, the Managed Metadata service application requires that the Managed Metadata web service is
running on at least one SharePoint server in the SharePoint farm.
Alternatively, you can start the Managed Metadata Web Service by running the following commands in
PowerShell:
$metadataWebService | Start-SPServiceInstance
To create an instance of the Managed Metadata Service Application and a proxy for the service
application:
2. In the ribbon, click New, and then click Managed Metadata Service.
3. In the Name box, type a name for the new service application.
4. In the Database Service box, type the name of the server that will host the managed metadata
database.
5. In the Database Name box, type a name for the new database.
6. Under Application Pool, select or create a new application pool for the service application.
7. Click OK.
Alternatively, you can create an instance of the service application and a proxy by running the following
commands in PowerShell:
#Create proxy
New-SPMetadataServiceApplicationProxy –Name "Managed Metadata Service Application Proxy"
–ServiceApplication $metaDataServiceApp –DefaultProxyGroup
MCT USE ONLY. STUDENT USE PROHIBITED
2-6 Developing Managed Metadata Solutions
Term Stores
A term store represents an instance of the Managed
Metadata service application proxy. For each term
store, you can specify term store administrators
who can create groups in the term store and
determine the managers of each group. You can
also specify the languages of the terms in the term
store.
The Term Store Management Tool is a graphical user interface that you can use to manage groups, term
sets, and terms within a term store. To access the management tool:
2. Click the managed metadata service application, and then click Manage.
Groups
You can use groups as administrative boundaries within the term store to govern which users can
contribute terms to each term set. You can create multiple groups within each term store. Two user roles
are important for each group:
Contributors. These users have permission to create new terms and term sets in the group.
Group Managers. These users have contributor permissions, but can also add other users to the
Contributors role.
Place term sets into a single group if the same set of uses should be able to manage terms in those term
sets.
Term Sets
Each term set contains a single hierarchy of terms. For each term set, you can set the submissions policy. If
the submissions policy is Open, any user can add terms. If the policy is Closed only group contributors can
add terms.
Owner. The term set owner is informational only. The term set owner is not granted any specific
permissions by virtue of being the term set owner.
Contact. The contact is not a user account but an email address. Users without contributor
permissions can send a message to this address to ask for new terms and other changes. The contact
email address is often the email address of the term set owner account.
Stakeholders. A stakeholder is a user who has an interest in the term set. Stakeholders are notified
when contributors make changes to the term set. For example, if a term set is used for navigation in a
web publishing site, the stakeholders should include the web site designers.
Within each term set, anyone with contribute permissions can create individual terms. You can create up
to seven nested levels of terms. You will learn more about terms in the next topic.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 2-7
Understanding Terms
A managed metadata term is more than a single
word. It has a number of properties and actions that
you can use to manage its behavior.
When you create a term, SharePoint sets the default label to match the term name. This is the label that is
displayed to users when an item is tagged with this term. It is also the value that is stored in the managed
metadata field for the item. You can use the Other Labels property to add any number of synonyms and
abbreviations.
Labels support multiple languages for each term. You can configure each term set to support multiple
languages. For each supported language you can specify a different set of labels for each term. For
example, in English, the default label for the "Bike" term may be "Bike" and other labels may include
"Bicycle". In French, the default label for the "Bike" term may be "Velo" and other labels may include
"Bicyclette".
Copy. When you copy a term, you create a sibling term with the same labels and other properties.
You can edit the copied term independently of the source term and move it to other locations in the
term store.
Copy with Children. When you copy a term with children, the copied sibling term includes the entire
sub-hierarchy of the source term. The sub terms can be edited independently.
Re-use. When you re-use a term, you make the same term appear at different locations in the term
store. However, there is only one term. If you change the properties of the re-used term in, one
location, your changes also apply to the other locations where the term appears. When you re-use a
term, child terms are not re-used and changes can be made wherever the term appears.
Pin with Children. As with re-using labels, when you pin a term, you make the same term appear at
different locations in the term store. However, changes can only be made in one location where the
term is pinned. Also, the child terms of a pinned term appear in both locations.
Custom Properties
You can associate custom properties with term sets and terms. Custom properties essentially enable you
to specify your own metadata with term sets and terms, typically for use in code-based solutions. You can
set custom properties in the term store management tool or programmatically.
unavailable for tagging so that a term cannot be applied to items. You can use this technique if a term is
intended to organize a term set rather than apply to items. For example, if you create a term set for users
to apply to products, you may not want users to apply the term "Accessories" to items. Instead the
"Accessories" term helps users to navigate the term set and find child terms such as "Flight Cases" and
"Power Supplies".
You can also deprecate terms when you no longer want them to be applied to items. Users cannot add a
tag with a deprecated term, but existing items can keep the deprecated term if it already applied. Users
also cannot copy, re-use, pin, or create child terms for deprecated terms.
Categorizing Products
You have products stored in several different
SharePoint sites in a single site collection. All the
product lists use the Product content type. You
want to enable users to categorize products
according to a set of categories provided by product managers. The key requirements are as follows:
The product category hierarchy consists of three levels: Department, Category, and Subcategory.
When users tag a product, they must select a tag at the Subcategory level. In other words, to prevent
orphaned objects, a user should not be able to specify a department or a category without specifying
a subcategory.
Only members of the Product Managers group should be able to alter the terms and structure of the
product category hierarchy.
The product category hierarchy is expected to change every so often, but old items may remain in the
catalog if they prove popular.
Technical Areas. This includes terms that describe engineering topics and is intended to help technical
staff find answers to technical questions.
Marketing. This includes terms that describe marketing campaigns and the subjects they promote.
Terms from Hot Topics may be relevant to marketing campaigns and technical staff. Technical terms may
be relevant to all users, but should only be changed by technical staff.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 2-9
Lesson 2
Configuring Managed Metadata Term Sets
Now that you understand how managed metadata works, you can learn how to manipulate managed
metadata in code. The SharePoint APIs enable developers to access groups, term sets, terms, and other
metadata objects from managed code or script. Using these APIs, desktop applications, SharePoint
solutions, and SharePoint apps can read and write information to the managed metadata hierarchy. In this
lesson, you will see how to build a term set by writing code that creates groups, term sets, and terms. You
will also see how to use the advanced features of terms and manage permissions and roles. In this way
you can provide a full set of terms with which users can tag content.
Lesson Objectives
After completing this lesson, you will be able to:
Obtain handles for taxonomy sessions and term stores, through which you can access metadata.
Write code that reads and creates new groups and term sets.
The TaxonomySession object includes a collection of all the term stores that exist in the Managed
Metadata service application. You can access a specific term store by providing an index. This can be an
integer, the GUID of the term store, or the name of the term store.
Note: If you use the name to access a specific term store, note that you should use the
name of the Managed Metadata service application proxy. The name of this proxy can differ from
the name of the service application itself.
The following code opens a term store named "Managed Metadata Service Application Proxy" in C#:
In the following C# example, the code checks that a group named "Vehicles" exists. If the group does not
exist, the code creates a new group:
In the following JavaScript example, the code checks for a group named "Vehicles" by looping through all
the groups in a term store:
In the following JavaScript example, the code creates a new group named "Vehicles":
The following code example accesses a term set with a specific ID. If the term set does not exist, the code
creates a new term set, named "Cars":
if (carsTermSet == null)
{
//There is no term set with the right GUID. Create a new one.
carsTermSet = vehiclesGroup.CreateTermSet("Cars", termSetGUID);
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 2-13
Note: Because you cannot run client-side code with elevated permissions, only term store
administrators will be permitted to create, edit, or delete groups, term sets, and terms from
client-side code.
Creating Terms
When you have a TermSet object, you can create a
top-level term by calling the
TermSet.CreateTerm() method. You can create
child terms by calling the Term.CreateTerm()
method. In this way, you can build a hierarchy of
terms.
Creating Terms
To create a term in a term set, you must supply three parameters to the CreateTerm() method:
Name. This string is also used as the default label for the term.
Locale ID. This integer specifies the language and region for the term.
GUID. Optionally, you can provide a GUID for the new term. SharePoint assigns a GUID automatically
if you do not supply one. However, if you specify a GUID it is easy to locate the correct term in later
code.
The following C# code illustrates how to create a new term in a term set:
termStore.CommitAll();
MCT USE ONLY. STUDENT USE PROHIBITED
2-14 Developing Managed Metadata Solutions
The following JavaScript code illustrates how to create a new term in a term set:
Demonstration Steps
1. Add references to the following namespaces:
o Microsoft.SharePoint
o Microsoft.SharePoint.Taxonomy
o Microsoft.SharePoint
o Microsoft.SharePoint.Taxonomy
3. Locate the "Connect to the taxonomy session here" comment and replace it with a line of code that
creates a new TaxonomySession object for the siteCollection.
4. Locate the "Get the term stores here" comment and replace it with a line of code that gets all the
term stores in the taxonomySession object and stores them in a variable named termStores.
5. Locate the "Get the first term store here" comment and replace it with a line of code that gets the first
term store and stores it in a variable named store.
6. Locate the "Get the Vehicles group here" comment and replace it with a line of code that uses the
groupGuid value to obtain the group from the store. Store the group in the vehiclesGroup variable.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 2-15
7. Locate the "Create a vehicles group here" comment and replace it with a line of code that creates a
new group called Vehicles. Use the following information:
o Method: store.CreateGroup
o Method: store.GetTermSet
o GUID: termSetGuid
9. Locate the "Create the Cars term set here" comment and replace it with a line of code that creates a
new term set called Cars. Use the following information:
o Method: vehiclesGroup.CreateTermSet
10. Locate the "Create a term here" comment and replace it with a line of code that creates a new term.
Use the following information:
o Method: carsTermSet.CreateTerm
o LCID: 1033
11. Locate the "Commit the changes to the term store here" comment and replace it with a line of code
that commits all changes to the store object.
14. Verify that the Vehicles group, the Cars term set, and the Station Wagon term have been created as
expected.
Using Terms
Each term can have multiple labels that are usually
synonyms or abbreviations of the term. Labels
encourage users to use terms consistently because
SharePoint suggests the term when they type a
synonym in a managed metadata field. A single
term can also be re-used in different term sets in a
term store.
the term in the managed metadata. If you use multiple languages, you can add labels in those languages
to each term so that a single term can be used internationally.
The following code shows how to add a label to a term by using the server-side object model:
//Commit changes
termStore.CommitAll();
Reusing Terms
In order to re-use a term in another location, you must first get a reference to the source term. Next,
obtain a reference to the parent term in the new location and call the Term.Re-useTerm() method.
Reusing a Term
//Get the source term.
Guid sourceTermGUID = new Guid("220227d7-c26e-4fc0-b0db-2e632bc561f8");
Term sourceTerm = termStore.GetTerm(sourceTermGUID);
When you re-use a term in this way, the term can be modified in both locations. In the above code, this
means that changes to the sourceTerm object will automatically apply to the re-usedTerm object.
Pinning a Term
When you re-use a term with pinning, the re-used term, which is the term in the destination, cannot be
modified. The Re-useTermWithPinning() method is similar to the Re-useTerm() method.
The following code shows how to re-use a term with pinning in C#:
Pinning a Term
//Get the source term.
Guid sourceTermGUID = new Guid("220227d7-c26e-4fc0-b0db-2e632bc561f8");
Term sourceTerm = termStore.GetTerm(sourceTermGUID);
EditTerm. This value indicates that a user has the right to edit the properties of a term.
EditTermSet. This value indicates that a user has the right to edit the properties of a term set and can
add new terms.
EditGroup. This value indicates that a user has the right to edit the properties of a group and can add
new term sets.
ManageTermStore. This value indicates that a user has the right to add new groups to a term store
and can set permissions for a group.
Contributor. This value indicates that a user has contributor permissions in a group and can add
terms.
GroupManager. This value indicates that a user has manager permissions in a group and can add
terms and term sets, as well as grant contributor permissions.
All. This value indicates that a user has full control on a taxonomy object.
Checking Permissions
Permissions are always enforced, whether you check them in your code or not. However, sometimes you
may want to take actions based on the permissions available to a user. For example, if a user cannot edit a
term, you may want to hide the “Add Label" button.
To check permissions in your code, use the TermSetItem.DoesUserHavePermission method. This
method returns a Boolean value by passing a TaxonomyRights value to indicate if the current user has
the permission you specify.
The following code shows how to check whether a user has contributor rights on a group:
Checking Permissions in C#
//Get the group
group = termStore.Groups["Vehicles"];
if (group.DoesUserHavePermissions(TaxonomyRights.Contributor))
{
Console.WriteLine("The current user is a contributor in the Vehicles group.");
}
else
{
Console.WriteLine("The current user is not a contributor in the Vehicles group.");
}
MCT USE ONLY. STUDENT USE PROHIBITED
2-18 Developing Managed Metadata Solutions
The following code shows how to add a contributor and a group manager to a taxonomy group in server-
side code:
The following code show how to use the AddStakeHolder() method in server-side code:
To remove the stakeholder, use the similar TermSet.DeleteStakeHolder() method and pass the same
login name.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 2-19
Objectives
After completing this lab, you will be able to:
Create and configure a new SharePoint-hosted app that works with managed metadata.
Obtain managed metadata objects such as term stores, groups, and term sets, and display them in a
web page.
Create managed metadata objects such as groups and term sets, by using the JavaScript CSOM.
Lab Setup
Estimated Time: 45 minutes
Virtual Machine: 20489B-LON-SP-02
Username: CONTOSO\Administrator
Password: Pa$$w0rd
The app includes no facilities for removing the term set and group that it creates. If, in Exercise 3, you
push the “Create Corporate Term Set” button more than once, an error will be displayed because the term
set and group already exist. If you want to remove the term set and group so that you can execute the
code again, run the following PowerShell script: E:\Labfiles\Scripts\CleanUpTermStore.ps1
A warm-up script named WarmUp.ps1 runs automatically when you start the virtual machine. This script
helps to improve the performance of the virtual machine by downloading the home page of the root site
in each site collection on the server. Occasionally this script displays timeout errors; you can ignore these
errors. You should ensure this script has finished running before you start the lab.
3. Open Visual Studio® and create a new project. Use the following information:
o Name: CorporateStructureApp
o Location: E:\Labfiles\Starter
3. In Visual Studio, in the Default.aspx file, locate the div element. Delete the entire contents of the div
element and paste the contents of the clipboard into the empty div element.
4. Delete the App.js file from the Scripts folder.
o Scope: Taxonomy
o Permission: Write
2. Add a permission request to the AppManifest.xml file. Use the following information:
o Scope: Web
Results: A new SharePoint hosted app with a JavaScript framework, user interface, and JavaScript library
links is completed.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 2-21
o Method: SP.Taxonomy.TaxonomySession.getTaxonomySession()
2. Obtain the term store and store it in the termStore variable. Use the following information:
o Method: taxonomySession.get_termStores().getByName()
o Term store name: Managed Metadata Service Application Proxy
4. Call the executeQueryAsync function and pass anonymous functions for successes and failures.
5. In the anonymous function for successes, update the page element with ID status-message to
inform the user that the term store is loaded.
2. Store all the groups in the termStore object in a new variable named groups.
4. Call the executeQueryAsync function and pass anonymous functions for successes and failures.
5. In the anonymous function for successes, remove all the child elements of the page element with ID
groups-list.
6. Get the enumerator from the groups collection and store it in a variable named groupEnum.
7. Use the groupEnum.moveNext() function to loop through all the groups in a while loop.
8. In the while loop, get the current group from the groupEnum object and store it in a new variable
named currentGroup.
9. Get the ID from the currentGroup object and store it in a new variable named currentGroupID.
10. Create a new <div> element and store it in a new variable named groupDiv.
11. Append a child element to the groupDiv page element. The child element must be a text node that
is the name of the currentGroup object.
MCT USE ONLY. STUDENT USE PROHIBITED
2-22 Developing Managed Metadata Solutions
12. Append the groupDiv object to the page element with ID groups-list.
13. In the anonymous function for failures, update the page element with ID status-message to inform
the user that groups could not be loaded.
15. Start the app in debugging mode and authenticate with the following credentials:
o Username: Administrator
o Password: Pa$$w0rd
16. Verify that the app displays a single group named System.
Results: A SharePoint-hosted app that can display groups from the Managed Metadata service
application.
2. Create a new taxonomy group and store it in the corporateGroup variable. Use the following
information:
o Method: termStore.createGroup
4. Create a new term set and store it in the corporateTermSet variable. Use the following information:
o Method: corporateGroup.createTermSet
6. Call the executeQueryAsync function and pass anonymous functions for successes and failures.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 2-23
7. In the anonymous function for successes, set the text of the page element with ID status-message to
Group and term set created.
9. In the anonymous function for failures, set the text of the page element with ID status-message to
Group and term set creation failed.
2. In the new createTerms function, set the text of the page element with ID status-message to
Creating terms…
3. Create a new term and store it in a new variable named hrTerm. Use the following information:
o Method: corporateTermSet.createTerm()
o Name: Human Resources
5. Create a new term and store it in a new variable named salesTerm. Use the following information:
o Method: corporateTermSet.createTerm()
o Name: Sales
7. Create a new term and store it in a new variable named technicalTerm. Use the following
information:
o Method: corporateTermSet.createTerm()
o Name: Technical
9. Create a new sub-term in the technical term and store it in a new variable named engineeringTerm.
Use the following information:
o Method: technicalTerm.createTerm()
o Name: Engineering
11. Create a new sub-term in the technical term and store it in a new variable named softwareTerm. Use
the following information:
MCT USE ONLY. STUDENT USE PROHIBITED
2-24 Developing Managed Metadata Solutions
o Method: technicalTerm.createTerm()
o Name: Software
13. Create a new sub-term in the technical term and store it in a new variable named supportTerm. Use
the following information:
o Method: technicalTerm.createTerm()
o Name: Support
15. Call the executeQueryAsync function and pass anonymous functions for successes and failures.
16. In the anonymous function for successes, set the text of the page element with ID status-message to
Terms created.
18. In the anonymous function for failures, set the text of the page element with ID status-message to
Error: Could not create the terms.
o Password: Pa$$w0rd.
6. Explore the groups, term sets and terms in the Managed Metadata Service Application.
7. When you are satisfied that the app has created the terms correctly, close Internet Explorer.
Results: A SharePoint hosted app that can create a new group and a new empty term set in a term store.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 2-25
Lesson 3
Working with Managed Metadata Fields
In order to use the terms and keywords in a term set to tag documents, items, and assets, users must have
managed metadata fields. A managed metadata field is a type of site column that you can use in lists,
libraries, or content types. Other field types include Choice, Single Line of Text, and Lookup fields.
Managed metadata fields can be single-valued, in which case a user can tag an item with only one term.
Alternatively, if the metadata field is multi-valued, the user can tag an item with many terms from
multiple term sets. In this lesson you will see how to create managed metadata site columns, read terms
from fields, and add new tags to items in code.
Lesson Objectives
After completing this lesson, you will be able to:
Create managed metadata fields in SharePoint sites and connect those fields to specific term sets.
Read and write values to single-valued managed metadata fields.
Connect the managed metadata field to a term set. If you connect the field to a specific term set, you
fix the term set from which the users can select tags. For example, in the "Product Categories" field,
users should be able to select terms from the "Products" term set but not from the "Social" term set.
In the following JavaScript example, XML strings are created to the managed metadata and note fields
and passed to the AddFieldAsXML() method:
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 2-27
TaxonomyField object. To perform this cast in JavaScript, which does not offer support for casting
classes, use the cast() method on the SharePoint ClientContext class.
The following JavaScript code illustrates how to connect a managed metadata column to a term set:
Single-Value Fields
Taxonomy fields are site columns that can be used
to tag SharePoint items with terms from managed
metadata. When you create a taxonomy field, you
can specify whether the field is single-valued or
multi-valued. If the term is single-valued, the user
can add only one term to the item. This makes the
code for reading and setting tag values relatively
simple.
TermGuid. This property is the GUID of the term as stored in the term set.
To access more information about the tagged term, such as full collection of labels, use the term GUID to
look the term up in the managed metadata term store.
The following code shows how to read the tagged term's GUID and default label from a list item's
managed metadata field. This example uses the .NET managed Client-Side Object Model (CSOM):
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 2-29
The following code shows how to set a tag for a single-valued taxonomy field:
context.ExecuteQuery();
context.ExecuteQuery();
//Get the values of the skills field and cast them as a TaxonomyFieldValueCollection
TaxonomyFieldValueCollection skillsTaxValues =
(TaxonomyFieldValueCollection)firstTask["Skills"];
context.load(skillTaxValues);
context.ExecuteQuery();
The following example shows how to set two terms as tags in a multi-valued taxonomy field:
//Get the client context, the list, the field, and the item
ClientContext context = new ClientContext("http://dev.contoso.com");
List tasksList = context.Web.Lists.GetByTitle("Tasks");
context.Load(tasksList);
context.ExecuteQuery();
}
MCT USE ONLY. STUDENT USE PROHIBITED
2-32 Developing Managed Metadata Solutions
Objectives
After completing this lab, you will be able to:
Lab Setup
Estimated Time: 60 minutes
Username: CONTOSO\Administrator
Password: Pa$$w0rd
The app includes no facilities for removing the managed metadata columns it creates. If, in Exercise 2, you
push the “Create Corporate Site Columns” button more than once, an error will be displayed because
columns already exist. If you want to remove columns so that you can execute the code again, run the
following PowerShell script: E:\Labfiles\Scripts\CleanUpMetaDataColumns.ps1
A warm-up script named WarmUp.ps1 runs automatically when you start the virtual machine. This script
helps to improve the performance of the virtual machine by downloading the home page of the root site
in each site collection on the server. Occasionally this script displays timeout errors; you can ignore these
errors. You should ensure this script has finished running before you start the lab.
2. In the App.js code file, in the createColumns function, write code that sets the text of the page
element with ID status-message to Obtaining the host web…
3. Use the context.get_web().get_parentWeb() method to get a web info object for the host web and
store it in a new variable named hostwebinfo.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 2-33
5. Call the executeQueryAsync function and pass anonymous functions for successes and failures.
o Function: context.get_site().openWebById()
4. In the anonymous function for successes, set the text of the page element with ID status-message to
Parent web loaded.
5. Call the addColumns() method.
6. In the anonymous function for failures, set the text of the page element with ID status-message to
Error: Could not load parent web.
Results: A SharePoint app that has a reference to the host web in preparation for creating site columns in
the host web.
2. In the addColumns function, write code that sets the text of the page element with ID status-
message to Creating site columns…
3. Get all the fields from the hostweb object and store them in a new variable named
webFieldCollection.
4. Create a new note field and store it in a new variable named noteField. Use the following
information:
o Method: webFieldCollection.addFieldAsXml()
6. Create a new metadata field and store it in a new variable named metaDataField. Use the Following
information:
o Method: webFieldCollection.addFieldAsXml()
8. Call the executeQueryAsync function and pass anonymous functions for successes and failures.
9. In the anonymous function for successes, set the text of the page element with ID status-message to
Columns added.
2. In the connectFieldToTermSet function, set the text of the page element with ID status-message to
Connecting the columns to the term set.
3. Get the ID of the termStore and store it in a new variable named sspID.
6. Call the executeQueryAsync function and pass anonymous functions for successes and failures.
7. In the anonymous function for successes, set the sspId of the metaDataTaxonomyField object to
sspID.
11. In the anonymous function for successes, set the text of the page element with ID status-message to
Connection made. Operations complete.
12. In the anonymous function for failures, set the text of the page element with ID status-message to
Error: Could not connect the taxonomy field.
o Username: Administrator
o Password: Pa$$w0rd
2. Browse to the list of Site columns in the web site and note the columns in the Custom Columns
category.
3. In Visual Studio, start the app without debugging and trust the app. Use the following credentials to
authenticate:
o Username: Administrator
o Password: Pa$$w0rd
5. In the Site Columns list for the http://dev.contoso.com site, note the new column in the Custom
Columns category.
6. Verify that the new site column is bound to the correct term set.
7. Stop debugging and close Visual Studio.
Results: A SharePoint-hosted app that can create site columns for metadata.
Review Question(s)
Question: The marketing team has created the term "Sales Lead" in the Marketing term set.
The sales team wants to use the same term in the Sales term set. When sales personnel make
changes to the new term, you do not want those changes to apply to the term in the
Marketing term set. How can you satisfy this requirement?
Verify the correctness of the statement by placing a mark in the column to the right.
Statement Answer
Module 3
Interacting with the Search Service
Contents:
Module Overview 3-1
Module Overview
The goal of this module is to enable students to create and execute search queries from client-side and
server-side code. The module provides an overview of the search service architecture in Microsoft®
SharePoint® 2013 as it relates to developers, before describing how to construct queries by using
Keyword Query Language (KQL) and FAST Query Language (FQL) and how to submit these queries to the
search service.
Objectives
After completing this module, you will be able to:
Lesson 1
Understanding the SharePoint 2013 Search Service
Explore the architecture of the search service from a development perspective.
Lesson Objectives
After completing this lesson, you will be able to:
Following its radical rebuild, the Search architecture is now made up of the following components:
Crawl
Content Processing
Analytics Processing
Indexing
Query Processing
Search Administration
There are two core functions of search: content ingestion and content query. Without effective content
ingestion, contributor content will not be effectively indexed. For search users, it is essential to have
indexed content available quickly and to ensure that search queries surface the most relevant content in
their result sets.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 3-3
Content ingestion
The process flow for ingesting content into the search index uses the following components:
Crawl. The crawl component can search content across a range of content sources—from both
Microsoft platforms and third-party sources. Access to these is provisioned by connectors. There are a
number of connectors shipped with SharePoint 2013. Crawled content is held in the crawl database.
Content Processing. The crawl component passes the crawled content to the content processing
component. This component performs tasks such as parsing documents, property mapping, and
processing linguistics, all of which create artifacts that can be stored in the search index. In addition,
this component processes URL links, which are stored in the link database.
Analytics Processing. The analytics processing component analyzes the crawled items and how users
interact with search results.
Index. The index component writes artifacts to the index file, which is actually a number of files and
folders. This component also manages the index partitions and replicas, ensuring that indexed
content is valid.
You can deploy multiple instances of these components to scale out your search architecture.
Content Query
The process for servicing user search queries is as follows:
1. A client interface, such as the Search Center, passes a query through a web front-end (WFE) to the
query processing component.
2. The query processing component performs some linguistic processing to maximize query efficiency
and effectiveness, such as word stemming and initiation of query rules. The processed query is then
passed to the index component.
3. The index component interrogates the search index and returns a result set to the query processing
component. This component processes these results to remove duplicates and performs any
additional security trimming that is required, and then passes the result set to the WFE to be rendered
to the client application.
Search Administration
The Search Administration Component runs system processes required for search. It is responsible for
search provisioning and managing topology changes, and it coordinates interaction between the other
search components—Content Processing, Query Processing, Analytics Processing, and Index Component.
Analytics Processing. Analytics Processing handles the storage and processing of all analytics data
related to search items.
Query Processing. The query processing component handles all queries to the index. It performs
various linguistic processing procedures before sending the query to the index.
Index. The index component stores and manages the indexed search data.
Any and all of these roles can be played by any server in the SharePoint Farm. A welcome change in the
search architecture is the ability to have more than one administration component for redundancy.
Start-SPEnterpriseSearchQueryAndSiteSettingsServiceInstance $serverName
Start-Sleep -m 60000
Once you have set up a search service application, it is important to know the series of steps that occur
when the content is processed. This will help you to better debug issues with your search results. The
high-level steps include:
1. The Search Crawler will connect to the target source and retrieve the crawl properties, security
information, and file contents.
4. Content Processing component will pass the item data through more than 70 flows, each flow having
a specific role in the content processing pipeline. For example, major flows include document parsing
and format handling, adding and retrieving data from the Analytics Component and Database, and
the Content Enrichment service web service callout.
5. Once all of the proper flows have been executed, the transformed metadata is passed to the indexing
component.
6. The Indexing component will determine the type of operation that should be applied, and then
perform the operation on the file based index.
7. Once added to the index, the search query component will take user- and application-submitted
queries and transform them before sending to the index component for retrieval.
8. The Indexing component will find all matching items and then pass the results back to the Query
component.
9. The Query component will do any required sorting and relevance operations.
Demonstration Steps
1. Start the 20489B-LON-SP-03 virtual machine.
5. Review the Search Administration page. Notice the Search Application Topology section and how
each role is assigned to a single server. Also notice how you cannot change the topology by using the
administration web site in SharePoint 2013, this must be done by using Windows PowerShell.
7. On the Details tab, review the processes that are running as noderunner.exe.
MCT USE ONLY. STUDENT USE PROHIBITED
3-6 Interacting with the Search Service
11. Switch back to SharePoint Central Administration, press F5 to refresh the page.
12. The page will fail to load because the administration service is down.
14. Notice how all the noderunner.exe processes have been removed
17. Switch to Task Manager, you should now see the noderunner.exe processes have started again.
18. Close all open windows.
Default. The default index update group contains all managed properties that do not belong to the
Security, Link, Usage, or People index update groups.
Security. The security index update group contains the document Access Control List (ACL) managed
property.
Link. The link index update group contains the managed properties related to link structure.
Usage. The usage index update group contains the managed properties related to usage data.
People. The people index update group contains the managed properties related to people search.
The index can be made redundant by adding more index roles to the farm. These roles can then provide
index redundancy by becoming a replica or a partition of the index. This mimics the architecture
functionality of FAST Search’s rows and columns. In order to add new replicas or partitions, you must use
Windows PowerShell and have more than one search server in your farm.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 3-7
The following code examples shows you how to add a new index partition to SharePoint Search by using
Windows PowerShell:
$ssa = Get-SPEnterpriseSearchServiceApplication
$activeTopology=Get-SPEnterpriseSearchTopology -Active -SearchApplication $ssa
$newTopology = New-SPEnterpriseSearchTopology -SearchTopology $activeTopology -
SearchApplication $ssa –Clone
Crawled Properties
As previously mentioned, the crawler is responsible
for finding properties about the crawled content.
This includes the content binary and any other
protocol and source specific metadata. In some
cases the number of crawled properties remains
constant; in other cases (like a SharePoint List), you
may find that new columns have been added. In the
case of the list, the new properties are discovered
automatically and show up in the search schema
after a successful crawl.
Search Application. The search application in which to create the crawled property.
The following code example shows how to create a new crawled property by using Windows PowerShell:
Managed Properties
Managed properties are mappings to crawl
properties that can be used in various different
ways in Search. Managed properties have several
settings that determine how the contents will be
displayed in search results. These settings include:
Queryable. Allows you to query the managed property by explicitly using the property name.
Retrievable. Will allow you to display this property in the search results.
Allow Multiple Values. Allows the property to store more than one value. This is helpful for managed
properties like Author.
Refinable. When set to “yes”, the managed property can be used to drill down into search results by
using the refinement web part.
Sortable. When set to “yes”, you can use the managed property to sort results.
Safe for Anonymous. Allows the property to be visible for anonymous users; typically used on
Internet-facing sites.
Alias. Can be used to change the name to something more meaningful. Used when you don’t have
permissions to create new managed properties.
Token Normalization. When enabled, results are returned ignoring casing and diacritics.
Complete Matching. Forces an exact match search on managed properties. Any substring search will
not be returned.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 3-9
Custom Entity Extraction. Tells the system that the managed property should be processed as part of
the respective entity extraction dictionary. This is explored in a later module.
When adding columns to lists, they automatically are added as crawl and managed properties. The crawl
property naming convention is:
ows_q_<Type>_<ColumnName>
ows_r_<Type>_<ColumnName>
ows_taxId_<Type>_<ColumnName>
<ColumnName>OWS<Type>
owstaxId<ColumnName>
Additional Reading: For more information on how to create managed properties by using
Windows PowerShell, see New-SPEnterpriseSearchMetadataManagedProperty at
http://go.microsoft.com/fwlink/?LinkId=321930.
The following code example shows how to create managed properties by using Windows PowerShell:
Demonstration Steps
1. Start the 20489B-LON-SP-03 virtual machine.
6. In the quick launch, under Queries and Results, click Search Schema.
13. In the navigation at the top of the page, click the Crawled Properties link.
20. You should be presented with a list of crawled property categories and how many exist in each
category.
Search Schema
The entire set of crawl and managed properties
make up part of the search schema. The entire set
includes:
Crawl Properties
Managed Properties
Mappings
Query Rules
Aliases
Result Sources
Result Types
Once you have created a search service application, you will have a basic set of known crawled and
managed properties. As you continue to index content sources, new crawled and managed properties will
be added.
Service Application
Site Collection
Site
Each level can see the managed properties and other values at the same level or higher.
Demonstration Steps
1. Start the 20489B-LON-SP-03 virtual machine.
5. Under the Search section, click Schema. You should see that you have no ability to create a managed
property at this level.
11. Click the site settings icon, then click Site Settings.
15. Notice how you can only add Text and Yes/No property types. You cannot specific multiple values,
and you cannot add it as a refiner or as sortable.
17. Click the site settings icon, then click Site Settings.
18. Under Site Collection Administration, click Search Result Sources. Notice that the Tasks (Site)
result type you just created is not visible.
22. Click the site settings icon, and then click Site Settings.
23. Under Site Collection Administration, click Schema.
24. For a search for Classification, you should see the site collection property you created.
25. Click the site settings icon, and then click Site Settings.
26. Click Result Sources. You should see the site collection result source.
30. Click Result Sources. You should not see the site collection or site level result sources created
previously, as they are out of scope.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 3-13
Lesson 2
Building Search Queries with KQL and FQL
In this lesson you will learn about the two different queries languages that SharePoint supports. You will
also learn how to build both simple and advanced queries to search for specific content.
Lesson Objectives
After completing this lesson, you will be able to:
KQL is the default and recommended query language, and will be used when users and applications
submit queries to the search engine. In order to use FQL, you must enable it manually.
SQL Syntax queries, also known as FullTextSqlQuery, are no longer supported. Any older applications that
utilize this language will break when moving to SharePoint 2013.
MCT USE ONLY. STUDENT USE PROHIBITED
3-14 Interacting with the Search Service
SharePoint
Aaren Ekelund
Author:"Adam Barr"
As you are about to learn, queries can get much more complex when adding operators.
KQL Operators
Simple KQL queries can get most users what they
are looking for, but there are many more use cases
where you need to apply operators to find very
specific information. To construct complex queries,
you can combine multiple free-text expressions
with KQL query operators. If there are multiple free-
text expressions without any operators between
them, the query behaviour is the same as using the
AND operator.
AND. Returns search results that include all of the free text expressions, or property restrictions
specified with the AND operator. This is the same as the “+” operator.
NOT. Returns search results that do not include the specified free text expressions or property
restrictions. This is the same as the “-“ operator.
OR. Returns search results that include one or more of the specified free text expressions or property
restrictions.
NEAR. The NEAR operator matches the results where the specified search terms are within close
proximity to one another, without preserving the order of the terms.
ONEAR. The ONEAR operator matches the results where the specified search terms are within close
proximity to each other, while preserving the order of the terms.
XRANK. The XRANK operator boosts the dynamic rank of items based on certain term occurrences
within the match expression, without changing which items match the query.
WORDS. The WORDS operator specifies that the terms in the query are synonyms, and that results
returned should match either of the specified terms. You can use the WORDS operator with free text
expressions only; it is not supported with property restrictions in KQL queries.
Advanced KQL
You can build very advanced search queries by
using the KQL operators. Here are some examples
of advanced queries:
Find all items that have the complete phrase “Microsoft SharePoint”: “Microsoft SharePoint”
Do a People search for first of Dan and title of CEO: FirstName:Dan JobTitle:CEO
Find all items of type Task in the team web application: Path:http://team.contoso.com
ContentType:Tasks
Search for documents that have the words “SharePoint” and “Microsoft” within two words of each
other: "SharePoint" NEAR(n=2) "Microsoft"
Find all People that have a last name that starts with “Sm”: LastName:Sm*
Do a search ranking all items with “IE” or “Internet Explorer” in them equally: WORDS (IE, Internet
Explorer)
MCT USE ONLY. STUDENT USE PROHIBITED
3-16 Interacting with the Search Service
Note: You should be careful with the filenames in files that you index. The default word
breaking engine in SharePoint will only break the words apart if they have underscores (“_”) or
dashes (“-“). If you search for a name of a document that has no word breakers, you will not find
them based on the filename unless you use a wildcard prefix.
Property specification. These are the managed properties or full-text index you are querying upon.
Operators are similar to KQL, but include a couple that KQL does not have. Operators include:
AND. Returns only items that match all expressions.
ANDNOT. Returns items that match first operand and do not match the second.
ANY. Similar to OR, but number of operands and distance between do not matter.
COUNT. The number of query terms an item must have to be included in results.
DATETIME. Used for explicit type conversion. In most cases this is not needed when the target
managed property is of the proper type.
DECIMAL. Used for explicit typing of numeric values.
ENDS-WITH. The given expression must be at the end of the managed property.
NEAR. Used to find items that are N terms away from each other.
OR. Used to find items with multiple expressions. Items that match more of the OR operands are
higher in the rankings.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 3-17
STARTS-WITH. A managed property value must start with the given expression.
Note: Note that FQL allows both prefix and suffix wildcard searches, and KQL only allows
prefix searches.
Additional Reading: For more information on FAST Query Language, see FAST Query
Language (FQL) syntax reference at http://go.microsoft.com/fwlink/?LinkId=321932.
Enabling FQL
To enable FQL in your applications, you must set the EnableFQL property on the search query. This can be
done programmatically and in REST service calls.
Changed in FQL
FQL isn’t exactly the same FQL from SharePoint 2010. Here are some changes you should be aware of:
ANY operator is the same as the OR operator, but can also be replaced with the WORDS operator.
Find any items that contain Microsoft or SharePoint with relevance manipulation: or(Microsoft,
SharePoint)
Find items that contain between five and 10 instances of SharePoint: count(SharePoint, from=5,
to=10)
Find items that have Microsoft, but do not have SharePoint: andnot(Microsoft, SharePoint)
Find items that have both Microsoft and SharePoint: and(Microsoft, SharePoint)
Find any documents with Author that starts with Dan: author:starts-with(“Dan”)
MCT USE ONLY. STUDENT USE PROHIBITED
3-18 Interacting with the Search Service
Lesson 3
Executing Search Queries from Code
In this lesson you will learn the various ways to execute queries against the SharePoint search index.
Lesson Objectives
After completing this lesson, you will be able to:
Search APIs
There are several ways to submit a query to
SharePoint Search, these include:
REST
User Interface
You can perform a search from any site in the SharePoint farm by using the search textbox. If you have set
up a global search center URL, all queries will go to the same URL to be processed. In most cases the
query text is pulled from the query string, as shown in the following example:
http://search.contoso.com/sites/Search/Pages/results.aspx?k=sharepoint
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 3-19
http://teams.contoso.com/_vti_bin/spsearch.asmx
The service has four main methods:
Query
QueryEx
Registration
Status
Both the Query and QueryEx methods accept an XML string that contains a specially formatted query
request.
The QueryEx method returns the search results in a System.Data.DataSet object. The DataSet object
contains a System.DataSet.DataTable object for each result type that is returned.
The Query method returns the search results in a string as XML. The format for the XML is defined by the
Microsoft.Search.Response and Microsoft.Search.Response.Document schemas. The full set of search
results is contained in the Results element of the Microsoft.Search.Response schema, with each
individual result represented by a Document element of the Microsoft.Search.Response.Document
schema.
The following code example shows how to call the SharePoint Web Service endpoint:
svc.Url = "http://search.contoso.com/_vti_bin/search.asmx";
svc.UseDefaultCredentials = true;
DataSet ds = svc.QueryEx(query);
this.GridView1.DataSource = ds;
this.GridView1.DataBind();
MCT USE ONLY. STUDENT USE PROHIBITED
3-20 Interacting with the Search Service
Here is an example of how to use the KeywordQuery class and its Execute method to run a query:
Server-Side Code to Call SharePoint Search by Using KeywordQuery.Execute with FQL Query
SearchQueryAndSiteSettingsServiceProxy settingsProxy =
SPFarm.Local.ServiceProxies.GetValue<SearchQueryAndSiteSettingsServiceProxy>();
SearchServiceApplicationProxy searchProxy =
settingsProxy.ApplicationProxies.GetValue<SearchServiceApplicationProxy>("Contoso
Search");
In some cases you will want to execute more than one query at a time. You can do this by migrating your
older code to the new SearchExecutor class.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 3-21
The following code examples show how to utilize the SearchExecutor class to execute multiple queries:
Code to Run More Than One Query by Using the SearchExecutor Class
public static Dictionary<string,DataTable> ExecuteMultipleQueries()
{
DataTable tableResults = null;
Dictionary<string, DataTable> searchResults = new Dictionary<string, DataTable>();
queries.Add("local", query1);
using (KeywordQuery query2 = new KeywordQuery(site))
{
query2.QueryText = "title:\"SharePoint\"";
query2.RowLimit = 100;
Source remoteSource = GetSearchSource("Twitter");
query2.SourceId = remoteSource.Id;
queries.Add("remote", query2);
Demonstration Steps
1. Start the 20489B-LON-SP-03 virtual machine.
6. Review the button1_click method. Notice that the calls are being made by using the Server Side
Object Model. Note that you could get back multiple result tables.
The client-side object model also provides the ability to execute multiple search queries at once. You
simply create more instances and add them to a generic dictionary that is passed to the ExecuteQueries
method. You can also use the KeywordQuery to specify the result source on which you want to execute
the query. You can use the GetSearchSource method to find a result source by name and then set the
SourceId property on the KeywordQuery class.
When you execute a query in an app, by default the query will run in the context of the app. The
implication of this is to restrict result sets based on the app principal, rather than the user principal. Often
you will want queries to run in the context of the user rather than the app. To enable queries to run in the
context of the current user rather than the app, you must specify the QueryAsUserIgnoreAppPrincipal
permission scope. When you use the QueryAsUserIgnoreAppPrincipal permission scope, the search
service will provide search results that the app would not otherwise have permission to access.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 3-23
Demonstration Steps
1. Start the 20489B-LON-SP-03 virtual machine.
6. Review the button1_click method. Notice that the calls are being made by using the Client Side
Object Model classes that look exactly like the service-side object model. Also point out the possibility
of getting multiple result tables back.
9. Click Search. You should get results back in the grid view.
http://server/_api/search/query?querytext='sharepo
int'
Additional Reading: For more information on the available properties and endpoints, see
SharePoint Search REST API overview at http://go.microsoft.com/fwlink/?LinkId=321935.
The following code example shows you how to execute search queries by using REST:
try
{
WebResponse res = req.GetResponse();
XDocument oDataXML = XDocument.Load(res.GetResponseStream(), LoadOptions.None);
XNamespace atom = "http://www.w3.org/2005/Atom";
XNamespace d = "http://schemas.microsoft.com/ado/2007/08/dataservices";
XNamespace m = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";
this.dataGridView1.DataSource = searchResults.ToArray();
this.dataGridView1.Refresh();
}
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 3-25
Demonstration Steps
1. Start the 20489B-LON-SP-03 virtual machine.
http://search.contoso.com /_api/search/query?querytext='Sharepoint'&enablefql=true
4. You should get an HTTP 500 error, because the default result source has a KQL query expression as its
query transform.
14. Switch to the first browser tab, then press F5 to refresh the page. You should now see results using
the FQL query.
15. Switch back to SharePoint Central Administration.
16. Set the Local SharePoint Results result source as the default.
MCT USE ONLY. STUDENT USE PROHIBITED
3-26 Interacting with the Search Service
The management team at Contoso is concerned about the proliferation of duplicate content across the
new intranet portal. The team wants to provide a way for users to check, given a particular document,
whether similar content exists elsewhere on the portal. To implement this functionality, you will create an
app that uses client-side search APIs to query the search index for similar content. In addition to using the
client applications, they would also like to be able to find items based on metadata, but without having to
type the queries. They would like you to add a custom action to the menu items to redirect to the client
app.
Objectives
After completing this lab, you will be able to:
Create a SharePoint App that uses the REST API to retrieve search results.
Understand how to use the REST Search APIs.
Lab Setup
Estimated Time: 60 minutes
Password: Pa$$w0rd
A warm-up script named WarmUp.ps1 runs automatically when you start the virtual machine. This script
helps to improve the performance of the virtual machine by downloading the home page of the root site
in each site collection on the server. Occasionally this script displays timeout errors; you can ignore these
errors. You should ensure this script has finished running before you start the lab.
2. If you are not already logged on, log on to the LONDON machine as CONTOSO\Administrator with
password Pa$$w0rd.
3. Create a new App for SharePoint project named SearchApp in the E:\Labfiles\Starter folder. The
project should:
a. Use the SharePoint-hosted app model.
4. Open the default.aspx page and delete all the markup within the PlaceHolderMain content control.
6. Open the App.js file, and delete the contents of the file.
var context;
var web;
var user;
var currentItem;
var hostweburl;
var appweburl;
var title;
function getQueryStringParameter(paramToRetrieve) {
var params =
document.URL.split("?")[1].split("&");
var strParams = "";
for (var i = 0; i < params.length; i = i + 1) {
var singleParam = params[i].split("=");
if (singleParam[0] == paramToRetrieve)
return singleParam[1];
}
}
function GetListId() {
return decodeURIComponent(getQueryStringParameter("ListID"));
}
function GetHostSiteUrl() {
return decodeURIComponent(getQueryStringParameter("SPHostUrl"));
}
function GetAppSiteUrl() {
return decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
}
function GetItemId() {
return getQueryStringParameter("ItemID");
}
9. Add a function named getSearchResults. The function should accept a single argument named
queryText.
10. Within the getSearchResults function, add code to display the text Search results for [queryText],
where queryText is the value of the queryText parameter, in the search-title div element.
11. Construct a URL that uses the REST API to submit the query text to the search service. You should
construct this URL by concatenating:
12. Instantiate a new SP.RequestExecutor instance named executor. Pass in the URL of the app web as
an argument to the constructor.
MCT USE ONLY. STUDENT USE PROHIBITED
3-28 Interacting with the Search Service
13. Call the executeAsync method on the executor object to send an HTTP GET request to the URL you
constructed. The method should:
a. Call a callback handler method named onGetSearchResultsSuccess if the request was successful.
b. Call a callback handler method named onGetSearchResultsFail if the request returns an error.
14. Add a function named onGetSearchResultsSuccess. The function should accept a single argument
named data.
15. Add a function named onGetSearchResultsFail. The function should accept arguments named data,
errorCode, and errorMessage.
16. In the onGetSearchResultsSuccess function, add the following code to parse the returned JSON and
display the search results:
17. In the onGetSearchResultsFail function, add the following code to display an error message to the
user.
22. On the SearchApp page, in the search text box, type Contoso, and then click Go. You should see
results presented in the app web page. This may take one to two minutes.
Note: Complete sample code for the App.js file is available in the
E:\Labfiles\Starter\App.js file.
Results: A new SharePoint App that uses Search REST API calls.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 3-29
2. Specify that the custom action should be exposed on the host web.
3. Set the scope of the custom action to List Template, and specify a specific scope of Document
Library.
~appWebUrl/Pages/Default.aspx?{StandardTokens}
&HostUrl={HostUrl}&Source={Source}
&ListURLDir={ListUrlDir}
&ListID={ListId}&ItemURL={ItemUrl}&ItemID={ItemId}
Note: You will need to start by loading an SP.Web object that represents the host web.
Use the utility methods in the App.js file to retrieve ID values for the list and the list item.
9. Using the title of the current list item as the query text, submit a search query using the code you
developed in the previous exercise.
10. Save your work, and then use Visual Studio to deploy the search app.
11. When prompted, trust the search app. You will test the app in the next task.
2. Use the Northwind Traders Contract.docx document to test your new custom action.
3. On the Documents page, on the Northwind Traders Contract row, click the ellipsis.
4. In the Northwind Traders Contract.docx dialog box, click the ellipsis, and then click Search. You
will be redirected to the App web page and a search is performed based on the Title of the
document.
Note: At this point, the app is designed to run only when a user clicks the custom action
menu item labeled Search. If you try to debug the app directly, you will see a JavaScript error
because there is no list item associated with the app. You must deploy the app and launch it from
the Edit Control Block on a document.
You learned about the two search query languages, Keyword Query Language and FAST Query Language.
Finally, you were shown how to submit those queries through the various SharePoint search APIs,
including Web Services, Server Object Model, Client Object Model, and REST Services.
Review Question(s)
Administration
Content Processing
Analytics
Crawler
Index
Which of the following search queries will return all Word documents modified after
1/1/2013?
What is the maximum query length of a search query when using the user interface?
1,024
512
2,048
4,096
256
What permission does an App for SharePoint need in order to execute search queries?
Search, QueryAsUserIgnoreAppPrincipal
Web, FullControl
Tenant, FullControl
MCT USE ONLY. STUDENT USE PROHIBITED
4-1
Module 4
Customizing the Search Experience
Contents:
Module Overview 4-1
Module Overview
Microsoft® SharePoint® 2013 provides an out-of-the-box search experience that is adequate for many
uses. However, there are several scenarios where administrators and developers will want to customize the
Search Center, the Search Center pages, which results are displayed, and how results are displayed. In this
module, you will learn how to customize various aspects of the search experience, including how
SharePoint processes queries, how search results are presented to the user, and how SharePoint processes
crawled content prior to indexing.
Objectives
After completing this module, you will be able to:
Customize query processing by creating and configuring result sources, query transforms, and query
rules.
Customize search results by creating and configuring search pages, search web parts, result types,
display templates, and refiners.
Customize content processing by configuring entity extractors, thesauri, and content enrichment web
services.
MCT USE ONLY. STUDENT USE PROHIBITED
4-2 Customizing the Search Experience
Lesson 1
Customizing Query Processing
In the past, search would simply handle a user or application keyword query and present a set of results
from a single source, such as SharePoint, in a static format. Search technologies have evolved to allow
multiple result sources, providing the display of rich content results with the ability for each result to have
a custom look and feel. This lesson will teach you how SharePoint Search performs these types of tasks
and the control you have over customizing the query process via programmatic interfaces.
Lesson Objectives
After completing this lesson, you will be able to:
Result Sources
SharePoint Search gathers content from content
sources that search administrators have configured.
These sources can be of any type and in any
number of places. Out-of-the-box SharePoint
Search can connect to SharePoint, File Shares,
Exchange, and many more sources. As a developer,
you can enhance search to implement Business
Connectivity Connectors to index any content that
resides on your network. The Search Gatherer
gathers content that resides in these sources and
put it into the index. No matter where the content
comes from, its crawled properties end up in the file
system-based index in a common format.
Once in the index, you can create Result Sources that partition the data based on managed properties. In
this way, result sources limit searches to certain content or to a subset of search results. Result Sources
support the following protocols:
Local SharePoint
Remote SharePoint
OpenSearch
Not only are Result Sources used to partition SharePoint content, but they are also used to implement
search federation. Search federation is used to display results from external search systems. Because of the
support of OpenSearch, you can create a Result Source that targets external systems like Bing, Twitter, and
many more.
Twitter: http://twitter.com/search?q={searchTerms}
Bing: http://www.bing.com/search?q={searchTerms}
Query Transforms
In addition to a protocol, Result Sources can be configured with Query Transforms to implement the
partitioning mentioned above. These Query Transforms can be manually typed in or, in most cases due to
ease of use, be created by using the Query Builder tool. Like regular search queries, Query Transforms can
be simple or very complex. The real power of Result Sources comes from the Query Transforms applied to
them.
Authentication
Lastly, you can set up a username and password for basic authentication to external sources in Result
Sources.
Items matching a content type. Items that match a content type that the incoming query specifies.
Items matching a tag. Documents or list items that match a managed metadata term.
Items related to current user. Documents or list items that are related to the user.
Local People Results. People items from the profile database of the User Profile service application.
Local Reports and Data Results. Excel®, Office Data Connection (ODC), or Report Definition Language
(RDL) items, or items in a report library.
Local SharePoint Results. All items from local SharePoint search index except People.
Local Video Results. Videos.
Recently changed items. Documents and list items sorted by modified date.
MCT USE ONLY. STUDENT USE PROHIBITED
4-4 Customizing the Search Experience
Recommendations. Documents and list items that you recommend for the incoming query.
You can set any result source as the default result source. When you add a Content Search Web Part to a
page, the Web Part automatically uses the default result source.
The following code example shows how to create a new result source:
// Get the search service application info object so we can find the Id of our Search
Service App.
SearchServiceApplicationInfo ssai = searchProxy.GetSearchServiceApplicationInfo();
Microsoft.Office.Server.Search.Administration.SearchService.Service.SearchApplications
.GetValue<SearchServiceApplication>(ssai.SearchServiceApplicationId);
As you can see from the code example, you need several pieces of information to set up a result source.
The main piece of information is the owner, and the second most important is the Provider ID. The valid
provider keys are:
OpenSearch Provider
Personal Favorites Provider
The following code example shows how to create result sources by using Windows PowerShell:
# define query
$query = '{searchTerms?}'
$resultSource = $fedManager.CreateSource($searchOwner)
$resultSource.Name = 'My Custom Source'
$resultSource.ProviderId = $fedManager.ListProviders()['Local SharePoint Provider'].Id
$resultSource.CreateQueryTransform($query)
$resultSource.Commit()
$site.dispose()
MCT USE ONLY. STUDENT USE PROHIBITED
4-6 Customizing the Search Experience
Query Transforms
A result source is defined by the Query Transform
that is applied on it. A Query Transform interprets a
user’s query and to modify it to provided targeted
results. A Query Transform is made up of two main
parts:
Query Filter
Sorting
Query Filter
A query filter is simply a query based on a set of
parameters passed into it or manually set. It can be
made up of Keyword and Property Filters.
Sorting
You can sort the result source based on a set of managed properties, a ranking model, or dynamic
ordering rules.
The last item to modify a query is the query transform in the result source. These changes are always
applied.
Query from the search box. This takes the value from the connected search box web part on a search
results page.
Name of the user who runs the query. This will pull the current SPUser’s name from the Query context
and pass it into the query.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 4-7
Value of a parameter from URL. This allows you to pull a value from the QueryString of the Search
Results page URL and pass it into the query.
Only return sites. Adds a managed property search that tells search to query only for sites.
Only return lists and libraries. Adds a managed property search that tells search to query only for lists
or libraries.
Only return items. Adds a managed property search that tells search to query only for list items.
As you can see, the possibilities for the type of result source you can build are limited to your metadata
and imagination.
By Content Type
By Modified Date
MCT USE ONLY. STUDENT USE PROHIBITED
4-8 Customizing the Search Experience
By Tag
By Path
By Title
Sort Levels
You don’t have to base the sort on a single property; instead, you can have several levels of sort. For
example, you can sort by the title first and then the modify date, or sort first by the modify date and then
the author.
Ranking Models
You can also select one of the 15 built-in ranking models. The default search model is based on the
industry-standard BM25 ranking function. These models include:
Dynamic Ranking
As a final step in sorting, you can specify a Dynamic Ordering Rule. This rule enables you to promote
items based on several conditions. These conditions include:
Promote to top
Promote by 1-10
No change
Demote by 1-10
Demote to bottom
{[SortList, LastModifiedTime:Descending]}
The available properties that can be added to the QueryTransformProperties are not well documented,
but you can get a good idea of what they are by evaluating the out-of-the-box Result Sources. Another
method is to simply build some queries with the Query Builder and then review the QueryTransform
object that is generated.
Once you have constructed your QueryTransformProperties object, you can optionally pass it in with
your query template to the CreateQueryTransform method of the Result Source. This method has two
overrides and does not need a QueryTransformProperties object. After creating the QueryTransform,
you need to call the Commit method on the Result Source to save the changes.
The following code example shows how to create a query transform programmatically:
MCT USE ONLY. STUDENT USE PROHIBITED
4-10 Customizing the Search Experience
// Get the search service application info object so we can find the Id of our Search
Service App
SearchServiceApplicationInfo appInfo = searchProxy.GetSearchServiceApplicationInfo();
SearchServiceApplication application =
Microsoft.Office.Server.Search.Administration.SearchService.Service
.SearchApplications.GetValue<SearchServiceApplication>(appInfo.SearchServiceApplicationId
);
Microsoft.Office.Server.Search.Administration.Query.FederationManager fedManager = new
Microsoft.Office.Server.Search.Administration.Query.FederationManager(application);
SearchObjectOwner owner = new SearchObjectOwner(SearchObjectLevel.SPSite,
oSPsite.RootWeb);
The following code example shows how to modify an existing query transform:
// Get the search service application info object so we can find the Id of our Search
Service App
SearchServiceApplicationInfo appInfo = searchProxy.GetSearchServiceApplicationInfo();
SearchServiceApplication application =
Microsoft.Office.Server.Search.Administration.SearchService.Service
.SearchApplications.GetValue<SearchServiceApplication>(appInfo.SearchServiceApplicationId
);
Microsoft.Office.Server.Search.Administration.Query.FederationManager fedManager = new
Microsoft.Office.Server.Search.Administration.Query.FederationManager(application);
SearchObjectOwner owner = new SearchObjectOwner(SearchObjectLevel.SPSite,
oSPsite.RootWeb);
Demonstration Steps
1. Start the 20489B-LON-SP-04 virtual machine.
5. On the Contoso Team Site home page, click Settings, and then click Site settings.
9. Notice that you are not setting the Query template, and then click Save.
10. On the Windows Start page, click Computer.
12. In the How do you want to open this type of file (.sln) dialog box, click Visual Studio 2012.
13. In Visual Studio®, in Solution Explorer, double-click Program.cs. Review the code, and notice each of
the steps that are required to get a Search context and that this result source is scoped at a site
collection level. Note the way to create the QueryTransformProperties object. Notice that after all
items have been set, you make a call to Commit to save your changes.
16. Click the My Custom Source result source. Notice that the Query template is now populated, and
then click Launch Query Builder.
17. In the Build Your Query dialog box, click the SORTING tab, notice that the sort is now based on the
LastModifiedTime in descending order, and then click Cancel.
Query Rules
Query rules are used to attempt to capture the
intent of a user query. When executed, they return
results that better match that intent. This is new
functionality that was not available in SharePoint
2010. Each query rule is made up of four main
parts:
Scope\Context
Query Conditions
Query Actions
Publishing Settings
Scope\Context
Each query rule is tied to a specific scope. This scope can be based on:
Result Source. You can target all result sources or a specific result source.
User Segments. You can target particular users that have certain metadata tags associated with them
(Department, Job Title, Location).
Note: Query Rules are the replacement for keywords in SharePoint 2010. When upgrading
to SharePoint 2013, keywords are automatically converted to Query Rules.
Publishing Settings
You can set a query rule to apply during a set timeframe. By default, a rule will be active until you
manually deactivate it. Deactivating a rule is done on the Query Rule administration page via the drop-
down list. Some examples of how you can use the publishing settings are:
Query Conditions
Aside from the Query Rule scope, you must set up
Query Conditions. When these conditions evaluate
to true, the Query Rule actions will execute. Query
Rules can be any of the following:
Query Actions
When a Query Condition evaluates to true, you can have any one of the following actions execute:
Add promoted results. This is a result that will appear at the top of the search results, and is similar to
keywords and best bets in 2010.
Add result blocks. This is a result set that is embedded in the default result set and will show at the top
of the results, or can be integrated into the core results. This is similar to how federated searches
worked in SharePoint 2010.
Change ranked results by changed the query. This can be used to add query filters to a user’s search
query to further refine what they are looking for based on past search results and user feedback.
Demonstration Steps
1. Start the 20489B-LON-SP-04 virtual machine.
7. On the Manage Query Rules page, in the Select a Result Source list, click Local SharePoint
Results (System).
9. On the Add Query Rule page, in the Rule name box, type SharePoint.
10. Click the Context link to expand the context configuration section.
12. In the Query Conditions section, in the Query exactly matches one of these phrases (semi-colon
separated) box, type SharePoint.
13. In the Actions section, click the Add Promoted Result link.
14. In the Add Promoted Result dialog box, in the Title box, type Microsoft SharePoint.
15. In the URL box, type http://www.microsoft.com/sharepoint, and then click Save.
16. On the Add Query Rule page, click the Publishing link to expand the publishing section.
17. For the Start Date, click the calendar icon, and then click today’s date.
18. For the End Date, click the calendar icon, click one week from today, and then click Save.
19. Click the Contoso Search link.
20. On the Search homepage, in the text box, type SharePoint, and then press Enter. You should see the
promoted result at the top of the page.
21. Close Internet Explorer.
The following code example shows how to import a search schema into a SharePoint site
programmatically:
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 4-15
// Import a configuration.
port.ImportSearchConfiguration(owner, import);
}
You can export and import result sources, query rules, result types, ranking models, and search settings at
the site collection or site level. You can also export search settings from a Search service application and
import the settings into a site collection. However, you cannot import search settings into a Search service
application.
Lesson 2
Customizing Search Results
In this lesson you will learn how to customize the search experience of the result pages. This includes the
pages they use to submit their queries and the result pages that display their results. Each result can be
classified by using result types, which then can be customized to be shown in various ways by using
display templates. Finally, if users are presented with hundreds of thousands of results, they will need a
way to narrow the results by using out-of-the-box and custom refiners.
Lesson Objectives
After completing this lesson, you will be able to:
Everything (results.aspx)
People (peopleresults.aspx)
Conversations (conversationsresults.aspx)
Videos (videoresults.aspx)
Search Box
Search Navigation
Search Results
Refinement
The only difference between each of these pages is the way the web parts are configured. The main
configuration difference is the Search Results web part. It has a different result source targeted for each
page, and as a result, you see targeted results when you are viewing each respective page.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 4-17
Query Settings
As part of the query settings, you can specify if you want Query Rules to execute on the search results.
You can also elect to have the URL rewritten for catalog pages (which are discussed in later modules).
Finally, you can have the web part submit the query when the page loads on the server side, or from the
browser after the page has loaded. The default is to execute the query from the browser, because this
makes it seem to the user that the page has loaded very quickly, even though results may not show up on
the page immediately.
Although you could programmatically update a web part on a web part page such as a results page, it is
not common to do so. It is typically done via the SharePoint UI and via the Query Builder dialog.
Result Types
When you have set up your content sources, search
will have indexed many different types of content,
from Adobe PDF files to Microsoft Word
documents. You will also index several types of
SharePoint content, including sites, HTML pages,
lists, list items, and many more. Each of these
different types of content should be displayed
differently. In the past, they were all displayed
exactly the same way: a title, a summary area, and a
link. You would then click on the link to view the
content wherever it resided and in the viewer
specific to that piece of content.
Search has evolved to provide a much more customized experience in which you see a different view of
the item based on its content type.
The way an item is rendered is based on Result Types. A result type is based on a particular type of
content. It has the following settings:
Source
Conditions
Actions
Source
The source is any visible Result Source including the “All Sources” option.
MCT USE ONLY. STUDENT USE PROHIBITED
4-18 Customizing the Search Experience
Conditions
A condition uses a managed property and then an operator and value. If the condition evaluates to true,
then the action is performed. A condition can utilize the following operators:
Equal and of
Contains any of
As you can see, a condition can match against multiple values. Multiple conditions must be combined
with the “AND” operator.
Actions
An action will determine the display template that is used if the condition has been met.
Display Templates
Display templates enable you to design the way a
search result will render. This can be in the Search
results web part, the Content Search web part, or
any other web part that renders search results.
Display templates are simple HTML files that have
special JavaScript markup in them to tell SharePoint
how to render the managed properties of a result
item.
Group. Group Display Templates are used to group together a number of Item Display Templates.
They can appear in Control Display Templates. They are used in the Search Results web part.
Item. Item Display Templates enable you to specify which managed properties are used and how they
appear for a result. They are used by the Content By Search and Search Results web parts.
Filter. Filter Display Templates enable you to create customized refinement controls that will appear in
the Refinement web part.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 4-19
Once you have selected a display template type, you can then specify the types of controls that can use
the display template. This includes:
SearchResults
SearchHoverPanel
SearchBox
Custom
SharePoint 2013 provides a wide range of out-of-the-box display templates for search, and you will
probably want to use these templates as the basis for your own custom templates. The Search-based
display templates live in the folder“/_catalog/masterpage/Display Templates/Search”. You should see
templates for the following:
BestBets
Common
Community
Default
Discussion
Excel
MicroBlog
Office Document
OneNote
Person
Personal Favorite
Picture
PowerPoint
Reply
Site
Video
WebPage
Word
MCT USE ONLY. STUDENT USE PROHIBITED
4-20 Customizing the Search Experience
The easiest way to view and edit these files is via SharePoint Designer. There are several files in this
directory, however, you should see that for each .html file there is a corresponding .js file. This .js file is
built for you and is similar to how publishing from Word into HTML works via thicket files (a file with a
linked folder containing resources). Each time you edit the .html file, the .js is updated. You will also notice
that there is a specific naming convention used for the file names. For example, if you look at the Person
display template, you will see six files:
Item_Person.html
Item_Person.js
Item_Person_CompactHorizontal.html
Item_Person_CompactHorizontal.js
Item_Person_HoverPanel.html
Item_Person_HoverPanel.js
You should use the same naming standard that Microsoft uses when creating your display templates. In
the example above, all files start with Item_. This tells you that this is an Item display template. The next
part will be the name of the display template, in this case Person. The third part delimited by the
underscore character is a special helper display template. You can see both a CompactHorizontal and a
HoverPanel helper. These drive the hover callout of the result when you move the mouse over the result.
Note: The naming convention is not what determines where and how a display template is
used. It is determined by the content type that is applied and the metadata of the item. Also, the
use of the hover panel is set in the JavaScript of the display template.
Title
TemplateHidden
MasterPageDescription
ContentTypeId
TargetControlType
HtmlDesignAssociated
ManagedPropertyMapping
Body
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 4-21
Each of these can be editing via the file, but it is also possible to do this through SharePoint UI by editing
the file properties when viewing it in the browser. When you change these in the UI, they will be updated
in the file.
The body of the display template is where the real work happens. As you can see in the code snippet
below, you will be passed a ctx variable that will contain all the information about the result item. You can
then write JavaScript code that will render the managed properties. It is important to point out that in this
template, you will see that it is rendering a div tag for each Word document. The div tag has an id
attribute and that attribute is set to the itemId of the search result item. This ensures that all your div tags
have a unique id and can be referenced easily by other JavaScript code that you might add to the display
template.
You will also notice that to switch in and out of code mode, you must use the “<!--#_” and “_#--
>”notation.
In this code example, you can see the Item_Word.html display template. As you can see, there is some
very important markup at the top of the file. This markup drives how the SharePoint UI works with the
display template:
Demonstration Steps
1. Start the 20489B-LON-SP-04 virtual machine.
8. On the Add Result Type page, in the Give it a name box, type Word Documents.
9. Click Show more conditions to expand the advanced conditions area.
10. In the Which custom properties should match? list, click FileType.
14. In the What should these result look like? list, click Office Document Item, and then click Save.
Refiners
When a user submits a search query, they can be
presented with thousands of results. Based on the
default ranking model that SharePoint uses, the
item that they are looking for may not show up in
the first page of results. When this happens, they
need a way to drill down into what they are looking
for. This is called refining your results.
ContentClass
ContentTypeId
WebTemplate
DisplayAuthor
LastModifiedTime
These are configured via the Refinement web part that exists on search result pages. By editing the
refinement web part, you can add any managed properties that have been configured to be an active
refiner. By default, managed properties do not have the Refinement property enabled. After enabling,
you must re-index your content in order to get any refinement values to display.
Refiner Properties
Each refiner has a series of properties. This includes:
Type. Text, integer, datetime, and so forth.
Display name. The name that should be displayed to users. Note that some managed property names
are not very meaningful, and that this property enables you to override what is displayed.
Display template. How the refiners will display. Text-based refiners are normally just a list, whereas
datetime-based refiners can show the date slider.
Sort by. You can sort based on count, name, and number.
Maximum number of refiner values. How many items should show in the refiner area.
Refinement Counts
Another interesting fact about refiners is that the refinement counts are not displayed by default. You
must enable these in the display templates.
MCT USE ONLY. STUDENT USE PROHIBITED
4-24 Customizing the Search Experience
Active
Active latent
Note: Although you can create your own managed properties at the site collection level,
you cannot create managed properties that can be used as refiners. This must be done at the
service application level. Even if you were able to do this, you will still need a service application
administrator to run a full crawl for you in order to use your managed property.
Once you have created a refinement-based managed property, you must add it to the refinement web
part. Because this is a setting of the web part on a particular search results page, it will not be something
that you will normally do programmatically (not that it can’t be done programmatically, it’s just not
common).
The Refinement web part will present you with a list of all available managed properties that you can use
as a refiner. You simply select the refiner you want to add, click Add, and then configure the refiner. As
previously mentioned, each refiner has a series of properties that you must configure. All of these
properties are conveniently displayed in the refinement web part’s configuration dialog.
Demonstration Steps
1. Start the 20489B-LON-SP-04 virtual machine.
3. On the Windows Start page, type SharePoint, and then click SharePoint 2013 Central
Administration.
6. In the quick launch section, under Queries and Results, click Search Schema.
7. In the Managed property box, type Author, and then press Enter.
9. Note the Refinable property is set to Yes - active; this allows the property to be used as a refiner.
10. Open a new browser tab, in the address bar, type http://search.contoso.com, and then press Enter.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 4-25
11. On the Search home page, in the text box, type SharePoint, and then press Enter.
12. On the results page, click Settings, and then click Edit page.
13. In the Navigation Zone section, click the Refinement Web Part Menu drop-down arrow, and then
click Edit Web Part.
17. In the Display name box, type Author, and then click OK.
The power of the CSWP comes in its configuration abilities. Similar to the search results web part and the
result sources, you can use the Query Builder to target specific content that you would like to display in
the web part, and therefore on a web page. In addition to targeting specific content, you can also utilize
special display templates to display the content. The display templates that show by default are:
Diagnostic
Large picture
Two lines
Video
MCT USE ONLY. STUDENT USE PROHIBITED
4-26 Customizing the Search Experience
You can add your own custom display templates for use in the CSWP. These are slightly different from the
display templates used for search results. When you select a display template, the editing dialog will
change. For example, when you select the Diagnostic display template, you will see that you have the
option to add up to 10 managed properties for output. This is helpful when you want to see what
properties a specific index item has. By contrast, the Picture on left, 3 lines on right display template
this only lets you select three managed properties to display.
In addition to pulling results from a locally configured query, you can also have the Content Search web
part fed results from another search web part (such as the search results web part). This enables you to
customize a search results web page to have other results display in a very specific manner (such as a
Twitter or Bing feed).
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 4-27
Objectives
After completing this lab, you will be able to:
Lab Setup
Estimated Time: 75 minutes
Password: Pa$$w0rd
A warm-up script named WarmUp.ps1 runs automatically when you start the virtual machine. This script
helps to improve the performance of the virtual machine by downloading the home page of the root site
in each site collection on the server. Occasionally this script displays timeout errors; you can ignore these
errors. You should ensure this script has finished running before you start the lab.
2. If you are not already logged on, log on to the LONDON machine as CONTOSO\Administrator with
password Pa$$w0rd.
5. Make a copy of the Item_Default.html display template in the same folder, and name the copy
Item_Tasks.html.
7. Change the title of the display template to Task Item, then save the file.
9. In the browser user interface, browse to the search display templates in the master page gallery.
10. Locate the Item_Tasks.html file. Notice that SharePoint has automatically created an associated
JavaScript file named Item_Tasks.js.
11. Edit the properties of the Item_Tasks.html item, and select all available target control types.
12. At the site collection scope, create a new result type named Tasks.
13. Configure the result type conditions to match items with a content type of Task.
14. Configure the result type actions to use the Item Task display template, and then save your changes.
15. On the Search site home page, run a search for ContentType:Task.
16. SharePoint will display five results. Notice that there is no visual difference between the new display
template and the standard (out-of-the-box) display template.
Note: You will customize the Item Task display template in the next exercise.
Results: After completing this lab, you should have created a new result type and a new display template.
_#=ctx.RenderBody(ctx)=#_
<h3>
<img src="/_layouts/images/icon_tasklist.gif" style="padding-right:5px;border:0px"/>
Title: <a href='_#=ctx.CurrentItem.Path=#_'>_#=ctx.CurrentItem.Title=#_</a><br />
Assigned To: _#=ctx.CurrentItem.AssignedTo=#_<br />
</h3>
Note: You may notice that SharePoint Designer displays some schema errors in the HTML
file. You can safely ignore these errors.
Results: After completing this exercise, you should have customized an item display template.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 4-29
3. Make a copy of the Item_Default_HoverPanel.html display template in the same folder, and name
the copy Item_Tasks_HoverPanel.html.
5. Locate the line of code that sets a variable named hoverUrl to the URL of the
Item_Default_HoverPanel.html file. Amend this code to specify the URL of the
Item_Tasks_HoverPanel.html file.
<br/>
Modified: _#=ctx.CurrentItem.LastModifiedTime =#_
11. On the Search site home page, run a search for Project.
12. Move the mouse over one of the results. Notice that the hover panel appears, showing the Modify
date.
13. Close Internet Explorer, and then close SharePoint Designer 2013.
Results: After completing this exercise, you should have created a hover panel display template for your
custom Task result type.
MCT USE ONLY. STUDENT USE PROHIBITED
4-30 Customizing the Search Experience
Lesson 3
Customizing Content Processing
In this lesson you will learn how to supplement the content processing to meet your organization’s search
needs. This will involve configuring search to handle both structured and unstructured data. You will also
learn how to supplement SharePoint search logic with your own business logic for enhancing managed
property values.
Lesson Objectives
After completing this lesson, you will be able to:
Entity Extractors
Many organizations have terabytes of data, much of
it unstructured. Unstructured simply means that it
has no metadata wrapped around it that can be
easily abstracted via a common algorithm or
process. In these cases, this data can be queried
only based on the text that is abstracted. FAST
Search in SharePoint 2010 introduced a concept
called entity extractors. These extractors are
designed to look for keywords in this unstructured
content and build a structured way of searching for
common content. This feature was moved forward
into SharePoint 2013 search.
Word Extraction. Case-insensitive dictionary entries matching tokenized content, with a maximum of
five dictionaries.
Word Part Extraction. Case-insensitive dictionary entries matching un-tokenized content, with a
maximum of five dictionaries.
Word Exact Extraction. Case-sensitive dictionary entries matching tokenized content, with a maximum
of a single dictionary.
Word Part Exact Extraction. Case-sensitive dictionary entries matching un-tokenized content, with a
maximum of a single dictionary.
As you can see, you don’t have an unlimited number of extractors like you had in FAST Search. You are
limited to a total of 12 entity extractors.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 4-31
Microsoft.UserDictionaries.EntityExtraction.Custom.Word.[1-5]
Microsoft.UserDictionaries.EntityExtraction.Custom.WordPart.[1-5]
Microsoft.UserDictionaries.EntityExtraction.Custom.ExactWord
Microsoft.UserDictionaries.EntityExtraction.Custom.WordWordPart
To create a new entity extractor, you should create a new text file on a network share. You then add
content to it in comma separated format.
When you have created the file, you can use Windows PowerShell to import the entity definitions into
SharePoint.
The following code example shows how to import an entity extraction file into SharePoint by using
Windows PowerShell:
Deploying
In previous versions of SharePoint Search, the
thesaurus file was stored on the file system, changes could be made directly against a file, and then you
could simply restart the Search service to apply the changes. In SharePoint 2013, you can no longer
modify the thesaurus in this way. Similar to Entity extractors, you must build and maintain a comma-
separated file that you then deploy via Windows PowerShell. Each time you want to make a change to the
thesaurus, you must update the entire thesaurus file. There is no delta update functionality, nor is there
any means of exporting thesaurus settings.
For each thesaurus entry, you also have the option of specifying the language that that entry will target.
Reference Links: For more information on the supported languages, see Create and
deploy a thesaurus in SharePoint Server 2013 at http://go.microsoft.com/fwlink/?LinkId=321936
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 4-33
Encoding
If your entries contain language-specific special characters, you will need to make sure that the file is UTF-
8 encoded.
Case Sensitivity
Thesaurus entries are not case sensitive when being applied to queries.
Query Processing
Once you have created and deployed your thesaurus file, the search engine will process a query and look
for any query terms that match a thesaurus key. If there are any matches, the query is expanded with the
synonym(s) for that key and the search results will contain results for the original query term as well as for
the synonym. You should be aware that synonyms are only one way, so if you want IE to mean Internet
Explorer and Internet Explorer to mean IE, you would need two entries in the thesaurus file.
Replacements
Another change from the way earlier versions of SharePoint Search operated was that it enabled you to
specify replacements. With a replacement, a word would be substituted with another word in a search
query. In SharePoint 2013, all entries in the thesaurus are expansions, and the original term is not
removed from the query. The original query term is always evaluated, and you cannot remove synonyms
or words directly from the index.
Diacritical Marks
Lastly, the thesaurus no longer supports the option to specify whether diacritical marks such as accents
should be ignored or should be applied by the search system when expanding a query with terms from
the thesaurus. By default, diacritical marks are always respected when matching query terms with terms in
the thesaurus
Note: In most cases you will be adding query spelling exclusions. This is because your
company may have acronyms and product names that deviate from dictionary-based words that
SharePoint will mistake for a spelling error.
MCT USE ONLY. STUDENT USE PROHIBITED
4-34 Customizing the Search Experience
Input managed properties that you want to send to the web service.
Output managed properties that you want to get back from the web service.
You can associate trigger conditions with the content enrichment web service, based on the value of
specified managed properties in the crawled item. For example, you might configure search to call the
content enrichment web service only if the Title managed property contains the text Contoso.
You can only associate one content enrichment web service with any given search service application.
The ProcessItem method has one parameter of type Item. Item has a property called ItemProperties,
which will contain all the requested managed properties that you requested. It is your job to loop through
the various managed properties and do any processing that needs to occur. The ProcessItem method
also has a return type of ProcessedItem. Once the processing is complete, you can add any new or
modified properties to the return back into the ItemProperties property of the ProcessedItem.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 4-35
It is important that you make the code as efficient as possible. Even though the search engine is multi-
threaded, you are still introducing a lot of latency into the item processing by making the WCF call. You
should take every precaution when building the service. This includes best practices like caching results for
future use.
processedItemHolder.ItemProperties.Add(custom);
}
catch (Exception)
{
processedItemHolder.ErrorCode = UnexpectedError;
}
return processedItemHolder;
}
MCT USE ONLY. STUDENT USE PROHIBITED
4-36 Customizing the Search Experience
SendRawData. If the item is a file, this will be the actual binary of the file.
DebugMode. This will send all the managed properties of an item.
MaxRawDataSize. Some files can be very large, so you should limit the size of the data you send on
each call to the WCF service so that you don’t saturate the network.
Trigger. A search query that tells the search engine which items should be sent to the WCF service.
It is important to note that the SendRawData and DebugMode properties should only be used in a
development environment. They can cause the entire crawl process performance to drop by several
multiples (from days to weeks).
It is also important to realize that you won’t need to process every single item that exists in the index.
Your code will target only certain types of content. Therefore, there is no need for the search engine to
pass you the properties and wait for empty logic to execute. In these cases, you will use a trigger
expression that will limit the items that the search engine sends to your service. This is a best practice, and
you should always have a trigger expression.
You can remove a connection to a Content Enrichment service by running the Remove-
SPEnterpriseSearchContentEnrichmentConfiguration cmdlet.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 4-37
The following code example shows how to configure a content enrichment service by using Windows
PowerShell:
$config = New-SPEnterpriseSearchContentEnrichmentConfiguration
$config.Endpoint = "http://WCF_URL/ContentEnrichmentService.svc"
$config.InputProperties = "Author", "Filename", "Address", "Latitude", "Longitude"
$config.OutputProperties = "Author", "Filename", "Address", "Latitude", "Longitude"
$config.SendRawData = $True
$config.DebugMode = $True
$config.MaxRawDataSize = 8192
$config.Trigger = ‘NOT IsNull(Address)’
Objectives
After completing this lab, you will be able to:
Lab Setup
Estimated Time: 45 minutes
Virtual Machine: 20489B-LON-SP-04
Password: Pa$$w0rd
A warm-up script named WarmUp.ps1 runs automatically when you start the virtual machine. This script
helps to improve the performance of the virtual machine by downloading the home page of the root site
in each site collection on the server. Occasionally this script displays timeout errors; you can ignore these
errors. You should ensure this script has finished running before you start the lab.
2. If you are not already logged on, log on to the LONDON machine as CONTOSO\Administrator with
password Pa$$w0rd.
3. In the E:\Labfiles\Starter folder, create a new folder named EntityExtractor. Grant the
CONTOSO\SPFarm account read permissions on the folder.
4. In the EntityExtractor folder, create a new text file named Memory.txt.
6. Use Windows PowerShell to deploy the Memory.txt file to SharePoint as a custom extraction
dictionary.
Note: When you import the dictionary file, specify the filename in UNC format as
\\London\EntityExtractor\Memory.txt. Specify the dictionary name as
Microsoft.UserDictionaries.EntityExtraction.Custom.Word.1.
2. Browse to the search schema and edit the managed property named Title.
3. In the Custom entity extraction section, select Word Extraction – Custom1, and then save your
changes.
6. Run a full search crawl. Wait for the crawl to complete before you continue.
2. Run a search for mp3 player, and verify that several results appear.
3. On the search results page, open the settings pane for the Refinement web part.
4. Add the WordCustomRefiner1 refiner to the Refinement web part. Set the display name for the
refiner to Memory.
5. Apply your changes, and then save and check in the page.
7. In the refiners on the left of the page, click 8GB. Notice that the search results are filtered to show
only those items that include 8GB in the title or description.
Results: After completing this exercise, you should have created, deployed, and tested a custom entity
extractor.
Question: What must you do after registering the entity extractor file?
MCT USE ONLY. STUDENT USE PROHIBITED
4-40 Customizing the Search Experience
Create custom result sources and use them in custom search result pages.
Review Question(s)
What web part do you configure to show data from a specific result source on a typical search
result page?
Search Results
Content Query
Refinement
Search Textbox
Search Navigation
Entity extractors
Thesaurus
Display Template
Verify the correctness of the statement by placing a mark in the column to the right.
Statement Answer
Verify the correctness of the statement by placing a mark in the column to the right.
Statement Answer
Module 5
Implementing Enterprise Content Management
Contents:
Module Overview 5-1
Module Overview
If you use Microsoft® SharePoint® to store documents in a large or complex organization, you may have
a number of functional and legal requirements to satisfy. For example, in the event of litigation, you must
be able to locate all documents that relate to the case, ensure that they cannot be changed, and export
them to your lawyers. You may want to ensure that documents are kept for a fixed period, or manage a
group of documents as a single entity. Other scenarios involve automating the movement of complete or
expired documents to an archive. SharePoint Server 2013 includes a range of facilities to satisfy these
requirements. In this module, you will see how to work with these document management features in
code.
Objectives
After completing this module, you will be able to:
Programmatically create and manage information management policies and document sets.
Lesson 1
Working with eDiscovery
Electronic Discovery, or eDiscovery, is the process of identifying and delivering electronic information for
use as evidence. This is usually for legal purposes, when the content identified relates to a legal case, but it
may also be for internal investigations within your organization. When a case arises, you must be able to
locate all relevant content quickly, confirm that users cannot tamper with the located content, and export
the content to stakeholders such as attorneys and investigators. All of these requirements can be satisfied
by using eDiscovery Centers in SharePoint Server 2013.
Lesson Objectives
After completing this lesson, you will be able to:
Describe how to locate, hold, and export content for legal and other purposes.
Describe the eDiscovery Center and the objects and facilities a Discovery Center can include.
Choose classes in the eDiscovery APIs for programmatic tasks.
eDiscovery Overview
In many organizations, SharePoint is the primary
content store. When a legal case arises, such as a
disputed contract or a libel, it is likely that one or
more documents that relate to the case are in the
SharePoint content database. If the documents are
not in the content database, they may be in another
location that is indexed by the SharePoint Search
service, such as a file share. In modern organizations
there may be no hard copies of these documents.
When cases arise, you must complete three tasks:
2. Control these located documents so that the current version cannot be tampered with by anyone
involved in the case.
3. Export these documents in a form that can be used by all stakeholders to investigate what happened.
In SharePoint 2013, you can use an eDiscovery Center to complete these tasks.
eDiscovery Infrastructure
An eDiscovery Center is a site collection created by using the eDiscovery Center template. If you expect to
use eDiscovery in your organization, you should plan for and create an eDiscovery Center site collection
so that it is ready for investigators to use. When a case arises, site collection administrators can choose the
users who can create cases. Each eDiscovery case is a sub-site in the eDiscovery site collection, created by
using the eDiscovery Case site template.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 5-3
Once you have created an eDiscovery Case you can search for content that relates to the case. eDiscovery
uses the SharePoint Search Service to locate content. Therefore, the limits of an eDiscovery search match
the limits of the Search Service index. Search administrators must confirm that all the locations where
documents are stored are included as content sources in the Search configuration. These locations can
include:
SharePoint Content. Administrators can configure a single Search service application to index not only
the content in the local SharePoint farm, but also other SharePoint farms on the network.
File Shares. Documents that have not been saved to SharePoint, but are stored in a Server Message
Block (SMB) file share can be indexed.
Business Connectivity Services Connections. Any location to which SharePoint can make a BCS
connection can be indexed.
Exchange Server. SharePoint can index Microsoft Exchange Server items in mailboxes and public
folders. In addition, if you archive Microsoft Lync® 2013 conversations in Exchange Server, these
conversations can be included in the SharePoint Search index, and therefore you can locate them
through eDiscovery.
Install the Exchange Web Services Managed API. This must be done on every SharePoint web front-
end server.
Add authorized users to the Discovery Management role. This role membership enables users to
discover potentially sensitive content in private mailboxes. You must take care to who you assign this
permission because it can enable access to private information.
To download the Exchange Web Services Managed API, follow this link:
For more information about configuring server-to-server trust relationships, follow this link:
eDiscovery Processes
When a case arises, users create a new eDiscovery
Case site within the eDiscovery Center site
collection. From within the new case, users can
perform all the operations required to locate,
control, and export the content that relates to the
case. This includes the following operations:
Exchange Mailboxes
SharePoint sites
File shares
Once you have defined the content sources for a set, you can also define filters to focus the set on
relevant documents. The filters can include:
A date range
An Exchange domain
By configuring sets in this way, you specify the content that the case relates to. For example, if the court
has informed you that the case concerns an email from a particular user on a given date, you can add a
specific mailbox as a content source and filters for the email sender and a narrow date range.
Having defined a content set, you can enable an in-place hold for the set. When a hold is applied, the
current version of the document is preserved as evidence. SharePoint creates a preservation hold library in
each SharePoint site included in the set. If a user modifies a document, a copy is placed in this folder. In
this way, users can continue to work on documents, but the version that is current when the hold is
imposed is protected. This preserved version is the one that is included in exports.
The Microsoft.Office.Server.Discovery
Namespace
This namespace includes that following classes:
SavedSearch. This class represents an eDiscovery query. You can use this class’s properties to set filters
and content sources for the query and to determine the total size of the query.
Export. This class represents an export for the results of an eDiscovery query. You can use the
properties of this class to check the status of the export and access the download link.
HoldSettings. You can use this class to manage holds. For example, you can add content on a
SharePoint site to a hold by using the HoldSettings.AddToHold() method.
In the following topics, you will see code samples that demonstrate how to use these classes.
Creating Cases
In SharePoint, an eDiscovery case is a sub-site
within an eDiscovery Center site collection. To
create a new case, you must therefore create a new
SPWeb object based on the correct site template.
The eDiscovery Case site template has the name
"EDISC#1". Once you have created the SPWeb
object, you can pass it to the Case class constructor
to access eDiscovery methods such as CloseCase()
and CreateExport().
MCT USE ONLY. STUDENT USE PROHIBITED
5-6 Implementing Enterprise Content Management
The following sample code creates a new SharePoint site based on the eDiscovery Case site template. The
code also demonstrates how to set the case to close after one month:
discoveryWeb.Dispose();
}
The following code sample creates a set and a source within the set:
Applying Holds
When the user selects Enable in place hold in an eDiscovery set, holds are created and applied for each
SharePoint site and Exchange mailbox in the discovery set. To perform this task in code, you must
therefore loop through all the sources in the eDiscovery set. If these sources are SharePoint sites or
Exchange mailboxes, you can use the HoldSettings.AddToHold() method to apply the hold.
The following code illustrates how to apply holds for all the SharePoint sources in a set:
}
}
}
}
Creating a Query
In the Microsoft.Office.Server.Discovery
namespace, an eDiscovery query is represented by the SavedSearch class. You can create a SavedSearch
by creating a new SPListItem in the Queries list. You can use the SavedSearch() constructor to access
specialized eDiscovery methods. You must set query properties and save them by calling the Update()
method.
You must bind a SavedSearch to a content source or set. To do this use the Source and SourceGroups
properties on the corresponding list item. Because these are multi-valued lookup values, you must create
a SPFieldLookupValueCollection and add values to it to save sources or sets.
Note: Do not confuse eDiscovery queries, represented by the SavedSearch class, with the
SourceGroup.Query property, which represents a filter on an eDiscovery set.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 5-9
The following code shows how to create a SavedSearch object in an eDiscovery case:
Creating Exports
To create an export in the Exports list you can use the Case.CreateExport() method. This method can
take Boolean values that indicate whether to include all versions of a document, whether to include
encrypted files, and whether to duplicate mailbox content if the same message appears in multiple
mailboxes.
The following code sample shows how to export content from a query programmatically:
}
}
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 5-11
Lesson 2
Working with Content Management
When you have a large quantity of content of different types in your SharePoint content database,
administration can become onerous. For example, suppose your organization has a new product. Authors
create 30 documents about the product, including posters, instruction manuals, sales materials, and more.
Six months after the product is released you want to archive all these documents. Five years after release,
you want to be sure that all of these documents are deleted. Meanwhile, many other products are
created, each of which has a similar body of documentation. By using a document set, you can reduce this
administrative workload because you take actions on all the product's documents in a single step. By
using information management policies, you can automate the deletion of the documents. In this lesson,
you will see how to code document sets and information management policies.
Lesson Objectives
After completing this lesson, you will be able to:
Describe how document sets are used to group documents for management purposes.
Policy Features
Four policy features are included in SharePoint
Server 2013. Administrators can define one or more
of these features in each information management
policy:
Retention. The retention policy feature enables you to define stages in the lifecycle of each document.
At the end of each stage, you can define an action that will be taken on each document. For example,
your policy could delete all earlier versions of a document after one year, and then declare the
document as a record after two years.
Auditing. The auditing policy feature enables you to specify which actions on a document are
recorded in the SharePoint audit logs. Using these logs, you can verify that sensitive information is
accessed only by authorized users. In the event of a security breach, the audit logs may help you to
MCT USE ONLY. STUDENT USE PROHIBITED
5-12 Implementing Enterprise Content Management
determine the user who accessed the sensitive data. You can audit operations such as changes, reads,
check-ins, check-outs, permission changes and deletions.
Labeling. A label is a searchable text area that SharePoint can generate by concatenating values from
the other fields of an item. For example, a label for a contact item may include the contact name and
address fields. Labels are useful when documents are printed.
Barcode. The barcode policy feature can generate a barcode for a document that is compliant with
the common Code 39 standard. By inserting the barcode image in the document you can enable bar
code readers to identify the document.
Note: Take care not to confuse information management policies, which govern content,
with site policies, which govern sites. Site policies help site collection administrators prevent the
proliferation of sites. They cannot be used to govern individual documents or items.
Configure the Secure Store Service Application. Auditing requires the Secure Store Service Application
to be running in the SharePoint farm. Administrators can create this service application in Central
Administration or PowerShell.
Start the Secure Store Service. After configuring a Secure Store service application, administrators must
start the Secure Store Service on at least one SharePoint server in the farm.
Once audit logging has been configured, you can view the audit logs at the site collection level:
4. Click the report of interest. Available reports include Content viewing, Content modifications, and
Deletions.
Components of Policies
A policy consists of one or more items. Each item
refers to one of the four policy features: retention,
auditing, barcodes and labeling. Some features
make use of policy resources to execute actions
such as retention stages.
Policy XML
An information management policy is stored as
XML file with a specific schema in the SharePoint
content store. You can export these XML files and
then import them into other site collections in the
same SharePoint farm. You can also import the XML
files into other SharePoint farms.
Most elements in the policy XML file have the p: prefix. For example, the top-level element is always a
<p:Policy> element.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 5-13
Each policy is made up of one to four policy items. A policy item stores the settings for one of the four
policy features: retention, auditing, barcodes, and labeling. You can choose whether to include policy
items for each of the policy features in your policy.
Some policy features make use of resources to execute their actions. For example, the retention feature
can call resources such as DeletePreviousVersions and MoveToRecycleBin when each retention stage
ends.
Demonstration Steps
1. Access the Content Type Policy Templates list for the http://dev.contoso.com site collection.
2. Create a new information management policy. Use the following information:
3. Enable retention and add a retention stage that deletes all previous versions of documents one year
after creation.
6. Export the policy to Downloads folder, and then open the Export Policy.xml file in Internet
Explorer®.
Programming Policy
Objects that enable developers to work with
information management policy are found in the
Microsoft.Office.RecordsManagement.Informati
onPolicy namespace. You can import and export
policy documents as well as associate a policy with
a content type.
Importing a Policy
To import a policy XML file into a SharePoint site collection, you must first access the policy catalog for
the site collection. To perform the import, pass the XML file to the static PolicyCollection.Add() method,
along with the site collection.
The easiest way to create a string representation of the XML file is to use XMLDocument class along with
a StringWriter object and an XmlTextWriter object. This requires references to the System.IO and
System.Xml namespaces.
This code example illustrates how to import a policy from a correctly formatted XML file:
Importing a Policy
using (SPSite site = new SPSite("http://intranet.contoso.com"))
{
//Access the policy catalog
PolicyCatalog policyCatalog = new PolicyCatalog(site);
If you have imported the policy from an XML file, you can find a GUID that uniquely identifies the policy
in the top-level <p:Policy> element. Use this GUID to reliably obtain the correct policy from the policy
catalog.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 5-15
The following code illustrates how to associate a policy in the catalog with a content type:
You should create a different content type for each type of document set you expect users to create.
Ensure these content types inherit from the default document set content type. For each of these
document set content types, you can specify:
Allowed Content Types. This list of content types specifies the kinds of documents that users can add
to the document set.
Default Content. This is a list of document files that are created automatically whenever a user creates
a new document set.
Shared Columns. This is a list of site columns that all the documents in the document set possess. The
values of these columns are automatically synchronized between all the documents in the document
set.
Welcome Page: This is the SharePoint page that is displayed whenever a user opens a document set.
You can customize the text and layout of this page and display different shared columns.
MCT USE ONLY. STUDENT USE PROHIBITED
5-16 Implementing Enterprise Content Management
Microsoft.Office.DocumentManagement.Docum
entSets. Use this .NET API for server-side code,
such as code in a SharePoint web part.
Microsoft.SharePoint.Client.DocumentSet. Use
this .NET API for client-side code, such as code
in a provider-hosted SharePoint app.
Parent Folder. This is the folder in which the document set will be stored.
Content Type ID. This is a number that uniquely identifies the content type. The content type ID
includes all the IDs of parent content types.
The following code illustrates how to create a document set by using the client-side .NET managed API.
This code runs within a console application:
context.ExecuteQuery();
}
}
}
MCT USE ONLY. STUDENT USE PROHIBITED
5-18 Implementing Enterprise Content Management
Lesson 3
Automating Records Management
When working with large quantities of content, SharePoint administrators require an automatic tool that
can move documents, assets, and other items to the most appropriate folder based on document
properties. Users should be encouraged to be productive by producing new content, but may be
discouraged if they must read complex rules that determine the SharePoint library or folder where the
content must be stored. By using Content Organizer, you can automate these rules so that SharePoint
moves documents into the most appropriate location. This makes it easier to locate documents at any
later time. Document IDs also help users to locate content, because they do not change throughout the
lifecycle of the document, whether they are moved by users, the Content Organizer, information
management policy, or some other component.
Lesson Objectives
After this lesson, you will be able to:
Describe how the SharePoint Content Organizer can ensure consistent, automatic document
management.
Describe how document IDs can help users to locate content that has moved.
Note: Before you can use the Content Organizer, a site administrator must enable the
Content Organizer site feature.
If a user places a document in any other document library, the user bypasses all Content Organizer rules.
You can permit users to do this if you are confident that they know where to place documents. In this
configuration, users who do not know the correct location for a document can use the Drop Off Library.
However, you can also configure the Content Organizer to redirect users to the Drop Off Library
whenever they add a document. In this configuration, Content Organizer rules are always enforced.
Redirect users to the Drop Off Library. When this setting is enabled, users cannot bypass Content
Organizer rules and must add all new documents to the Drop Off Library.
Sending to another site. When this setting is enabled, Content Organizer rules can have destinations in
other sites or site collections. These sites should also have the Content Organizer enabled.
Folder Partitioning. When this setting is enabled, the Content Organizer will create a subfolder
whenever the number of items in a destination library exceeds a number that you specify.
Duplicate Submissions. With this setting you can specify what happens when a document with a
duplicate name already exists in the destination library. Content Organizer will either create a new
version of the document, if versioning is enabled, or add random characters to the end of the file
name.
Preserving Context. When this setting is enabled, audit entries and properties in the Drop Off Library
are preserved when the document is moved to the destination.
Rule Managers. You can specify user accounts as rule managers who can create Content Organizer
rules in the site. Rule Managers must have the Manage Web Site permissions level.
Submission Points. With this setting, you can configure web services that will accept uploaded
documents and place them in the Drop Off Library, where rules are applied.
Rule Status and Priority. You can use this setting to enable and disable a rule. You can also specify a
priority of 1 to 9. If a document matches two rules, the one with the lower priority number is applied.
1 is the highest priority and 9 is the lowest.
Submission's Content Type. You can use this setting to match all documents of a particular content
type.
Conditions. You can create conditions that examine and match individual properties of the document.
The properties that you can match depend on the content type you have selected. You can add
multiple conditions, all of which have to be matched for the rule to apply.
Target Location. For each rule, you can use this setting to determine the location to which matching
documents will be moved.
MCT USE ONLY. STUDENT USE PROHIBITED
5-20 Implementing Enterprise Content Management
The following code illustrates how to create a new Content Organizer rule by using the server-side API:
Note: Content organizer rules apply at the web level. You can only export content
organizer rules programmatically.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 5-21
The document ID service generates IDs only for documents, and not for items or media assets. To receive
a document ID, a document must be based on the Document content type or a content type that inherits
from Document.
Assign Document IDs. This setting enables or disables the generation of document IDs for new
documents. If you disable this setting, SharePoint will not remove the IDs or static URLs for existing
documents.
Begin IDs with the following characters. You can use this setting to apply a prefix to all document IDs.
For example, you could specify the name of the company or division.
Document ID Lookup Search Scope. When users search for a document ID or click a static URL,
SharePoint must locate the document. To do this it can query the Search Service. This setting specifies
which search scope will be used for this query.
The Search Service can be used by SharePoint to locate documents from a document ID. Search
administrators should consider these queries when they configure the Search Service. For example,
administrators should consider creating a dedicated search scope that includes all destinations within
SharePoint where documents are stored.
Document ID Providers
The Document ID Service uses document ID providers for two purposes:
Therefore, there are two methods by which a document can be located from its ID:
Using the Search Service. The Search Service is an excellent and functional method of locating
documents. However, if the document is new, the ID may not be in the index and may not be found.
Using the Document ID Provider. The provider can include custom code for document location.
GenerateDocumentId. This method creates the document ID for the list item that is passed. You can
access the properties of the list item, add random numbers, add a GUID or lookup values from
external systems, and use these values to create and return the ID.
GetDocumentUrlsById. This method performs a custom search routine that does not use the
SharePoint Search service.
GetSampleDocumentIdText. This method returns a string that illustrates the format of the document
ID.
DoCustomSearchBeforeDefaultSearch. If this property returns true, the GetDocumentUrlsByID
method is called to find documents before the Search Service. If this property returns false, the
opposite order is used.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 5-23
//Insert the random number into the format string and return the resulting ID
return string.Format(this.docIdFormatString, randomNumber);
}
if (!itemUrls.Any())
{
return null;
}
else
{
return itemUrls.ToArray();
}
//Indicate that the custom search method will be called before the Search Service
public override bool DoCustomSearchBeforeDefaultSearch
{
get { return true; }
}
The following code illustrates how to build a feature receiver that installs and uninstalls a custom
document provider:
To assist the team, you will implement various document management features on the SharePoint
intranet portal. First, you will implement a document ID provider to generate a unique document ID for
every document. The Sales team can record the document ID on the sales ledger, and use the ID to
retrieve the document quickly from SharePoint even if it has been moved. Next, you will configure and
apply an auditing policy that ensures document reading and writing operations are recorded.
Objectives
After completing this lab, you will be able to:
Create a custom document ID provider.
Create and apply a custom information management policy in a SharePoint feature receiver.
Lab Setup
Estimated Time: 75 minutes
Password: Pa$$w0rd
A warm-up script named WarmUp.ps1 runs automatically when you start the virtual machine. This script
helps to improve the performance of the virtual machine by downloading the home page of the root site
in each site collection on the server. Occasionally this script displays timeout errors; you can ignore these
errors. You should ensure this script has finished running before you start the lab.
o Language: Visual C#
o Name: ContosoDocumentIDProvider
o Location: E:\Labfiles\Starter
2. Use the http://dev.contoso.com site for debugging and configure the project as a farm solution.
o Microsoft.Office.DocumentManagement
o Microsoft.Office.Policy
5. Add using statements for the following namespaces to the DocumentIDProvider.cs code file:
o System.Data
o Microsoft.SharePoint
o Microsoft.Office.DocumentManagement
7. Ensure that the DocumentIDProvider class inherits from the DocumentIdProvider class in the
Microsoft.Office.DocumentManagement namespace.
o Type: string
o Name: docIdFormatString
o Value: "Contoso{0}"
5. Use the random object to generate a random integer between 100,000 and 999,999 and store the
integer in a variable named randomNumber.
6. Use the string.Format() function to insert the randomNumber value into the docIdFormatString
and return the resulting string.
3. Create an if statement that checks that the site parameter is not null and that the documentId
parameter is not null or an empty string.
6. If the itemUrls variable has zero strings, return null. Otherwise, return the itemUrls list converted into
an array.
2. Use the string.Format() function to insert the string "123456" into the docIdFormatString and
return the resulting string.
3. Override the DoCustomSearchBeforeDefaultSearch property.
Results: A Microsoft Visual Studio® project with a custom document ID provider class coded and
completed.
3. Add an event receiver to the ContosoDocIDFeature and remove all commented code from the event
receiver.
o Password: Pa$$w0rd
3. Examine the Document ID Settings for the site collection. Notice that you can edit the prefix for
document IDs.
5. Examine the Document ID settings for the site collection. Notice that a custom document ID
provider has been configured and that you cannot edit the prefix for document IDs.
6. Add the following document to the Documents library:
7. Add the Document ID column to the current view. Notice that the provider has generated a
document ID for the Test Document that begins with "Contoso".
o Password: Pa$$w0rd
o Administrative Description: This policy ensures auditing for reading and editing items
4. Export the Contoso Audit Policy to a new folder named Polices in the root of the C: drive.
5. Delete the Contoso Audit Policy from the http://dev.contoso.com site collection.
MCT USE ONLY. STUDENT USE PROHIBITED
5-30 Implementing Enterprise Content Management
3. Add an event receiver to the ContosoAuditingFeature and remove all commented code from the
event receiver.
o System.Xml
o Microsoft.Office.RecordsManagement.InformationPolicy
o System.IO
6. Load the exported Contoso Audit Policy.xml file into the policyXmlDoc object.
7. Create a new StringWriter object named stringWriter.
8. Create a new XmlTextWriter object named xmlTextWriter by passing the stringWriter object to
the constructor.
10. Convert the stringWriter object to a string and store it in a new string variable named policyXml.
11. To import the policy, call the static PolicyCollection.Add() method and pass site and policyXml as
parameters.
12. In the C:\Policies\Contoso Audit Policy.xml file, copy the id value from the first <p:Policy> element to
the clipboard.
13. Use the id value you just copied to retrieve the new policy from the policyCatalog.PolicyList
collection and store it in a new Policy object named newPolicy.
14. Get the Document content type from the root web of the site collection and store it in a new
SPContentType object named docContentType.
15. To add the policy to the Document content type, call the static Policy.CreatePolicy() method and
pass docContentType and newPolicy as parameters.
3. Get the Document content type from the root web of the site collection and store it in a new
SPContentType object named docContentType.
4. To remove the policy from the content type, pass docContentType to the static
Policy.DeletePolicy() method.
5. In the C:\Policies\Contoso Audit Policy.xml file, copy the id value from the first <p:Policy> element to
the clipboard.
6. To delete the policy, call the static PolicyCollection.Delete() method and pass the site collection and
the id value you just copied.
7. Save your changes.
2. Open the list of Content Type Policy Templates for the site collection. Notice that the Contoso
Audit Policy has been recreated by the feature receiver.
3. Access the Information Management Policy Settings for the Documents library.
4. Check that the information management policy for the Document content type is Content Audit
Policy.
5. Stop debugging and close Visual Studio.
Results: A SharePoint solution that imports and applies an information management policy when it is
activated.
Review Question(s)
Question: You have created an eDiscovery Center and a new eDiscovery Case. However,
when you create a set and try to access results within the set, you receive an error. You also
cannot create queries on the set. How can you solve this problem?
Verify the correctness of the statement by placing a mark in the column to the right.
Statement Answer
Module 6
Developing a Publishing Site for Web Content
Contents:
Module Overview 6-1
Module Overview
Microsoft® SharePoint® Server 2013 has introduced new capabilities for building rich web content
publishing sites. While preserving many of the successful foundational elements of publishing sites,
including page layouts and publishing pages, key improvements have been made in navigation, search
engine optimization, surfacing search-driven content, and support for mobile devices.
In this module, you will learn how to develop web content solutions for publishing sites.
Objectives
After completing this module, you will be able to:
Describe how to utilize the Publishing API to access publishing settings and content.
Describe how to use and customize page content controls in publishing sites.
MCT USE ONLY. STUDENT USE PROHIBITED
6-2 Developing a Publishing Site for Web Content
Lesson 1
Programming with the Web Content Publishing API
The SharePoint Publishing API provides a collection of classes for programmatically accessing the
enhanced capabilities of publishing-enabled sites. In this lesson, you will learn how to work with the
publishing API to deploy and customize publishing settings and content.
Lesson Objectives
After completing this lesson, you will be able to:
Describe how to access the Publishing API by utilizing the server-side object model.
Some of the additional capabilities available on sites with publishing feature enabled include:
Page Layouts and Publishing Pages. In addition to the standard page types such as Wiki pages and
Web Part pages, a new page rendering model is enabled that supports the use of Page Layouts and
Publishing Pages.
Variations and Device-Specific Targeting. Publishing sites can support multilingual variations in site
content, and can redirect users to the appropriate language content resources based on browser
language settings. Variations and Device Channels can also be used to provide alternative
presentation of content based on mobile device use, or geographic elements such as country or
region.
Portal and Managed Navigation. Publishing sites utilize unique navigation providers for handling the
special characteristics of publishing sites. Managed Navigation, a new feature introduced in
SharePoint 2013, supports user-friendly URL’s,
Image Renditions. Optimizing images for publishing sites is an important consideration for
performance. Image Renditions is a new feature in SharePoint 2013 that automatically renders images
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint 2013 Advanced Solutions 06-3
to meet preconfigured resolutions, and enables content authors to select appropriate renditions when
embedding media in content.
Search Engine Optimization. Publishing sites now support auto-generation of site maps, robots
exclusion protocol, canonical URL’s, and SEO meta properties for pages and navigation.
Cross-Site Publishing. This new feature introduced in SharePoint 2013 utilizes search technology to
allow content in one or more authoring sites to be surfaced in a publishing site. By defining a list or
library as a catalog, cross-site connections can be established that enable a publishing site using the
Content Search Web Parts to display content authored and located in a remote site collection.
SharePoint 2013 has introduced some significant changes and a myriad of new choices for developers
building publishing solutions. In particular, architects, designers, and developers must consider the
following:
Server-Side vs. Client-Side Programming. SharePoint 2013 has seen significant enhancements in the
capabilities of the Client Side Object Model (CSOM) and the JavaScript Library (JSOM), providing
enhanced access to publishing capabilities that previously could only be accomplished by using
server-side code.
Solutions vs. Apps. SharePoint 2013 has introduced a new programming model called Apps for
SharePoint. The Solutions and Features Framework is still fully supported, but Microsoft is now
recommending the use of the new app model for many kinds of customizations.
The remainder of this lesson will focus on Page Layouts and Publishing Pages, including provisioning,
configuration of publishing settings through code, and how to work with and customize publishing page
components for use in publishing sites.
Accessing the publishing features of a site collection or site commonly requires provisioning an instance
of one of these objects.
In the following code example demonstrates how to instantiate a PublishingSite and PublishingWeb
object for accessing publishing settings on a site collection:
The following code example demonstrates how to provision a Page Layout by using a Module element:
As demonstrated above, two new attributes are available on the File element of a Module:
ReplaceContent. This attribute now allows the contents of an existing file to be replaced with the
contents of the new file.
Level. This attribute now allows specifying the version setting when provisioning the file as Draft or
Published.
Some new properties are also available for Page Layouts that should be included:
PublishingHidden. Indicates whether the page layout is displayed to users when creating new pages
through the SharePoint UI.
HtmlDesignAssociated. Indicates whether the Page Layout is associated with an HTML layout file.
When creating Page Layouts through the Design Manager, this association is set to TRUE by default.
To separate a Page Layout or Master Page association with an HTML template, set this value to FALSE.
The following code example demonstrates a module element to provision a publishing page:
PublishingPageLayout. This property requires specifying the page layout to associate with the
publishing page in the format {server-relative URL, title}.
ContentTypeId. This property requires the Content Type ID of the content type to be associated with
the publishing page.
In addition, depending on the content type, you can specify additional properties for any of the fields
included in the content type.
Note: SharePoint App Webs do not support deploying Module elements to the Host Web,
and do not support Publishing features on the App Web. When attempting to deploy a
publishing page to the Host Web from a SharePoint App, the publishing page must be
provisioned by using code.
The following code example demonstrates how to provision a publishing page by using the Publishing
API:
Provisioning publishing pages requires an instance of a PublishingWeb object, which provides a number
of overloads for the AddPublishingPage method.
The following code example demonstrates how to enable scheduling on the Pages library of a publishing
site:
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint 2013 Advanced Solutions 06-7
If (!pagesLib.EnableModeration)
{
pagesLib.EnableMinorVersions = true;
pagesLib.EnableModeration = true;
pagesLib.Update();
}
pubWeb.EnableScheduling(pagesLib);
The scheduling capability is supported by a timer job that checks the PublishingStartDate and
PublishEndDate columns respectively, and automatically updates the content approval status on an item.
The PublishingPage class provides properties to update the start and end dates, and to trigger scheduling
on a page item.
The following code example demonstrates how to schedule publishing on a page programmatically:
It is important to update the underlying list item after updating the StartDate and EndDate properties on
a PublishingPage item. After updating the item, call the Schedule method.
Microsoft.SharePoint.Publishing
Microsoft.SharePoint.Publishing.Navigation
The following code example demonstrates how to import the correct namespaces for working with
publishing navigation settings:
Navigation Providers
Publishing sites have two built-in navigation objects:
Each navigation object can be configured separately, enabling publishing sites to combine navigation
models according to requirements. In addition to the PortalProvider carried forward from previous
versions of SharePoint (now referred to as Structured Navigation), SharePoint 2013 includes a new type of
navigation provider called Managed Navigation that utilizes the Managed Metadata Service. Managed
Navigation works in conjunction with other new web content management features, including Friendly
URLs and Cross-Site Publishing with Catalogs. Managed Navigation utilizes the TaxonomyProvider.
The following code example demonstrates how to set the navigation provider for Global and Current
Navigation:
Include Pages. This setting indicates whether new pages should be added automatically to navigation.
Dynamic Child Limit. This setting limits the number of child navigation items displayed.
The PortalNavigation object also provides methods for setting the sort order of navigation items, and for
adding additional manual items to the collection of navigation items.
The following code example demonstrates setting navigation options for structured navigation:
// navigation sorting
portalNav.OrderingMethod = OrderingMethod.Automatic;
portalNav.AutomaticSortingMethod = AutomaticSortingMethod.Title;
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint 2013 Advanced Solutions 06-9
pubWeb.Update();
web.Update();
The following code example demonstrates updating navigation settings for managed navigation:
webNav.Update();
web.Update();
Lesson 2
Developing Page Components for Web Content
Publishing
SharePoint provides developers with a combination of techniques to customize the presentation and
behavior of content, without requiring extensive editing of master pages or page layouts. In this lesson,
you will learn how to create and deploy page components for web content publishing sites, including
field controls, web parts, delegate controls, and custom user actions. This lesson will also introduce the
new SharePoint 2013 page components, including App Parts and the new JSLink property.
Lesson Objectives
After completing this lesson, you will be able to:
Dynamically inject JavaScript into publishing pages with the ScriptLink control.
Customize the display and behavior of page fields with custom field controls.
Customize the display and behavior of fields with the JSLink property and client-side templates.
Page layouts. A page layout is effectively a template for a particular type of page. A page layout is an
ASPX page that contains HTML markup and content controls such as page field controls, or web
parts. When a page is rendered, markup and controls contained within content placeholders are
merged with the master page.
Page content. Content for publishing pages is stored as data in a SharePoint list, where each row of
list data represents a publishing page. When a page is rendered, the content from each field in the list
item is displayed by the corresponding field control in the page layout.
Various SharePoint and ASP.NET controls, such as the SharePoint Welcome menu control and the
ASP.NET ScriptManager control.
Several ASP.NET ContentPlaceHolder controls, into which page layouts or web part pages can insert
content.
Each page layout is based on a content type. The content type defines the fields that must be included on
the page. For example, suppose you want to create a page layout that includes a title, two columns of
text, and an image. The corresponding content type might include fields named Title, Column1Text,
Column2Text, and PageImage. The page layout would then include field controls to render the values of
each of these four fields.
The following code example shows how field controls are placed within content controls in a page layout:
When a user creates a new page based on a particular page layout, they are simply creating a new list
item with the relevant content type. The user provides values for each of the fields defined by the content
type. The page layout and the master page together determine how the content provided by the user is
rendered.
Delegate Controls. A delegate control is a placeholder for content controls that are loaded
dynamically at runtime. Delegate controls allow content controls to be deployed as a feature and
loaded into a page without requiring changes to the master page or page layout. Delegate controls
are only supported in full-trust solutions.
MCT USE ONLY. STUDENT USE PROHIBITED
6-12 Developing a Publishing Site for Web Content
Server Controls and Web Parts. Server Controls and Web Parts provide a completely custom and
dynamic rendering of content from virtually any data source, and are the ‘Swiss Army knife’ of
content controls. Server controls must be added directly to a master page or page layout. Web Parts
can be added dynamically at runtime, when contained within a Web Part Zone. Web Parts are
typically full-trust solutions; however, SharePoint 2010 added the ability to write Web Parts as part of
a Sandbox solution. Sandbox solutions have now been deprecated in SharePoint 2013 in favor of the
new App model. Custom server controls are not supported in the app model.
Custom Actions. These allow applications to register custom commands for display at select locations,
such as the ribbon menu, the list item edit control block, and site actions. The ScriptLink control
allows JavaScript links or script blocks to be inserted dynamically into a master page. Custom actions
are supported from full-trust and sandbox solutions, and can be created either declaratively, or
programmatically by using the client-side object model from SharePoint Apps.
App Parts. App Parts are a new kind of control introduced in SharePoint 2013 as part of the app
model. The app model does not support the deployment of Web Parts to the Host web as part of an
app. An App Part utilizes an IFrame to display a remote page hosted by a SharePoint app. The user
experience of adding an App Part to a page is similar to a Web Part, and is available from the ribbon
menu when editing a page.
JSLink / Client Templates. These are new to SharePoint 2013, and are very similar to Field Rendering
Controls; however, they are implemented in JavaScript and run client-side. A new JSLink property is
provided to link to JavaScript files that implement rendering script on specific objects including Fields,
Lists, Views, and some Web Parts.
It is not uncommon to see advanced solutions utilize many of these content controls together to satisfy
requirements. With a growing emphasis on client-side programming, the new SharePoint 2013 App
model, and Microsoft’s strong push towards moving customers to Office 365 and SharePoint Online, it is
important when considering customizations for developers to consider all alternatives when selecting the
best solution.
Rendering Template. A rendering template is typically a user control responsible for rendering the
display or edit views of a field.
Field Control Class. The field control class is responsible for reading and writing the field value
between the page field and the associated rendering template.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint 2013 Advanced Solutions 06-13
Rendering Templates
Rendering templates are user controls that contain a RenderingTemplate tag. Rendering templates are
associated with a Field Control class based on the value of the ID property. Inside the <Template>
element can be a mix of HTML <div> or <table> tags for layout purposes, and any ASP.NET controls
necessary to present the display or editing experience for the user. The user control is not responsible for
implementing the logic to read and write the values of the controls it hosts; this is done by the Field
Control class.
Rendering Template
<SharePoint:RenderingTemplate ID="ContosoProductCodeRenderingTemplate" runat="server">
<Template>
<asp:TextBox ID="ProductCodeTextBox" runat="server" />
</Template>
</SharePoint:RenderingTemplate>
User controls that contain a RenderTemplate tag must be deployed to the 15\Template\ControlTemplates
folder, and must exist in the root of this folder in order to be detected by SharePoint.
Best Practice: It is generally recommended to deploy custom files to the SharePoint root
folder path under a solution-specific sub-folder in order to separate out-of-box files from custom
solutions. In the case of rendering templates, SharePoint will only inspect the root folder, and will
not search child folders. User control files containing rendering templates must be deployed to
the root folder. To reduce the risk of file naming conflicts, you should prefix your user control file
names with a solution-specific identifier.
DefaultTemplateName. The default template name returns the ID of the rendering template that will
be loaded to support field control.
CreateChildControls. This is a standard method for any server control; however, you don’t create
controls. In field control classes, you reference the TemplateContainer property provided by the base
class to call the FindControl method to get a reference to any controls hosted in the rendering
template.
Value. This implementation is used to get and set the field value, provided by the base class as
ItemFieldValue, and get and set the appropriate control values hosted in the rendering template.
The following example demonstrates the basic structure of a field control class:
The core logic of a field control class is initiated by overriding the Value property. The get method is
called just before SharePoint needs to update the page field on the associated content item. The set
method is called when a user opens a page in edit model in order to initialize the controls in the
rendering template that will be shown to the user.
Note: SharePoint field types are serialized and stored as a raw text string. For simple field
type objects such as Text, the field value can be read and set directly. For more complex types,
the raw string value may be a concatenation of sub-strings. For example, a URL field type is a
combination of the URL display text, and the URI. Field types that require special encoding
typically provide a special field value class for reading and writing the raw field value (for
example, SPFieldUrlValue). If your field control class supports binding to many field types, it is
your responsibility as a developer to implement defensive coding techniques to determine the
system type of the ItemFieldValue in order to read and write the field value correctly.
Deploying your completed solution requires placing the assembly containing the custom field control
class to the Global Assembly Cache (GAC) on all SharePoint front-end servers, and registering the control
as a SafeControl in the web.config. This is best accomplished by packaging the assembly and the
rendering templates in a SharePoint solution file so they can be installed together into the SharePoint
farm. The solution package will also ensure that the SafeControl entry is added properly.
Note: Due to the restriction that field controls deploy to the SharePoint file system, they
must be deployed as a Farm-trust solution and are not supported in sandbox solutions or from
SharePoint apps.
The following example demonstrates the tag for adding a Web Part Manager control:
In order to host a web part, a page must have an instance of this control, so it is most commonly found in
the site master page. All out-of-box SharePoint master pages include this control. If you are working with
a custom master page, confirm that this control is included in order to support web parts in your solution.
The following is an example of a Web Part zone that can be added to a Page Layout to host Web Parts:
Web parts are not required to be contained in a WebPartZone, and can be embedded directly within a
content placeholder just like any other ASP.NET server-side control. The disadvantage of this approach is
that web parts cannot be edited through the SharePoint user interface, participate in web part
connections, or be accessed programmatically through code.
MCT USE ONLY. STUDENT USE PROHIBITED
6-16 Developing a Publishing Site for Web Content
Best Practice: It is recommended that when embedding a web part in page layouts or
pages, that the part always be contained in a web part zone. The exception to this rule is when
adding web parts to a master page that does not support web part zones.
Additional Reading: For more information about Web Part Zones, read the WebPartZone
Class documentation on MSDN at http://go.microsoft.com/fwlink/?LinkId=321110.
Embedded Control Tag. Add the Web Part directly to a page or page layout by using an HTML tag.
Additional Reading: For a description of the standard properties available on all web
parts, read about the WebPart Class on MSDN at http://go.microsoft.com/fwlink/?LinkId=321111.
The following example demonstrates adding a Register tag for a control assembly. This tag should be
placed at the top of the file, and is required to add any control contained within the specified namespace
and assembly to the page layout or site page:
The following demonstrates how to insert a Script Editor web part within a web part zone of a page layout
or site page:
AllUsersWebPart Element
The AllUsersWebPart element can be used within a Module to provision an instance of a web part on a
page layout or page.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint 2013 Advanced Solutions 06-17
The following example demonstrates how to add the AllUsersWebPart element when provisioning a Page
Layout:
AllUsersWebPart Element
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<Module Name="PageLayouts" Url="_catalogs/masterpage">
<File Path="PageLayouts\ProductArticle.aspx" Url="ProductArticle.aspx"
Type="GhostableInLibrary">
<Property Name="Title" Value="My Custom Article Page" />
<Property Name="MasterPageDescription" Value="This is my custom Article page for
SharePoint 2010" />
<Property Name="ContentType"
Value="$Resources:cmscore,contenttype_pagelayout_name;" />
<Property Name="PublishingAssociatedContentType"
Value=";#$Resources:cmscore,contenttype_articlepage_name;;
#0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF3900242457EFB8B2
4247815D688C526CD44D;#" />
<AllUsersWebPart WebPartZoneID="Right" WebPartOrder="1">
<![CDATA[
<webParts>
<webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
<metaData>
<type
name="Microsoft.SharePoint.WebPartPages.ScriptEditorWebPart, Microsoft.SharePoint,
Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
<importErrorMessage>Could not import</importErrorMessage>
</metaData>
<data>
<properties>
<property name='Title’>Script Editor</property>
<property name="ChromeType" type="chrometype">None</property>
</properties>
</data>
</webPart>
</webParts>
]]>
</File>
</Module>
</Elements>
Programmatically
When deploying publishing site customizations such as a new Web Part control, it is common to want to
provision instances of the web part on existing pages. Using the WebPartManager control allows adding
web parts programmatically to any WebPartZone.
The following example demonstrates how to add a web part to a page programmatically by using the
page’s web part manager control:
page.CheckIn(String.Empty);
}
}
The following code example demonstrates how to include an App Part in a page layout or site page:
The Content element is responsible for identifying the source page to display inside the IFrame hosted by
the control. Custom properties can also be defined for the web part, and are passed to the remote page
by adding additional parameter tokens in the URL configured for the Content element’s Src attribute.
Since all App Parts are provisioned by using a standard out-of-box ClientWebPart, and configured
through properties on the web part, they can be provisioned in exactly the same way: by embedding the
web part tag directly into the page layout or site page, or by using the AllUsersWebPart element as
demonstrated in the topic on Working with Web Parts.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint 2013 Advanced Solutions 06-19
AllowMultiple. This value determines whether the delegate control will select and load a single control
or support loading multiple controls. Selection of controls and rendering is determined by the
sequence number, with the lowest number receiving the highest priority. The default is false.
Scope. Indicates the scope of the delegate control, which can be Farm, WebApplication, Site, or Web.
By default, the scope applies to all. When a developer registers a control for a delegate control, the
associated scope of the feature will correlate to the scope of the delegate control.
The out-of-box SharePoint master pages make liberal use of delegate controls as a way to customize
many page elements through the use of features. The following is a list of some of the standard delegate
controls available in SharePoint 2013. The delegate controls highlighted in bold are new to SharePoint
2013.
AdditionalPageHead
GlobalSiteLink0
GlobalSiteLink1
GlobalSiteLink2
PublishingConsole
PageHeader
TopNavigationDataSource
TreeViewAndDataSource
PageFooter
QuickLaunchDataSource
SmallSearchInputBox
GlobalNavigation
MCT USE ONLY. STUDENT USE PROHIBITED
6-20 Developing a Publishing Site for Web Content
SuiteBarBrandingDelegate
SuiteLinksDelegate
PromotedActions
Developers can use the out-of-box delegate controls, or can implement custom delegate controls when
deploying custom master pages or page layouts. Be aware that implementing a custom delegate control
will only customize pages based on the customized master page or page layout.
Registering Controls
Controls are registered using a CAML element that is deployed as part of a Feature, and support
registering either a user control or a server control. When registering a user control, the control must be
deployed to the SharePoint server file system under the \15\Template\Layouts\ControlsTemplates folder.
User controls can only be loaded from a file system, and the ControlTemplates folder is already included
in the SafeControls section of the SharePoint web.config.
Id. The Id value is used to register the control with any delegate control with the same name.
Sequence. The sequence number determines the loading priority for the control. A lower number
means the control will load before another control with a higher number. If two controls have the
same sequence number, the choice of ordering is arbitrary.
ControlSrc. The value of this property contains the location of the user control to load.
If registering a server control, then you must specify the assembly and class that implement the control.
The assembly must be deployed to the GAC, and registered as a SafeControl in the SharePoint web.config
for all content web applications.
Delegate controls are not supported by sandbox solutions, and are not supported in the new SharePoint
App model.
Note: If you examine built-in SharePoint 2013 master pages, you will notice that delegate
controls and various other page elements are wrapped by AjaxDelta controls. These AjaxDelta
controls are part of the Minimal Download Strategy (MDS) feature in SharePoint 2013. Essentially,
MDS ensures that only content that has changed, rather than all content within an element, is
downloaded through Ajax.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint 2013 Advanced Solutions 06-21
Use a Delegate Control. As we saw previously, delegate controls can dynamically load user controls or
server controls. These controls can register a JavaScript reference using the
Page.ClientScript.RegisterClientScriptBlock method. This approach requires a farm-trust solution in
order to deploy the control. This approach is not supported in SharePoint Online.
Use the ScriptLink Control with a Custom Action. Custom actions provide an extensibility point for
adding custom commands to the SharePoint UI, such as the ribbon menu or a list ECB menu. It also
supports a location called ScriptLink that is capable of inserting a JavaScript link or block into the
header area of a SharePoint master page. This approach is supported as full-trust, a sandbox solution,
or the new SharePoint 2013 App model. This approach is supported in SharePoint Online as either a
sandbox solution (using CAML) or programmatically from a SharePoint App.
When comparing the three options noted above, using the ScriptLink control with a custom action is the
most flexible approach, and is really the only approach that is supported across all of the SharePoint
development models.
The following example demonstrates how to create a custom action targeting the ScriptLink location as a
CAML element that can be deployed in a SharePoint feature:
Location. The location property indicates the target control for inserting a custom action. The value of
this property must be specified as ScriptLink.
Sequence. The sequence number indicates the order in which targeted actions will be loaded into the
control. For the ScriptLink control, this indicates the order in which scripts will be inserted into the
page. A lower number indicates a higher priority.
MCT USE ONLY. STUDENT USE PROHIBITED
6-22 Developing a Publishing Site for Web Content
ScriptSrc. Contains the URL to a file that contains JavaScript to be added to the page.
The following example demonstrates how to create a custom action targeting the ScriptLink
programmatically using the JavaScript client-side object model from a SharePoint-hosted app:
ctx.executeQueryAsync(success,error);
Additional Reading: You can find out more about the ScriptLink class on MSDN at
http://go.microsoft.com/fwlink/?LinkId=235313.
Demonstration Steps
1. Connect to the 20489B-LON-SP-06 virtual machine.
2. If you are not already logged on, log on to the LONDON machine as CONTOSO\Administrator with
password Pa$$w0rd.
5. In the How do you want to this this type of file (.sln)? dialog box, click Visual Studio 2012.
7. Notice that the jQuery-1.7.1.min.js is being deployed to the SharePoint file system. Note that this
location will allow the file to be accessed by using the virtual path "_layouts".
8. Expand the ScriptLinks folder, and then double-click the Elements.xml file.
9. Review the two custom actions. Note that one custom action is using the ScriptSrc property to insert
a script link tag, and the other is using a ScriptBlock property to insert a snippet of JavaScript.
10. Note that the custom action with the lower sequence number of 150 will be inserted before the
higher sequence number of 151.
11. Expand the Features folder, and then double-click on the ScriptLinks feature.
14. Note that the script block has executed when the alert dialog is displayed in Internet Explorer®.
17. In Visual Studio, in the Features folder, double-click the ScriptLinks feature.
25. Wait for the retractions process to complete, and then close Visual Studio.
Web Parts
o PromotedSitesViewWebPart
o BaseXsltListWebPart
o ListFormWebPart
o TilesViewWebPart
SPContentType
MCT USE ONLY. STUDENT USE PROHIBITED
6-24 Developing a Publishing Site for Web Content
SPForm
SPView
The JSLink property can be set programmatically, or it can be specified as part of a CAML element.
The following code sample demonstrates how set the JSLink property on a Field element:
Registration: This function is required to register template overrides with the page template
manager.
Form Template Overrides: For each object in your template, you can provide custom display
templates for each of the separate forms: View, NewForm, EditForm, and DisplayForm.
Callbacks: As part of rendering the display template for each form, you can register a selection of
callbacks to be able to response to user actions.
Depending on the specific object being customized, there are additional properties available.
Registering a Template
When specifying the JSLink property, only the name of the file is provided. In order to register the
template, the file must contain an Immediately Invoked Function Expression (IIFE). This function is
executed when the file is loaded.
The following example demonstrates an anonymous function to register a client-side template for a field:
View
Header
Body
Footer
Group
Item
Fields
OnPreRender
OnPostRender
It is not required to provide an override for each of these properties, and not all properties are applicable
to all requirements. For example, the Header, Item, and Footer properties can be used when customizing
a template for an SPList or SPView object. The OnPreRender and OnPostRender properties can be used to
call functions before and after a template is rendered.
Scope. This defines which forms to override. Choices are View, DisplayForm, NewForm, and EditForm.
The following code demonstrates how to implement the function to render the override for a field’s
NewForm scope:
The template override function is very similar to the purpose of the Field Control class. Its job is to retrieve
values from the form context containing the field’s values, and render the HTML markup to display in the
browser.
Handling Callbacks
In addition to the normal callbacks you can associate with various DOM components by using JavaScript,
each form template includes a set of available callbacks you can use to respond to specific events related
to the form. The following are two of the most important callbacks that should be handled for the
NewForm and EditForm scopes:
MCT USE ONLY. STUDENT USE PROHIBITED
6-26 Developing a Publishing Site for Web Content
registerInitCallback. This callback is invoked when the form is being loaded. This is where you can set
the default values for controls displayed on the form.
registerGetValueCallback. This callback is invoked when the form is being submitted. This is where you
provide the value that will be saved to the SharePoint content item.
There are additional callbacks available, depending on the type of template and the view being
overridden.
The following example demonstrates functions to implement callbacks for registerInitCallback and
registerGetValueCallback:
formCtx.registerInitCallback(formCtx.fieldName, function() {
var productCodeInput = document.getElementById('productCodeTextBox’);
var productCodeValue = formCtx.fieldValue != null ? formCtx.fieldValue : '';
if ( productCodeInput != null && productCodeValue != null ) {
productCodeInput.value = productCodeValue;
}
});
formCtx.registerGetValueCallback(formCtx.fieldName, function() {
var productCodeInput = document.getElementById('productCodeTextBox’);
if ( productCodeInput != null ) {
return productCodeInput.value;
}
else {
return '';
}
});
Callbacks are registered as part of the function that overrides a particular form scope. To avoid
duplicating code, it is a good idea to place these in a separate function that can be called as needed.
The following example demonstrates deploying the template JavaScript file by using a Module element:
Objectives
After completing this lab, you will be able to:
Build and deploy custom site columns and content types to support publishing pages.
Build and deploy a custom page field control and rendering templates.
Build and deploy custom page layouts with page fields and web parts.
Lab Setup
Estimated Time: 45 minutes
Virtual Machine: 20489B-LON-SP-06
Password: Pa$$w0rd
A warm-up script named WarmUp.ps1 runs automatically when you start the virtual machine. This script
helps to improve the performance of the virtual machine by downloading the home page of the root site
in each site collection on the server. Occasionally this script displays timeout errors; you can ignore these
errors. You should ensure this script has finished running before you start the lab.
You will start by creating a User Control with rendering templates for display and edit. You will then
create a field control class to utilize the rendering templates.
6. Open the Contoso.ProductCodeTemplate.ascx file. In the code editor, append the following code:
<SharePoint:RenderingTemplate ID="ContosoProductCodeRenderingTemplate"
runat="server">
<Template>
<asp:TextBox ID="ProductCodeTextBox" runat="server" />
<asp:RegularExpressionValidator ID="ProductCodeValidator" runat="server"
ControlToValidate="ProductCodeTextBox"
ErrorMessage="Please enter a valid product code in the format @@@-####."
ValidationExpression="^[A-Z]{3}[0-9]{4}$" />
</Template>
</SharePoint:RenderingTemplate>
<SharePoint:RenderingTemplate ID="ContosoProductCodeDisplayRenderingTemplate"
runat="server">
<Template>
<asp:HyperLink ID="ProductCodeHyperLink" runat="server" />
</Template>
</SharePoint:RenderingTemplate>
Note: If you prefer, you can copy this markup from the text file at
E:\Starter\Snippets\RenderingTemplate.txt.
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
else
{
ProductCodeTextBox =
(TextBox)this.TemplateContainer.FindControl("ProductCodeTextBox");
ProductCodeValidator =
(RegularExpressionValidator)this.TemplateContainer.FindControl("ProductCodeValidator"
);
}
}
public override object Value
{
get
{
this.EnsureChildControls();
return ProductCodeTextBox.Text;
}
set
{
this.EnsureChildControls();
ProductCodeTextBox.Text = (string)this.ItemFieldValue;
}
}
Note: If you prefer, you can copy this code from the text file at
E:\Starter\Snippets\ProductFieldCode.txt.
Results: After completing this exercise, you should have created a User Control containing rendering
templates, and a custom field control.
You will start by adding page field controls, including the custom ProductCodeField control you created
in the previous exercise. Next, you will add a web part zone to enable users to add web parts to pages
using the SharePoint UI. Then you will embed a Script Web Part directly into the layout. Finally, you will
deploy and test the page layout.
3. In the code editor, add a content placeholder by appending the following code:
7. Validate that the Product Code is being displayed as the correct URL.
Results: After completing this lab, you will have learned how to build and deploy page layouts that
include page field controls and web parts.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint 2013 Advanced Solutions 06-31
Add content controls such as field controls and web parts to page layouts.
Review Question(s)
Which of the following objects does not support the JSLink Property? (Select one)
SPField
SPView
BaseFieldControl
SPContentType
ListFormWebPart
Verify the correctness of the statement by placing a mark in the column to the right.
Statement Answer
Verify the correctness of the statement by placing a mark in the column to the right.
Statement Answer
Question: Compare and contrast the Solution and Features Framework versus the Apps for
SharePoint model. What are some of the limitations in the Apps for SharePoint model that
specifically related to Web Content Management.
MCT USE ONLY. STUDENT USE PROHIBITED
7-1
Module 7
Structuring and Publishing Websites for All Users
Contents:
Module Overview 7-1
Module Overview
This module will focus on providing you with the knowledge to build websites that are mobile device
friendly, support multiple languages, and employ proper navigation. This will be accomplished by
introducing you to device channels, managed navigation, variations, and other Microsoft® SharePoint®
2013 features.
Objectives
After completing this module, you will be able to:
Configure website structure and navigation.
Lesson 1
Website Structure and Navigation
This lesson will introduce you to the various ways that SharePoint implements navigation. This includes
reviewing each of the areas that utilize SharePoint navigation providers and how you can customize them.
You will learn how to configure navigation by using both structured and managed navigation features. In
addition, you will learn how to re-use navigation terms by pinning them to other site collections’
navigation term sets.
Lesson Objectives
After completing this lesson, you will be able to:
Types of Navigation
When designing your navigation strategy, you should take into consideration all of your web applications,
site collections, and sites. You should also consider links to sites outside of SharePoint. When you consider
these types of links, you will find that there are three types of navigation that you can present to a user in
your SharePoint sites:
Global Navigation. This enables users to navigate within a site collection, including the sites in the site
collection.
Local Navigation. This enables users to navigate within a site. Items could include lists and pages
within the site. This traditionally has been implemented via the Quick Launch area in SharePoint.
Breadcrumb Navigation. This control enables users to navigate to any site between the top site and
your current site.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint 2013 Advanced Solutions 07-3
Navigation Providers
The nodes that make up a navigation menu must be stored somewhere. This can be in a SharePoint list, a
database, an XML file, or some other storage mechanism. To use this data, you must create or use an out-
of-the-box navigation provider. There are several providers that come with SharePoint, including:
SPSiteMapProvider
SPContentMapProvider
SPXmlContentMapProvider
SPNavigationProvider
PortalSiteMapProvider
TaxonomySiteMapProvider
If you want to utilize data that exists outside of SharePoint for your navigation, you must create and then
register a navigation provider with SharePoint. Registration is simple and is performed by adding the
navigation provider to the web.config file of the targeted web application.
Navigation Areas
SharePoint 2013 includes two main areas of navigation: the Global Navigation at the top of a site page,
and the Current Navigation area on the left side of a page. Each of these areas is fully customizable, or
natively supports dynamic generation of menu items. If you want to override how a navigation menu gets
its navigation nodes, you can simply override the SharePoint DelegateControl in which the data source is
defined.
Global navigation is defined in the AjaxDelta DeltaTopNavigation control of the basic master page. You
can override the data source by overriding the TopNavigationDataSource delegate control:
The Quick Launch navigation area is provided in SharePoint master pages by the SPNavigationManager
control with an ID of QuickLaunchNavigationManager. Notice that you can override the data source by
overriding the QuickLaunchDataSource delegate control:
<Template_Controls>
<asp:SiteMapDataSource
SiteMapProvider="SPNavigationProvider" ShowStartingNode="False" id="QuickLaunchSiteMap"
StartingNodeUrl="sid:1025" runat="server" />
</Template_Controls>
</SharePoint:DelegateControl>
<SharePoint:AspMenu id="V4QuickLaunchMenu"
runat="server" EnableViewState="false" DataSourceId="QuickLaunchSiteMap"
UseSimpleRendering="true" Orientation="Vertical" StaticDisplayLevels="3"
AdjustForShowStartingNode="true" MaximumDynamicDisplayLevels="0" SkipLinkText="" />
</SharePoint:SPNavigationManager>
<SharePoint:SPNavigationManager
id="TreeViewNavigationManagerV4"
runat="server"
ContainedControl="TreeView"
CssClass="ms-tv-box"
>
<SharePoint:SPLinkButton runat="server"
NavigateUrl="~site/_layouts/15/viewlsts.aspx" id="idNavLinkSiteHierarchyV4"
Text="<%$Resources:wss,treeview_header%>"
accesskey="<%$Resources:wss,quiklnch_allcontent_AK%>"
CssClass="ms-tv-header" />
<SharePoint:DelegateControl
runat="server" ControlId="TreeViewAndDataSource">
<Template_Controls>
<SharePoint:SPHierarchyDataSourceControl
runat="server"
id="TreeViewDataSourceV4"
RootContextObject="Web"
IncludeDiscussionFolders="true"
/>
<SharePoint:SPRememberScroll
runat="server" id="TreeViewRememberScrollV4"
onscroll="javascript:_spRecordScrollPositions(this);"
style="overflow:
auto;">
<SharePoint:SPTreeView
id="WebTreeViewV4"
runat="server"
ShowLines="false"
DataSourceId="TreeViewDataSourceV4"
ExpandDepth="0"
SelectedNodeStyle-
CssClass="ms-tv-selected"
NodeStyle-CssClass="ms-
tv-item"
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint 2013 Advanced Solutions 07-5
SkipLinkText=""
NodeIndent="12"
ExpandImageUrl="/_layouts/15/images/tvclosed.png?rev=23"
ExpandImageUrlRtl="/_layouts/15/images/tvclosedrtl.png?rev=23"
CollapseImageUrl="/_layouts/15/images/tvopen.png?rev=23"
CollapseImageUrlRtl="/_layouts/15/images/tvopenrtl.png?rev=23"
NoExpandImageUrl="/_layouts/15/images/tvblank.gif?rev=23"
>
</SharePoint:SPTreeView>
</SharePoint:SPRememberScroll>
</Template_Controls>
</SharePoint:DelegateControl>
</SharePoint:SPNavigationManager>
SharePoint enables a breadcrumb control that does not exist by default on the master pages:
Structured Navigation
Structured navigation in SharePoint builds
navigation menus based on the sites and pages in
the site collection. When configuring structured
navigation, you can select whether sites and\or
pages are displayed automatically. You also have
the ability to specify how many items will be
displayed in the navigation area. By default, this is
limited to 20 items. It is poor practice to have more
than a handful of items in the navigation areas;
limiting the items is recommended.
The default provider used in structured navigation is the SPNavigationProvider. This provider will
interrogate the node data this is stored in the SPWeb’s Navigation property. These nodes are added
automatically when various events occur in SharePoint (like a new site being added). When adding new
nodes, you may not see your changes displayed immediately because the nodes are cached in a special
memory object called CachedNavigation of the SPWeb object.
MCT USE ONLY. STUDENT USE PROHIBITED
7-6 Structuring and Publishing Websites for All Users
Farm-Wide Navigation
Structural navigation only spans a site collection. It does not allow you to have a single instance of
navigation that can be used to provide the same links across all of your SharePoint sites in the farm. In
order to do this, you would need to implement your own custom navigation provider and point your
master pages to this navigation provider. It also means that you will need to design your master pages to
allow for both a global-global navigation area and a global-local navigation area. If you choose not to
implement a farm-wide navigation strategy, you will be limited to site collection navigation as your global
navigation strategy.
Global Navigation
Global navigation with structured navigation will display only items that exist in the site collection. You
must manually add any nodes you want to display that live outside of the respective site collection. This
means that you would also need to add these nodes manually to any other site collection’s structural
navigation configuration. You will not be able to reuse your settings.
Current Navigation
With current navigation in a structured navigation configuration, by default you will see all the items at
the current site level. This is helpful for navigating inside the respective site. However, this can be
overridden to display exactly what would be displayed in the global navigation, and you also have the
ability to customize the navigation nodes.
Managed Navigation
In addition to structural navigation, SharePoint
2013 has added a new option called Managed
Navigation. Managed navigation uses the Managed
Metadata service application to feed navigation
nodes via a special navigation provider called
TaxonomySiteMapProvider. To add navigation to
a site, you simply add terms to a term set. Each
term has a set of properties that define the title and
the URL of the node.
Term Sets that are created programmatically must include specific custom properties in order to be used
as managed navigation:
//set properties
termSet.SetCustomProperty("_Sys_Nav_IsNavigationTermSet", "True");
//termSet.SetCustomProperty("_Sys_Facet_IsFacetedTermSet", "False");
//termSet.SetCustomProperty("_Sys_Nav_AttachedWeb_SiteId", site.ID.ToString());
//termSet.SetCustomProperty("_Sys_Nav_AttachedWeb_WebId", site.RootWeb.ID.ToString());
//termSet.SetCustomProperty("_Sys_Nav_AttachedWeb_OriginalUrl", site.RootWeb.Url);
Navigation Terms
Terms that are added to a navigation term set must also be set up with custom properties in order for
them to be used. If these properties are added or configured incorrectly, the navigation menus will display
errors and the UI can become unresponsive when editing the terms. There are two types of navigation
links that can be used:
Target URLs. These use the _Sys_Nav_TargetUrl property and must be set to a valid page in the site. If
the page does not exist in the site, the node will not render.
Simple Link URLs. These use the _Sys_Nav_SimpleLinkUrl property and are absolute URLs to a valid
web site (both inside and outside of SharePoint).
Creating navigation terms programmatically requires special properties:
t = termSet.CreateTerm("Intranet", 1033);
t.SetLocalCustomProperty("_Sys_Nav_SimpleLinkUrl",
"http://intranet.contoso.com/Pages/Home.aspx");
Note: Terms do not have versioning features like pages. If you change a term, the change
is immediate and you cannot revert to previous changes.
Sort Order
Just like with structured navigation, you also have the ability to sort the terms in some custom fashion via
the Term Store Management Tool. Using a custom sort order will ensure that terms appear in a consistent
manner, regardless of the language or any changes in the default labels.
Note: When you reuse terms that are relative links, the code will check to see if the page
actually exists in the site. If it does not, then the node will not be rendered in the navigation area.
You can use pinning to create pointers to terms from other term sets:
Friendly URLs
Previous versions of SharePoint had an interesting way of generating the item’s URL. The links were
awkward because they tended to be incredibly long and not easy to remember. These long URLs also
meant that when you copied and pasted them in emails, they would take up much of the email body. It
also meant that when a search engine indexed the path of the items, it would not be able to do any type
of path-based relationships.
An example of an unfriendly URL for users and search engines from previous SharePoint versions is:
http://www.contoso.com/SitePages/Publishing/Product.aspx?ID=157
http://www.contoso.com/Product/157
Shorter URLs are made possible by the managed navigation feature of SharePoint 2013. You can create
term-driven navigation that will simplify your URLs. For example, you can convert the following URL from
http://intranet.contoso.com/Pages/home.aspx to http://intranet.contoso.com/Home.
Friendly URLs even let you assign more than one term to a page, so the above example could also have a
term-drive page called http://intranet.contoso.com/Default. These friendly URLs assist with Search Engine
Optimization (SEO) on Internet-facing sites.
GlobalNodes
TopNavigationBar
QuickLaunch
SearchNav
TitleResource : Microsoft.SharePoint.SPUserResource
IsVisible : True
IsDocLib : True
IsExternal : False
Id : 1000
ParentId :0
Parent :
Navigation : Microsoft.SharePoint.Navigation.SPNavigation
Url : /default.aspx
Children : {}
Properties : {vti_globalpage}
TargetSecurityScopeId : 6fba9156-d2b1-4a9f-a127-7f05a55f2020
TargetParentObjectType : Web
As you can see, the node contains some very important properties that determine how the node will be
displayed, what type of node it is, and what kind of permissions will be enforced on the node.
MCT USE ONLY. STUDENT USE PROHIBITED
7-10 Structuring and Publishing Websites for All Users
The following code shows a simple example of how to add navigation nodes programmatically in a non-
publishing SharePoint site:
As you can see from the code snippet above, there are no configuration properties available that enable
you change the navigation from Structured to Metadata Navigation. This has to be done by using a
special class called WebNavigationSettings.
You can manage site navigation programmatically by using server-side and client-side APIs. Each type of
navigation requires a different set of classes in order to manipulate it.
Publishing webs require a different approach to updating navigation than non-publishing sites:
Changing the type of navigation provider is implemented in a new class in SharePoint 2013. Older classes
do not know about metadata navigation:
Lesson 2
Publishing Content
In this lesson, you will learn about the basic web publishing features of SharePoint, which include check-
in, check-out, content approval, versioning, and workflows. Next, you will explore the new features of
cross-site publishing in SharePoint 2013, and how to set up and configure lists and libraries to be catalogs
that are used to generate cross-site source and target sites. Finally, you will be shown that search and
metadata navigation are a big part of the cross-site publishing architecture.
Lesson Objectives
After completing this lesson, you will be able to:
Publishing Features
Companies today are becoming very agile. Content
must be published in larger quantities and at a
faster pace. Anything that can help automate and
increase productivity will help to deliver high-
quality content to users who need and want it. You
can easily achieve these publishing goals by
leveraging the publishing features in SharePoint.
SharePoint provides several publishing features to support these types of content and the policies and
procedures that wrap them. These include:
Check in and Check out. This feature enables a user to check out content that is being edited, which
prevents other authors from making changes.
Major and Minor versions. This feature enables users to keep older versions of files, with optional
comments. This helps to prevent losing old work due to copy-and-replace actions.
Content Approval. When enabled, only content that has a status of Approved will display to users. Any
draft, pending, or rejected versions will not be displayed.
Approval Workflows. If you have pages or content that must be approved by a single or by multiple
users, you can set up a workflow that requires those individuals’ approval.
MCT USE ONLY. STUDENT USE PROHIBITED
7-12 Structuring and Publishing Websites for All Users
When simply assigning tasks to approvers will not meet your content approval requirements, you can use
SharePoint Designer to implement much more advanced approval workflows. For example, you can build
workflows that:
Route approvals based on the type of content (invoices, web page, IT requests, and so forth).
Route approvals based on metadata (amount of an invoice, the type of IT request, and so forth).
Publishing Environments
In well-organized organizations, you will find a very
specific set of procedures when deploying new
code and customizations to applications. These
procedures normally define a process in which
customizations are moved from one environment
to the next, and each environment is managed by
individuals with specific roles in the deployment
process. For example, when developing a piece of
code, it is common for a developer to work on their
development machine, and when they are code
complete, they will pass the application to the
Quality Assurance (QA) team for testing. In a
traditional organization you will find the following environments:
Development. The environment in which developers design and build applications that will eventually
be used in production.
Quality Assurance (QA). A team of engineers that tests the developer’s code to confirm that all
requirements have been met. If requirements have not been met, QA passes the code back to the
developers
Staging. The environment where the proposed deployment can be tested before going to production.
Any inaccuracies in the deployment process must be documented. If failure occurs, the deployment is
passed back to QA and development for refinement
Production. The environment for all tested and approved applications and updates.
These well-defined environments ensure that a high quality product is released to users with minimal to
zero issues. In large organizations with large investments in SharePoint, you will find very strict policies
driving the use of all four of these environments.
SharePoint Authoring
In a SharePoint publishing environment, you typically have an additional environment called the
authoring environment. This environment is where users develop the content that will be published to the
production site. The reason for this extra environment is the policy that dictates that no changes will be
made in production without first being approved. These policies prevent any type of editing in the
production environment. As a result, an authoring environment is required. In the absence of these
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint 2013 Advanced Solutions 07-13
policies, corporations will edit documents in the production environment, which is also a supported
method of authoring in SharePoint.
Cross-Site Publishing
In addition to the content deployment APIs, there is
a new way of deploying content to sites in
SharePoint 2013 called Cross-site publishing. Cross-
site publishing does not use the content
deployment APIs, but instead utilizes search and
managed navigation as its deployment
methodology. This type of publishing provides
benefits such as:
Authoring site. The source of content that should be published. This site contains list data that will be
consumed by other sites.
Catalog list. Source of content that should be published and displayed on a target publishing site.
Search. The component responsible for finding, indexing, and exposing content to the target
publishing sites.
Term store. Contains the metadata used to organize the content and the navigation to content in a
publishing site.
Publishing site. The site that users will use to browse the content authored on the authoring site by
using specific catalog page layouts.
Cross-site publishing can be used to deploy content from one site to one site (1:1) or one site to many
sites (1:N). In order to utilize cross-site publishing you must perform several steps:
1. Enable the Cross-Site Collection Publishing feature on the source site.
Note: As of this writing, SharePoint Online does not support cross-site publishing. Only on-
premise installations can utilize this feature.
MCT USE ONLY. STUDENT USE PROHIBITED
7-14 Structuring and Publishing Websites for All Users
Considerations
There are several moving pieces to cross-site publishing and you should make sure you are aware of any
limitations or quirks before you implement, some of these are:
Content is not shown until it is indexed. Be sure that your search architecture is configured properly
and is set up to index your content in an efficient manner for publishing the latest content to the
sites. Items will not be indexed if they are not approved, so make that your content is approved.
Term store does not support versioning. If you create terms that do not have corresponding content,
users will be presented with empty options and the experience will not be optimal
Basic Lists do not have content approval enabled by default. This means that the list data will always be
indexed and displayed. You will not have the ability to limit the publishing of the content, and it will
be displayed regardless of whether it is complete, valid, or approved.
Consuming Catalogs
Before you can show content from an authoring site collection, you have to configure the catalog
connections in the publishing site collection that will consume those catalogs. When you configure
catalog connections, you specify which catalogs the publishing site collection will use to show content.
When you configure a catalog connection, you must specify several pieces of information, including:
The category page layout has four Web Part zones: Body, Left, Bottom Center, and Right.
A Content Search Web Part is added to the Body Web Part zone.
The query in the Content Search Web Part is pre-configured to use the result source that is created
automatically during catalog connection. The result source limits search results to the current and
sub-page navigation terms.
The item display template that is used is Picture on top, three lines on bottom (known as
Item_Picture3Lines in the Master Page Gallery).
By default, a page based on the catalog item page layout is added to the Pages library with the name
CatalogItem-<catalog name>. The page is applied to the last level (catalog item) within the catalog
navigation structure, for example, to show the individual product Contoso Digital Camera M200. The
association between a catalog item page and items within the catalog appears in the Term Store
MCT USE ONLY. STUDENT USE PROHIBITED
7-16 Structuring and Publishing Websites for All Users
Management Tool, on the TERM-DRIVEN PAGES tab. The catalog item page layout has the following
features:
The catalog item page layout has one Web Part zone, which is Body.
A Catalog-Item Reuse Web Part is added to the Body Web Part zone.
The query in the Catalog-Item Reuse Web Part is pre-configured to use the result source that was
created automatically during catalog connection, and to limit search results based on an additional
query filter.
In addition to the Catalog-Item Reuse Web Part in the Body Web Part zone, one server-side Catalog-Item
Reuse Web Part is added to the catalog item page layout for each indexed field in the catalog. By default,
all Catalog-Item Reuse Web Parts on a page use the same query as the first Catalog-Item Reuse Web Part.
These fields render server-side in the page layout, and can only be changed by editing the catalog item
page layout directly. Because these are server-side Web Parts, you should edit the HTML source page to
specify the HTML that is rendered together with the catalog content.
Objectives
After completing this lab, you will be able to:
Lab Setup
Estimated Time: 45 minutes
Password: Pa$$w0rd
A warm-up script named WarmUp.ps1 runs automatically when you start the virtual machine. This script
helps to improve the performance of the virtual machine by downloading the home page of the root site
in each site collection on the server. Occasionally this script displays timeout errors; you can ignore these
errors. You should ensure this script has finished running before you start the lab.
4. Review the navigation settings for the SharePoint site. Notice that both the global navigation and the
current navigation are set to use structural rather than managed navigation.
6. Open the Central Administration website and browse to the Managed Metadata term store. Notice
that there is currently no navigation term group.
o Microsoft.SharePoint.Taxonomy.dll
o Microsoft.SharePoint.dll
o Microsoft.SharePoint.Publishing.dll
Note: You can find all of these assemblies in the C:\Program Files\Common
Files\microsoft shared\Web Server Extensions\15\ISAPI folder.
9. In the Program class, add using statements for the following namespaces:
o Microsoft.SharePoint
o Microsoft.SharePoint.Administration
o Microsoft.SharePoint.Navigation
o Microsoft.SharePoint.Publishing
o Microsoft.SharePoint.Publishing.Navigation
o Microsoft.SharePoint.Taxonomy
10. Add a static method named CreateGroup to the Program class. The method should:
o Accept an argument of type TermStore named termStore.
11. In the CreateGroup method, check whether the passed-in TermStore already contains a Group
object with the passed-in name. If it does not, create the Group object and return it to the caller. If
the Group object already exists, return the existing Group object to the caller.
Note: If you prefer, you can copy the CreateGroup method from the text file at
E:\Labfiles\Starter\Snippets\CreateGroup.txt.
12. Add a static method named CreateNavigationTermSet to the class. The method should:
o Return void.
13. In the CreateNavigationTermSet method, check whether the passed-in group already contains a
term set with the passed-in name. If the term set does not already exist:
e. Set a custom property to indicate that the term set is a navigation term set.
Note: If you prefer, you can copy the CreateNavigationTermSet method from the text file
at E:\Labfiles\Starter\Snippets\CreateNavigationTermSet.txt.
14. In the Main method, create a new TaxonomySession object using the site collection at
http://intranet.contoso.com.
17. Use the CreateNavigationTermSet method to create a term set named Intranet.
19. When the program has finished running and the console window has closed, switch back to the
Central Administration website and reload the Term Store Management Tool page.
20. Verify that the list of term groups now includes a group named Navigation.
21. Expand the Navigation group, and verify that the group includes a term set named Intranet.
o Return void.
Term Term
Navigation Settings
Name LCID
Term Term
Navigation Settings
Name LCID
Note: If you prefer, you can copy the CreateNavigationTerms method from the text file at
E:\Labfiles\Starter\Snippets\CreateNavigationTerms.txt.
4. In the Main method, below the existing code, retrieve the term set named Intranet from the term
group.
5. Call the CreateNavigationTerms method, passing the Intranet term set as an argument.
8. Expand Navigation, expand Intranet, and notice the terms in your term set.
9. Click the Intranet term set, and on the INTENDED USE tab notice that the Use this Term Set for
Site Navigation check box is selected.
10. Click the Finance term, and on the NAVIGATION tab notice that the Simple Link or Header option
is selected.
11. Click the Home term, and on the NAVIGATION tab notice the Term-Driven Page with Friendly
URL option is selected.
12. On the TERM-DRIVEN PAGES tab, notice the Target Page Settings has been configured to
/Pages/Home.aspx.
o Return void.
2. In the PinTermSet method, iterate over the terms in the source term set.
3. For each term in the source term set, re-use the term with pinning in the target term set.
Note: If you prefer, you can copy the PinTermSet method from the text file at
E:\Labfiles\Starter\Snippets\PinTermSet.txt.
4. In the Main method, below the existing code, call the CreateNavigationTermSet method again.
Pass the Navigation group and the string text Team as parameters.
5. Retrieve the term set named Team from the Navigation group.
6. Call the PinTermSet method. Specify the Intranet term set as the source term set and the Team
term set as the target term set.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint 2013 Advanced Solutions 07-21
9. When the program has finished running and the console window has closed, switch to SharePoint
2013 Central Administration.
12. Expand Team, and notice the same terms exist in the new term set as in the Intranet term set.
o Return void.
2. Within the SetManagedNavigation method, configure the passed-in site to use the taxonomy
provider for global navigation.
4. Retrieve the ID value of the term set with the passed-in term set name.
5. Use the term store ID and the term set ID to associate the site global navigation with the specified
term set.
Note: If you prefer, you can copy the SetManagedNavigation method from the text file at
E:\Labfiles\Starter\Snippets\SetManagedNavigation.txt.
7. In the Main method, instantiate an SPSite object in a using statement for the site at
http://intranet.contoso.com.
8. Within the using statement, call the SetManagedNavigation method. Pass the SPSite instance, the
group name Navigation, and the term set name Intranet as arguments.
9. Instantiate an SPSite object in a using statement for the site at http://team.contoso.com.
10. Within the using statement, activate the site collection publishing infrastructure feature (use the
GUID value f6924d36-2fa8-4f0b-b16d-06b7250180fa).
11. Call the SetManagedNavigation method. Pass the SPSite instance, the group name Navigation,
and the term set name Team as arguments.
Note: If you prefer, you can copy the Main method from the text file at
E:\Labfiles\Starter\Snippets\Main.txt.
13. When the program has finished running and the console window has closed, switch to Internet
Explorer and browse to http://intranet.contoso.com.
14. Notice the managed navigation items are displayed. If the navigation items are not visible, click
Refresh.
15. Click the HR node, notice that you are directed to the http://intranet.contoso.com/hr URL.
16. Click New Tab, in the address bar, type http://team.contoso.com, and then press Enter. Notice that
in the global navigation area, the pinned terms being used are similar to your intranet publishing site.
Results: A new navigation term set used by a site collection and shared by a team site.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint 2013 Advanced Solutions 07-23
Lesson 3
Publishing to Mobile Devices
In this lesson, you will learn about the new features in SharePoint 2013 that support mobile devices. This
includes understanding device channels and device channel panels.
Lesson Objectives
After completing this lesson, you will be able to:
Screen size. Mobile devices have wildly different size screens, and each screen size will present the
content in a different way. This is important when rendering large pictures and icons, or placing ads
on the page.
Touch support. Some devices support a touch interface. For those that do, a touch-friendly UI should
be presented, including larger buttons and easily clickable links.
Network bandwidth. Mobile phones tend to utilize network technologies like 3G and 4G, and some of
the newer network transmission protocols such as 4G LTE. Each network technology has differing
speeds that dictate what a device is capable of downloading in short periods of time. This is
important when using large supporting files such as JavaScript libraries and images.
Browser and browser feature support. The browser that runs on the device is also important because it
may not support some of the newer web technologies such as HTML5 or the latest versions of
JavaScript and CSS.
SharePoint 2013 has been designed to provide better support for mobile devices, and also gives you the
flexibility of changing its behavior based on your current or future devices. Out of the box, you have three
possible browsing options when using a mobile device:
Contemporary view. The optimized browser experience for mobile browsers. This view renders in
HTML5 and has many mobile-friendly features.
MCT USE ONLY. STUDENT USE PROHIBITED
7-24 Structuring and Publishing Websites for All Users
Classic view. An HTML, CHTML, WML, or similar view that is rendered on devices that do not support
HTML5.
Full-screen UI. This is the full desktop version view of a SharePoint site.
Each view depends on the mobile device and capabilities as outlined above.
Contemporary View
This new view in SharePoint 2013 provides HTML5 support and offers the following features:
Menu button. Located on the right side of the page view, it allows a user to access “Site Contents”, or
“Sign Out”, or “Close” a particular view.
Switch to PC View. This will switch the view from the mobile view to the full desktop view.
Navigation window. The navigation window allows a user to browse the content in a site.
Tap to open links. This feature allows users to more easily tap links, because they are rendered with a
wide strip that can be clicked.
Once activated, SharePoint will interrogate the HTTP header variables and make a decision based on the
values defined in the browser definition file. This file, called compat.browser, lives in the virtual directory
of the SharePoint web application under the App_Browsers directory. When new devices are added to
your network, you may need to update this file to tell SharePoint which features the device supports and
if it is a mobile device.
Device Channels
Despite all the improvements offered out of the box
with SharePoint 2013, you may still have devices
that need even more targeted customizations to
ensure user satisfaction and adoption. If you find
you have this requirement, SharePoint 2013
provides a new feature called Device Channels.
Device channels allow you to specifically target
devices with custom master pages and CSS by using
the HTTP User Agent header that is passed with
every browser request.
Alias. The name used to identify the channel when you reference it in code and device channel
panels.
Description. A simple field for describing the channel and its usage.
Device Inclusion Rules. The user-agent field that the device channel is targeted at.
Active. Whether the device channel is ready for production use. This can be tested by using the
DeviceChannel query string, which is explored later in the module.
Note: You can have up to 10 device channels per site, and each device channel can have
up to 150 device inclusion rules.
Once you have created a device channel, you must create a master page to use with the device channel.
Ultimately, this master page would target the capabilities of the device. For example, if it has a small
screen, then you might want to replace the large images that are used on your pages with smaller ones or
remove the images completely. The logic for selecting a device channel resides in the
PublishingLayoutPage, which most pages in SharePoint inherit from. Inside the OnPreInit is where the
HTTP request is analyzed, and then the appropriate master page is selected. The mapping of a device
channel to a master page must be done by using the SharePoint UI because there are no APIs that
currently support changing it. When you make a change to a mapping, that change is saved in the master
page gallery as a file called __DeviceChannelMapping.aspx.
Ordering
In many cases, a particular device manufacturer or a particular product may include many different device
models, each with significant differences in the features they support. In this case, you will need to create
more than one channel for the same set of devices. This is where the ordering of the device channels
becomes very important. You should always have the more specific user-agent values at the top of the list
to make sure that they are called (rather than the more generic ones).
Note: You can test your Device Channel panels by appending the DeviceChannel
querystring to the end of your page URL:
http://teams.contoso.com/pages/default.html?DeviceChannel= WindowsPhone
You can have individually targeted content on master pages by using Device Channel Panels:
</PublishingWebControls:DeviceChannelPanel>
Demonstration Steps
1. Start the 20489B-LON-SP-07 virtual machine.
4. In Internet Explorer, in the address bar, type http://intranet.contoso.com, and then press Enter.
7. On the Design Manager: Manage Device Channels page, click Create a channel.
8. In the Device Channels - New Item dialog box, in the Name box, type Windows Phone.
12. Select the Active check box, and then click Save.
13. In the Device Channels - New Item dialog box, click Close dialog.
Lesson 4
Multi-Language Sites Using Variations
In this lesson, you will configure variations on your intranet site and then create a new French variation.
You will also learn how to export XLIFF files and how to test variations by using your browser language
settings.
Lesson Objectives
After completing this lesson, you will be able to:
Configure variations.
Variations
Companies that have customers and employees in
different parts of the world often require the same
content in SharePoint sites, but in different
languages. This requirement usually means you
have a source site that needs its content copied and
then translated to target sites. SharePoint provides
the Variations feature to facilitate these types of
requirements. Common scenarios include:
Multiple devices. Content that is published to target sites that have varying layouts to support specific
devices.
Coordinating Content Creation and Updates. Ensuring that content is synchronized and managed
when you have several versions of it is a daunting task that is made easier through the use of the
variations feature.
Accuracy of translated content. Ensuring that the content is accurately translated into the target
language.
Variation root site. The site that will contain the landing page that will redirect users to the proper
variation sites. This site does not have to be the root site of the site collection. It cannot be changed
after you have created it.
Variation sites. There are two types of variations, source and target. Each time you create a new label,
a corresponding site will be created.
Variations hierarchy. The entire set of sites in the variation root site, you can have only one variation
hierarchy per site collection.
MCT USE ONLY. STUDENT USE PROHIBITED
7-28 Structuring and Publishing Websites for All Users
Variation lists. Lists that have been configured to be synchronized to the target variation sites
Variation pages. Pages that are stored in the Pages library of the source variation. You should avoid
adding any other types of documents other than pages in the Pages library.
Timer Jobs. A series of jobs will review the settings in the variation configuration and then do the
work necessary to set up any variation labels
Event Receiver. The Pages library has several event receivers attached to it that are in charge of telling
the variations architecture that changes have been made
Note: SharePoint on-premise can have up to 209 variation labels. SharePoint Online™ can
have up to 50.
Variation redirection works by analyzing the browser’s language setting and then routing the user to the
proper variation via a redirection page. For example, if the user’s browser language is French, when the
user hits the variation root site they will be redirected to the French version (if you have created it,
otherwise it goes to the source variation). You can customize the redirection page with your own
redirection logic if you prefer to redirect based on factors other than the browser language setting.
Each time a source variation site has a new item (in most cases, a web page in the Pages library) created, a
corresponding item is created in all the target variations. This item is an exact replica of the original and
must either be translated by someone or else translated by using the machine translation service.
Note: The Variation architecture does not copy resources like images and documents. This
is a feature of the content deployment APIs.
Variation Configuration
There are several settings you can configure when you setup variations, these include:
Site, List and Page Creation Behavior. Specifies if sites, lists, and pages of the source variation are
created automatically or manually. By default, the setting is Create Everywhere, which means they are
always created.
Recreate Deleted Target Page. Specifies if a pages should be recreated if it is deleted in a target
variation.
Update Target Page Web Parts. Specifies if web parts should be updated on target pages if the source
pages are updated.
Notification. Sends email notifications to the target label contact when a new page is created, or
notifies the page owner when a page is updated.
Property bag of root site of site collection. These include the ID of the Relationships List and Labels list.
Property bag of root folder of root site of site collection. This will be used to save the status of any
content deployment jobs.
Property bag of root folder of Relationships List. This includes the Update Web Parts, Auto Spawn Stop
After Delete, Source Variation Root Web Template, Copy Resources, Enable Auto Spawn properties,
Send Notification Email, Disable Automatic Propagation, and Translate Fields properties
List Items in Relationships List. Used to save the variation root site URL in case you move the site by
using the Site Manager feature.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint 2013 Advanced Solutions 07-29
List Items in Variation Labels List. Each label created will be saved here.
Property bag of sites in the Variation Hierarchy. Stores the link of sites to peers.
Fields of pages in the Variation Hierarchy. Links pages and their peers.
Variation Logs
The variation system logs status information to the hidden Long Running Operation Status list in the root
of the site collection. You can use this to see the status of the various timer jobs that execute in order to
create the variations hierarchy and variation label sites.
Variation Labels
A Variation label is the name of a variation site. As
part of the configuration process, you must create a
source variation and then the target variations. The
variation label will normally correspond to the
language that the variation implements. For
example, if you create three variations called EN, FR,
and DE, you will have corresponding sites at
http://www.contoso.com/EN,
http://www.contoso.com/FR, and
http://www.contoso.com/DE.
Language. These options are based on the language packs you have installed in the system. Even
though your target may be a different language in terms of content, you may find the UI in the
default language. You should ensure that both the content and the UI are translated.
Locale. The locale that is used to determine where the browser will be redirected based on the default
browser language setting.
Label name. The label that will be used in the site’s URL.
Hierarchy Creation. Made up of three options that determine what language items will be translated
into. These include Sites, Lists, and Pages.
Translation Options. Two settings that determine if human or machine translation is enabled.
Page Update Behavior. How sync will work when a source page is updated.
Label Contact. The person who will be contacted when the site is created, new pages are copied, and
new sites and lists are created
When creating a variation site, if you want the user interface to reflect the language of the variation, you
must make sure that the language pack has been installed. Otherwise, the site’s UI will be in your default
language, but the various pages with be in the target language (after they have been translated).
Additional Reading: For more guidance on language packs, see Install or uninstall
language packs for SharePoint 2013 at http://go.microsoft.com/fwlink/?LinkId=141342.
MCT USE ONLY. STUDENT USE PROHIBITED
7-30 Structuring and Publishing Websites for All Users
Timer Jobs
Once you have configured your variation hierarchy, SharePoint will create the hierarchy using Time Jobs.
These timer jobs execute in the OWSTimer.exe windows service and will only execute if that service is
running. Timer jobs include:
Variations Create Hierarchies Job Definition. Responsible for creating the variation hierarchy on any
un-spawned labels.
Variations Propagate List Items Job Definition. Creates and updates peer list items.
Variations Propagate Page Job Definition. Creates and updates peer pages in the target variations.
Variations Propagate Sites and Lists Job Definition. Creates peer sites and lists when a user creates a
variation site
Variation timer jobs implement the SPWorkItemJobDefinition job class. The reason for this is that the
worker process of the web application is not normally allowed to write to the configuration database. This
means the timer jobs must pull the workload data from the content database via work items. Once the
timer jobs have successfully completed, the work item is removed.
Translating Content
Once the source and target variations have been
configured and created, pages must be translated
to the target variation language. This can be done
one of two ways:
Human translation
Machine translation
Human Translation
The goal of variations is to create language-focused
versions of a particular web site. In previous
versions of SharePoint, translation workflows would
be executed to let translators know that a page
needed to be translated. This would typically occur when a page is copied from the source variation to the
target variation. This is a simple copy operation, and no translation is performed. Whatever the page’s
source language was, for example English, is what it will have in the target. The human translator will then
need to translate the page.
Machine Translation
SharePoint 2013 includes a new service application called Machine Translation. This service acts as a proxy
to the online Microsoft Translation service. Several features within SharePoint can take advantage of
machine translation. These include:
Office Web Apps (Word and PowerPoint translation)
Managed Metadata
You should be careful with what you submit to machine translation. This content is submitted to Microsoft
and is available for the company to review in order to improve the translation engine. You should also
consider that machine translation is far from perfect, and a human reviewer will still need to confirm the
content was translated properly.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint 2013 Advanced Solutions 07-31
XLIFF Files
Pages can be exported for translation by external companies by using industry standard file formats. The
most common of the translation file formats is XML Localization Interchange File Format (XLIFF). Once
translated, these translation files can then be imported back into the variation site to update the pages.
Additional Reading: For more guidance on the XLIFF standard, see OASIS XML Localisation
Interchange File Format (XLIFF) TC at http://go.microsoft.com/fwlink/?LinkId=258217.
Multilingual Navigation
Each variation will have a managed term set created
for it. By default, the term set for the source
variation is called Variations Navigation. The term
set for the target is called Variations Navigation
(LabelName). Each time you create a new page, the
target variation page will be created and a new
term added to the term set. Variations will not copy
a term set term to a target site unless there is a
page associated with it. If you create any other
terms, they will not be copied. Once you have
associated terms with pages in the source site
collection, running the Variations Propagate Page
Job Definition job for the web application in which your variations site collection exists will create the re-
used terms.
When working with managed navigation and variations, consider the operation to be similar to a one-
time copy operation. This means that if you change attributes of the terms or move them into a different
place in a term hierarchy, they won’t get picked up by the variations timer jobs. If you make changes in
the terms after they’ve been pushed to the target sites, you will need to do some manual updating or
write scripts for the updates.
When you export a page for translation, the term label is also exported. When you import the package,
the term label is also updated.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint 2013 Advanced Solutions 07-33
Contoso managers would like to have a more customized experience when using their mobile phones and
other devices when browsing the intranet. They have asked you to utilize the device channel feature in
SharePoint 2013 to implement the customizations.
Objectives
After completing this lab, you will be able to:
Lab Setup
Estimated Time: 60 Minutes
Virtual Machine: 20489B-LON-SP-07
Password: Pa$$w0rd
A warm-up script named WarmUp.ps1 runs automatically when you start the virtual machine. This script
helps to improve the performance of the virtual machine by downloading the home page of the root site
in each site collection on the server. Occasionally this script displays timeout errors; you can ignore these
errors. You should ensure this script has finished running before you start the lab.
9. Save the file, close SharePoint Designer, and switch back to Internet Explorer.
10. In the site settings for the site at http://intranet.contoso.com, specify that the Windows Phone
device channel should use the WindowsPhone master page.
Results: After completing this exercise, you should have configured a device channel for Windows Phone
devices.
a. TagPrefix: PublishingWebControls
b. Namespace: Microsoft.SharePoint.Publishing.WebControls
Note: You can copy the Register directive from the text file at
E:\Labfiles\Starter\Snippets\PublishingWebControlsTagPrefix.txt.
11. Immediately above the located code, add a DeviceChannelPanel element with the following
properties:
Note: If you prefer, you can copy the DeviceChannelPanel element from the text file at
E:\Labfiles\Starter\Snippets\DeviceChannelPanel.txt.
12. Save the file, close SharePoint Designer, and switch back to Internet Explorer.
13. In the site settings for the site at http://intranet.contoso.com, specify that all device channels
should use the custom master page.
3. Reload the page, and notice that the page now includes a welcome message for Windows Phone
users.
Results: After completing this exercise, you should have configured a master page to use device channel
panels to display content to users of specific devices.
MCT USE ONLY. STUDENT USE PROHIBITED
7-36 Structuring and Publishing Websites for All Users
Review Question(s)
Question: What will be your SharePoint navigation strategy?
Verify the correctness of the statement by placing a mark in the column to the right.
Statement Answer
Verify the correctness of the statement by placing a mark in the column to the right.
Statement Answer
10
Verify the correctness of the statement by placing a mark in the column to the right.
Statement Answer
Verify the correctness of the statement by placing a mark in the column to the right.
Statement Answer
Module 8
Developing Optimized Internet Sites
Contents:
Module Overview 8-1
Module Overview
While most of the attention when building an Internet-facing site is focused on layout and content, your
site will not be successful if nobody can find it, or if poor performance degrades the user experience.
Internet users today have very short attention spans. You need to grab their attention when they search
for content and provide a fast and accurate user experience when accessing site content. To mitigate
these concerns, it is important to optimize Internet sites for search engines, and to ensure that the site
provides the best possible performance for the user’s device, browser, and network characteristics.
In this module, you will learn how to optimize your site for Internet search engines and how to maximize
the performance of rendering your site content.
Objectives
After completing this module, you will be able to:
Lesson 1
Optimizing a SharePoint Site for Search Engines
Microsoft® SharePoint® 2013 includes a number of new features to assist with search engine
optimization (SEO), and helps to ensure that SharePoint is a great platform for Internet-facing web sites.
These new features include the ability to define user-friendly and canonical URLs for pages, support for
Sitemaps and the Robot Exclusion Protocol (also known as robots.txt), and the ability to define SEO
properties on pages, including browser title, description, and keywords. This lesson will discuss the new
SEO capabilities in SharePoint 2013, and demonstrate how to configure SEO settings and properties.
Lesson Objectives
After completing this lesson, you will be able to:
Configure custom meta tags and canonical URLs to improve analytics and boost ranking.
Set SEO properties for publishing pages and Managed Navigation terms.
Today, most Internet search engines rely much more heavily on “off page” factors like external link
analysis and click-through statistics to determine rankings. In other words, it is the value of the content on
your site, its popularity with other sites, and prior search click-through activity, that primarily determine
search ranking.
Despite changes in the Internet search ranking process, optimizing your pages for Internet search is still
highly relevant. There are a number of goals that need to be considered for Internet search optimization:
Crawl Frequency and Relevancy. Site contents will not be displayed in organic Internet search results
until the site is crawled and indexed by Internet search engines. The Sitemap and Robot Exclusion
Protocols can help provide guidance to Internet search engines to help ensure a site’s relevant
content can be crawled effectively, and exclude content that is not relevant for Internet search
purposes.
Search Results Formatting. SEO-related meta properties on pages may not be highly relevant for
search ranking, but they are used by many search engines when rendering search results. SEO
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint 2013 Advanced Solutions 8-3
properties on pages provide content authors control over how content links in search results are
displayed.
Crawl Accuracy and Analytics. Two factors that can impact search ranking are related to how
accurately search engines can interpret a site’s navigation and structure and to accurately crawl and
index a site’s content. The more accurately search engines can crawl a site’s structure, the better they
can eliminate indexing errors associated with content duplication, and the more accurately they can
measure click-through analytics to boost popular content.
SharePoint 2013 now supports SEO settings and properties to help meet each of these goals.
Generating Sitemaps
Internet search engines find content on the internet
by crawling domain names, and then by following
hyperlinks to additional content. While it is likely
that search engines will eventually find and crawl
your site’s content, generating and submitting a site
map can help ensure that your content is crawled
more quickly and completely.
Sitemaps are used to provide links and metadata to search engines about pages available on your site for
crawling. In addition to the hyperlink to the content item, additional metadata can be provided, including
the last time the item was updated, topic category, license, and so forth.
Reference Links: SharePoint generates an XML Sitemap by using the Sitemap Protocol that
is supported by most search engines, including Microsoft Bing, Yahoo, and Google. You can find
more information about the Sitemap standard at http://go.microsoft.com/fwlink/?LinkId=320800
SharePoint 2013 now provides native support for auto-generating an XML Sitemap by using the timer job
named Search Engine Sitemap job. A separate instance of this timer job is configured for each web
application in the farm, and by default, is scheduled to run daily. To include a site collection in sitemap
generation requires activating the Search Engine Sitemap feature at the Site Collection level.
The following sample demonstrates how to activate the Search Engine Sitemap feature on a site
collection, and then manually run the related timer job using PowerShell:
Once the timer job has been run, a file named sitemap.xml is written to the root folder of the site
collection top-level site. This file can provide links to multiple XML Sitemap instances. SharePoint 2013
generates separate Sitemap files for standard and mobile views of the site.
MCT USE ONLY. STUDENT USE PROHIBITED
8-4 Developing Optimized Internet Sites
Sample sitemap.xml
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<!--Generated: 2013-07-15T14:40:31-->
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap>
<loc>http://www.contoso.com/sitemap0.xml</loc>
</sitemap>
<sitemap>
<loc>http://www.contoso.com/sitemap_mobile0.xml</loc>
</sitemap>
</sitemapindex>
The actual content of each generated Sitemap.xml file is based on SharePoint search indexing. If your
Sitemap is empty, run a full crawl on the site and then re-run the Search Engine Sitemap job.
The Robot Exclusion Protocol is enabled by placing a file named “robots.txt” in the root folder of a web
site domain and is specific to a domain.
The robots.txt file is typically comprised of two directives:
User-agent. Used to target web crawlers from specific search engines. The default wildcard * indicates
that the following section applies to all robots.
Disallow. Used to provide the partial or full path to the content to exclude. To exclude a directory,
include the trailing / character. For a specific page, include the full URL to the page, including the
page file name and extension, if applicable.
Additional directives can also be included:
Sitemap. Used to provide the full URL to an XML file supporting the Sitemap protocol.
Crawl-delay. Used to specify the number of seconds to wait between crawl requests. Also used to
throttle the load that external crawlers can place on the site.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint 2013 Advanced Solutions 8-5
The following is an example of the default robots.txt file that is generated by SharePoint 2013 when the
Search Engine Optimization feature is enabled on a site:
Disallow: /layouts/
Disallow: /_vti_bin/
Disallow: /_catalogs/
Sitemap: http://www.contoso.com/sitemap.xml
It should be noted that the robots.txt file is purely advisory and may be ignored by malware crawlers that
may be trying to harvest phone numbers or email addresses from your site, or may be looking for security
vulnerabilities.
Additional Reading: You can find additional details and formatting examples at
http://go.microsoft.com/fwlink/?LinkId=320801
SharePoint provides the ability to view and customize the directives that are written to the robots.txt file
from the Search Engine Sitemap Settings found under Site Collection Administration. The value of the
Internet Search Engine Exclusion setting is stored in the property bag of the root web of the Site
Collection with a key of “xmlsitemaprobotstxtpropertyname”. Property bag settings can be viewed by
using Microsoft SharePoint Designer 2013, or can be accessed programmatically.
The following code sample demonstrates how to read and update the Internet Search Engine Exclusion
setting using PowerShell:
Consolidate link popularity with canonical URLs. This setting is used to indicate whether search
crawlers should filter parameters used in page URLs or crawl each combination of parameters as a
unique content item.
The ability to consolidate links is a very important concept for SEO. Web pages often use URL parameters
to provide directives to client or server-side code related to rendering page content. Some URL
parameters influence the content displayed, and some don’t. URL parameters may be used to impact
visual layout (for example, /news.aspx?format=print), or they may be used to filter data results (for
example, /news.aspx?year=2013&month=12).
The problem with these kinds of URL parameters is that search engines have a difficult time
understanding which URL is the best URL to show in search results, particularly if the pages have
significant duplication of content. To address this issue, some search engines now support a Canonical
URL tag that can indicate which URL parameters produce meaningful changes in page content, and which
should be ignored. The tag is inserted as a link reference that indicates the URL of the page to crawl. If the
URL is not the same as the URL of the current item, the crawler will process the link reference as a redirect
and crawl the URL provided as canonical instead. One way to look at these links is that they are similar to
an HTTP 302 redirect, but specific to search crawlers.
The following is an example of the canonical tag that is inserted into the <HEAD> section of a rendered
Publishing Page. The link will include only filtered parameters:
SharePoint 2013 takes care of inserting the correct tag into the site Master Page through the use of a
delegate control. The delegate control must be present in the Master Page in order for this feature to
work correctly. The SharePoint 2013 Site Collection SEO settings provide the ability to specify “Filter link
parameters”, which are the URL parameters that produce a meaningful change to the content rendered.
By entering one or more filter parameters, all other parameters will be ignored and only the specified
parameters will be crawled. SharePoint will then use the specified values to generate and insert the correct
canonical tag into the rendered publishing page.
Note: SEO settings are available only on site collections that have the Publishing
Infrastructure site collection feature enabled. This feature is automatically activated on sites
created from the Publishing Site template.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint 2013 Advanced Solutions 8-7
Property Description
Title The value displayed in the page title area and navigation. This is the
standard Title field found on all content items in SharePoint.
Meta Description A brief description of the page. This value is commonly used as the link
description by Internet search engines.
Sitemap Priority Provides guidance for search crawlers on the relative priority of this page
content. This value is used when generating the XML Sitemap.
Sitemap Change Provides guidance for search crawlers on the anticipated change frequency
Frequency of this page. This value is used when generating the XML Sitemap.
Exclude from Used to advise web crawlers to ignore this page. This value is used to render
Internet Search a <META> tag in the rendered publishing page.
Engines
The location where SEO property values are stored depends on the Navigation Settings of the site. If the
site is using the default Structured Navigation, SEO property values are stored as hidden fields on the
publishing page item. If the site is using the new Managed Navigation introduced in SharePoint 2013, the
values of SEO properties are stored as a set of hidden custom local properties on the Navigation Term
associated with the publishing page.
MCT USE ONLY. STUDENT USE PROHIBITED
8-8 Developing Optimized Internet Sites
In addition to being hidden, each of these columns is sealed and marked to deny deletion. In other words,
these fields should not be modified.
Note: The fields supporting SEO are provisioned by the Search Engine Optimization
feature. You can review the field details by examining the feature located under the SharePoint
root folder at 15\TEMPLATE\FEATURES\SearchEngineOptimization.
Although these fields are hidden, they are available programmatically as columns on any publishing page
item in the Pages library of a publishing site. These settings can be read or modified by using PowerShell,
the server-side object model, or the client-side object model and REST API.
The following code example demonstrates how to open a publishing page item and read the SEO
properties by using PowerShell:
$seoColumns | ForEach-Object {
Write-Host $_ " = " $homePage[$_]
}
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint 2013 Advanced Solutions 8-9
Similar to the hidden columns used for SEO Properties when using Structured Navigation, the properties
are prefixed with “_Sys”, making them hidden. If you access the Navigation Term through the SharePoint
UI, the SEO properties will not be visible to users.
The following code example demonstrates how to access the SEO properties on a Navigation Term by
using PowerShell:
$navTermSet.Terms | ForEach-Object {
MCT USE ONLY. STUDENT USE PROHIBITED
8-10 Developing Optimized Internet Sites
$term = $termSet.GetTerm($_.Id)
Write-Host $term.Name
$seoProps | ForEach-Object {
Write-Host $_ " = " $term.LocalCustomProperties[$_]
}
}
}
}
Demonstration Steps
1. Start the 20489B-LON-SP-08 virtual machine.
7. Enter a selection of sample values for each property, and then click OK.
8. Click the Publish tab from the ribbon menu, and then click Publish.
9. From the Publish dialog box, click Continue.
12. Note that the code is reading column values on page list item that stores SEO properties.
14. Note that the column values match the sample values you entered in a previous step.
17. Click the site actions menu, and then click Edit page.
18. From the Page tab on the ribbon menu, click Edit Properties, and then click Edit SEO Properties.
19. Note that the UI to edit the SEO properties is the same regardless of whether the site is using
Structured or Managed Navigation.
20. Enter a selection of sample values for each property, and click OK.
21. Click the Publish tab from the ribbon menu, and then click Publish.
25. Note that the code is now accessing a NavigationTermSet associated with the site collection, and
reading SEO properties from the NavigationTerm local custom properties collection.
Lesson 2
Optimizing Performance and Scalability
Publishing sites, whether Internet-facing or internal, are generally designed to serve content to a wide and
potentially very large audience. This makes investing in optimizing performance a high priority, both in
terms of providing the best user experience possible across today’s wide array of devices and browsers,
but also to help minimize infrastructure costs for hosting the site and to provide optimal scalability to
meet peak performance demands.
This lesson will explore a variety of techniques that can applied to SharePoint publishing sites and web
content to optimize for client- and server side-performance, and for optimal scalability.
Lesson Objectives
After completing this lesson, you will be able to:
Describe techniques for optimizing the performance and scalability of publishing sites.
Describe how client-side programming can improve the performance of web sites.
Client-Side Programming
Client-side programming is increasingly being used
to enhance the user experience and the
performance of web sites and applications.
JavaScript embedded in web pages provides the
ability to intercept user mouse and keyboard
actions, and process the events locally within the
browser, on the user’s device. If additional data
from the server is required, efficient background
data calls can be performed without requiring the
entire page to be posted back to the server.
Additional Reading: For more information on programming with the SharePoint 2013
REST API, read Get Started with the SharePoint 2013 REST Service on MSDN at
http://go.microsoft.com/fwlink/?LinkId=320805
Additional Reading: For more information on programming with the SharePoint 2013
JavaScript Object Model, read “How to: Complete basic operations using JavaScript library code
in SharePoint 2013” on MSDN at http://go.microsoft.com/fwlink/?LinkId=320804
Minification
Source code files contain a lot of extra content related to formatting. Characters like tabs, line breaks,
block delimiters, and comments make it readable for other programmers, but it also increases the file size,
often considerably. Many computer languages go through a process of compilation to create an
executable file; source code formatting and commenting are ignored by this process, so the extra
characters are of little concern.
The sources for web-based programming languages such as HTML, CSS, and JavaScript, however, are
parsed and processed natively by the web browser as part of rendering page content. Since the HTTP
protocol is a text-based protocol, all of these extra characters (including whitespace) contribute to the
page weight, the number of bytes that have to be downloaded from a web server to the client device to
render a web page.
Minification refers to striping all characters that are not functionally required from source code in order to
minimize the file size. This reduces the time required to download the files to the browser, and
subsequently the amount of time needed for the browser to render the web page to the user. Minification
is most commonly used for JavaScript source files, but it is equally effective for CSS and even static HTML
files.
Minification is typically performed by developers as part of packaging and deploying a website. There are
a variety of web-based and desktop utilities available to developers to support minification, as well as
extensions for popular development studios.
Bundling
It is common for web designers and developers to componentize source files by breaking out CSS and
JavaScript files into many separate files in order to facilitate team-based development, source code
control, and versioning. It is also common to utilize controls and plugins from third-party vendors or
open-source projects (for example, jQuery) that come with their own CSS and/or JavaScript resources.
The result of this practice is that as the number of CSS and JavaScript files increases, so does the load time
of a page. Each static resource linked or referenced from an HTML page generates an additional HTTP
request to a server to download the file. Browsers limit the number of downloads that can be executed at
MCT USE ONLY. STUDENT USE PROHIBITED
8-14 Developing Optimized Internet Sites
one time; the default for most browsers is between two and eight. If the HTML page requires additional
resources, the download requests are queued, and the time to render the page is increased.
Bundling, similar to the process of minification, combines multiple source files into a single file. The result
is that a smaller number of files are linked or referenced from the HTML page, and the browser is required
to perform fewer additional download requests to the server, reducing the bandwidth overhead
associated with each request and reducing the total time to download required resources and to render
the page.
Reference Links: Visual Studio® Web Essentials in an extension for Microsoft Visual Studio
2013 that can perform minification and bundling for CSS and JavaScript files. You can down the
extension from http://go.microsoft.com/fwlink/?LinkId=320806
Caching
SharePoint 2013 provides a number of caching
technologies to help optimize the performance of
publishing sites.
BLOB Cache
The BLOB cache is used for caching large static resources such as images, audio, and video, as well as files
like CSS and JavaScript. Normally, these resources are stored by SharePoint in the content database in SQL
Server®. When a page is rendered for the first time, all of these resources must be retrieved from the
database before being delivered to the client. The BLOB cache is configured and runs on the front-end
web server. By caching these files, which will not change frequently, network traffic with SQL Server is
reduced, and page load times decrease. In addition to the performance benefits, the BLOB cache
integrates with IIS media streaming, which enables large video and audio files to begin playback in the
browser without requiring the entire file to be completely downloaded to the client.
Configuring the BLOB cache requires making changes to the web.config file and is disabled by default
when creating a new SharePoint web application. Since the setting is enabled or disabled for all site
collections within a web application, it should be considered when planning the Information Architecture
for your SharePoint sites.
Location. The cache is stored on disk on the front-end web server. It is recommended that the cache
be placed on a high-performance disk.
Included Files. The files that will be cached are defined by file extension. For publishing sites that
display content that may be changed infrequently, it is recommended to cache as many different file
types as possible.
Size. The size in MB determine how large a cache to support. The default is 10GB and should be sized
roughly 20% larger than the amount of content expected to be cached.
The BLOB cache is also required to support image renditions on publishing sites.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint 2013 Advanced Solutions 8-15
The output cache is an in-memory cache used to store the rendered output of a page. Since the content
displayed on a page may vary based on the permissions of each user, separate versions of pages are
cached for each unique permission set. The utility of the output cache is strongly tied to publishing sites
that support anonymous users, or authenticated users who typically share the same permission set.
The output cache can be configured at the site collection level, or for an entire web application by making
a modification to the web.config file. If the Output cache is configured in the web.config file, it will
override the cache configuration settings at the site collection level for all site collections contained in that
web application.
Object Cache
The object cache is an in-memory cache commonly used by developers to implement caching at a
component level, such as a web part. The object cache is used to store query results for settings, list and
library data views, and page layouts. By reducing the calls to the SQL Server database, the object cache
helps reduce traffic between the web front-end servers and the SQL database servers, and improves the
overall speed at which pages are rendered and delivered to the client.
The object cache requires minimal configuration. The size of the cache can be configured at the site level
or at the web application level.
Additional Reading: For more information, read the Plan for caching and performance in
SharePoint Server 2013 on Microsoft TechNet at http://go.microsoft.com/fwlink/?LinkId=320808
Avoid Scaling. HTML and CSS support scaling an image to display at a resolution greater or smaller
than its native resolution. Scaling an image does not reduce the size of the image that is downloaded
from the server to the browser, even if the image appears to be much smaller than it actually is. It is
common to add high-resolution images to a website that are much larger than necessary. It is always
advisable to resize images to an appropriate size and resolution before they are added to a website.
Note: Image Renditions is a new feature in SharePoint 2013 that resizes images
automatically to a set of pre-determined sizes. We cover this new feature in more depth later in
the lesson.
Web Fonts
The number of fonts supported by HTML across browsers (referred to as web-safe fonts) has always been
quite limited. Web designers wanting to utilize fonts not supported natively by browsers commonly
resorted to rendering styling text as images.
The @font-face feature introduced with CSS3 and HTML5 now supports the ability to download custom
typefaces. Some of the advantages of web fonts include:
Searchable
Dynamically scalable
Similar to images, web fonts have to be downloaded by the browser. Like many features in the HTML5
umbrella of capabilities, there continue to be issues regarding support across devices and browsers, so be
sure to use progressive enhancement techniques when considering web fonts.
The advantage of this technique is that it reduces the number of files that need to be downloaded by the
browser. However, the technique inflates the size of the CSS file considerably. Base64 encoding also adds
about 10% to the size of the original image due to the encoding. It also precludes using separate caching
strategies for images.
Using a data URI can make sense if the images are very small and are only referenced once through a CSS
file.
Image Sprites
An Image sprite is a collection of images that are consolidated into a single image file. Using sprites allows
the browser to download and cache a single file instead of having to make multiple server requests,
minimizing bandwidth and improving page load performance.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint 2013 Advanced Solutions 8-17
Sprites are used in combination with CSS capabilities that allow image references to render only a portion
of an image. The position and dimension of the image to render is controlled by using the height and
width of the <IMG> element combined with the left and top properties of the background element.
The following is an example of how CSS is used with a sprite. In this example, a single sprite image file
contains a collection of 64px x 64px icons. As the user moves the mouse over the search icon, the left
starting position of the background position is shifted 64 pixels:
img.search:hover {
background-position: 64px 0;
}
Sprites are a particularly good choice for collections of images that share a common purpose and size,
such as navigation icons that include variations such as hover transitions, or are themed for different color
selections. When images in a sprite share common dimensions, it makes it easier to calculate the offsets
required when referencing them in CSS.
Since image quality typically degrades when an image is scaled to a higher resolution, most images are
uploaded at a high resolution and then scaled down by the browser when displayed at a lower resolution
(such as a thumbnail). This requires the full-size image to be downloaded to the browser, even though it
may be displayed in a significantly smaller resolution. This can drastically increase bandwidth
requirements and page load times.
Image renditions allow an original source image in SharePoint to be resized to a pre-defined set of
alternative height and width dimensions called a “Rendition”. For example, a site may have three defined
renditions for images used in articles; thumbnail (100px x 100px), newsfeed (220px x 100px), and article
detail (400px x 300px). For image resolutions where the aspect ratio (ratio of height to width) is not
consistent with the original image, authors can crop the portion of the image shown for each rendition
when the page is displayed.
MCT USE ONLY. STUDENT USE PROHIBITED
8-18 Developing Optimized Internet Sites
Somewhat atypically for SharePoint, the configured list of renditions is serialized and stored in a file
located in the Master Page Gallery at
~SiteCollection/_catalogs/masterpage/PublishingImageRenditions.xml.
Working with renditions programmatically is done through the SiteImageRenditions class, which is
contained in the Microsoft.SharePoint.Publishing namespace and assembly.
The following example demonstrates how to retrieve the collection of renditions through PowerShell:
Image renditions are only available on publishing sites, and require configuration of the BLOB cache. If
the BLOB cache is not enabled on the site, the full-size original image will always be used.
Additional Reading: For more information on working with image renditions, read
SharePoint 2013 Design Manager image renditions on MSDN at
http://go.microsoft.com/fwlink/?LinkId=303705
The settings associated with each rendition are stored as a comma-delimited string within the Property
Bag associated with each Image item in the Asset Library where they are stored. The string is comprised of
seven integer values, in the following order:
Rendition Version
Crop X Position
Crop Y Position
Crop Width
Crop Height
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint 2013 Advanced Solutions 8-19
When inserting or editing an image on a page, authors can select from the available renditions through
the SharePoint UI. Each rendition has an associated URL that can be used to link to the image. The
following is an example:
http://www.contoso.com/siteimages/contoso-logo.jpg?RenditionID=1
Each rendition has a unique numeric identifier that is used to select the appropriate rendition.
Alternatively, you can specify the specific height and width of the rendition, and SharePoint will match the
correct rendition if it exists, as follows:
http://www.contoso.com/siteimages/contoso-logo.jpg?Height=100&Width=100
If there are multiple renditions matching the same height and width, SharePoint will select the rendition
with the lowest ID value.
Note: Warning: If the Height and Width specified do not match an existing rendition, the
full-size image will be returned.
Performance. Resources are delivered from servers in closer proximity to the user. Since content
hosted on a CDN is static, they also benefit from aggressive caching strategies.
Reliability. Content delivery networks are most commonly hosted in professionally managed data
centers that provide strong security and high reliability.
File Mirroring. Content is copied between multiple server locations, providing protection from
regional disasters and ensuring high availability.
Scalability. CDNs can scale up quickly to support spikes in demand, and also provide service level
agreements for performance.
The use of a CDN for hosting static resources such as CSS, JavaScript, images, and video for public-facing
websites has become very popular in recent years. In addition to the benefits of listed above, A CDN also
off-loads having to serve static content from an organization’s web servers, which helps to maximize
resources for the generation of dynamic content.
Getting started with the benefits of a CDN is easy. There are a number of public CDNs hosting popular
open-source libraries that you can use right away. For example, the Microsoft Ajax Content Delivery
Network hosted at ajax.aspnetcdn.com hosts popular libraries like jQuery, jQuery UI, jQuery Mobile,
Knockout.js, and Twitter Bootstrap.
MCT USE ONLY. STUDENT USE PROHIBITED
8-20 Developing Optimized Internet Sites
The following example shows how you can link jQuery from your website:
Best Practice: Despite the implied high-availability of CDNs, in recent years there have
been some very public failures that have impacted the business operations of CDN customers. To
protect your site against potential CDN failures, it is a best practice to include fallback scripts to
local resources.
To support your own site-specific resources, you will need to select and sign up for a CDN that provides
hosting services. There are many CDN service providers, including the Microsoft Windows Azure Content
Delivery Network.
Reference Links: You can find out more information on the Windows Azure Content
Delivery Network on MSDN at http://go.microsoft.com/fwlink/?LinkId=205043
Note: In production environments, you should avoid manually editing web.config files,
because it becomes hard to keep changes synchronized across multiple web servers. Instead, you
should use the SPWebConfigModification class to make the changes programmatically,
typically within a feature receiver class. For more information, see How to: Add and Remove
Web.config Settings Programmatically at http://go.microsoft.com/fwlink/?LinkID=311887. The
article was written for SharePoint 2010, but the process is the same in SharePoint 2013.
Demonstration Steps
1. Connect to the 20489B-LON-SP-08 virtual machine.
2. If you are not already logged on, log on to the LONDON machine as CONTOSO\Administrator with
the password Pa$$w0rd.
4. Right-click web.config, point to Open with, and then click Microsoft Visual Studio 2012.
o The location attribute specifies the file system location where files will be cached.
o The path attribute specifies the file types that should be cached, in the form of a regular
expression.
o The maxSize attribute specifies the maximum size of the cache in gigabytes (GB).
o The enabled attribute specifies whether the BLOB cache is enabled.
Note: The BLOB cache is already enabled in the virtual machine to save time during the
demonstration.
11. On the Site Settings page, under Look and Feel, click Image Renditions.
15. In the Height box, type 400, and then click Save.
16. On the Settings menu, click Site contents.
20. In the Site Collection Images – VanGoghStarryNight.jpg dialog box, click Save.
22. On the All Assets page, select the VanGoghStarryNight row (click in the column with a checkmark
header).
Note: Because you are viewing a newly-uploaded image, SharePoint may take
approximately a minute to generate the renditions.
24. Scroll down the page and briefly review how the image appears in each rendition.
27. Drag the image handles to resize the selected area. Notice how the resolution stays the same, at 500 x
400 pixels, but you are effectively zooming in on the selected area.
28. Drag the selected area, and notice how the preview image is updated.
MCT USE ONLY. STUDENT USE PROHIBITED
8-22 Developing Optimized Internet Sites
Note: The key point here is that the dimensions of the rendition do not change; in this case, they
are fixed at 500 x 400 pixels. However, for individual images, you can configure whether to scale the
whole image down to the size of the rendition, or whether to crop the image to size, or a combination of
the two.
Objectives
After completing this lab, you will be able to:
Lab Setup
Estimated Time: 90 minutes
Password: Pa$$w0rd
A warm-up script named WarmUp.ps1 runs automatically when you start the virtual machine. This script
helps to improve the performance of the virtual machine by downloading the home page of the root site
in each site collection on the server. Occasionally this script displays timeout errors; you can ignore these
errors. You should ensure this script has finished running before you start the lab.
You will start by activating Sitemap generation and configuring Search Engine Sitemap Exclusions to
advise web crawlers to ignore the site’s legal notices. Next, you will configure the site to support website
identification for Microsoft Bing, and enable canonical URLs for the sites product catalog pages. Finally,
you will update the SEO properties on the site Welcome Page, and the Managed Navigation terms for
each of the site’s top level navigation landing pages.
8. In the event receiver class, add using statements for the following namespaces:
o System.Text
o Microsoft.SharePoint.Taxonomy
o Microsoft.SharePoint.Publishing.Navigation
Note: When calling the SPSite.RootWeb property, it is a best practice to utilize a using
statement to ensure the object instance is properly disposed of when complete.
For the remainder of this Lab, code should be appended within the using statement curly braces.
11. Within the FeatureActivated method, and within the SPWeb using statement, insert the contents of
the text file at E:\Labfiles\Starter\Snippets\ConfigureSEOSettings.txt.
12. Review the code you just added. The code performs the following tasks:
13. Build your solution and verify that the build completes without errors.
5. In the event receiver class, add using statements for the following namespaces:
o Microsoft.SharePoint.Utilities
o Microsoft.SharePoint.Taxonomy
o Microsoft.SharePoint.Publishing.Navigation
8. Within the FeatureActivated method, and within the SPWeb using statement, insert the contents of
the text file at E:\Labfiles\Starter\Snippets\ConfigureSEOProperties.txt.
9. Review the code you just added. The code performs the following tasks:
10. Build your solution and verify that the build completes without errors.
2. When the Contoso Pharmaceuticals page has finished loading, if you are not already signed in, click
Sign In.
3. Browse to the site collection Features, and activate the following Features:
o Contoso.Website.SEO – Props
o Contoso.Website.SEO – Settings
4. Browse to the search engine optimization settings for the site collection.
5. Verify that the SEO settings include a msvalidate.01 meta tag to validate your ownership of the site.
6. Verify that category is configured as a filter link parameter for canonical URLs.
7. Browse to the search engine sitemap settings for the site collection.
8. Verify that items on the /legal/ path are excluded from indexing by Internet search engines.
9. Browse to the site home page, and then edit the page.
10. From the Page tab on the ribbon menu, click Edit Properties, and then click Edit SEO Properties.
11. Verify that the SEO properties have been updated and are not blank.
12. Click Cancel.
13. From the Page tab on the ribbon menu, click Check In, and then click Discard Check Out.
Results: After completing this lab, the Internet-facing site collection at www.contoso.com configuration
for search engine optimizations should be complete.
MCT USE ONLY. STUDENT USE PROHIBITED
8-26 Developing Optimized Internet Sites
You will start by configuring the BLOB Cache settings, which requires modifying the web.config of a
SharePoint web application through code. Next, you will configure the Page Output cache settings for the
Contoso website site collection. Lastly, you will configure a new image rendition that can be used for
inserting masthead images on the site.
6. In the event receiver class, add a using statements for the Microsoft.SharePoint.Administration
namespace.
7. Uncomment the FeatureActivated method.
8. Within the FeatureActivated method, insert the contents of the text file at
E:\Labfiles\Starter\Snippets\ConfigureBlobCache.txt.
9. Review the code you just added. The code performs the following tasks:
o It modifies the web.config file for the web application to enable the BLOB cache.
10. Build your solution and verify that the build completes without errors.
5. In the event receiver class, add a using statements for the Microsoft.SharePoint.Publishing
namespace.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint 2013 Advanced Solutions 8-27
7. Within the FeatureActivated method, insert the contents of the text file at
E:\Labfiles\Starter\Snippets\ConfigureOutputCache.txt.
8. Review the code you just added. The code performs the following tasks:
9. Build your solution and verify that the build completes without errors.
5. In the event receiver class, add using statements for the following namespaces:
o Microsoft.SharePoint.Publishing
o System.Linq
o System.Linq.Expressions
8. Review the code you just added. The code performs the following tasks:
o It adds the new image rendition to the collection of image renditions on the root web.
9. Build your solution and verify that the build completes without errors.
3. In Visual Studio 2012, open the web.config file for the web application on port 80.
4. Locate the BlobCache element. Verify that the Enabled attribute is set to true and the maxSize
attribute is set to 5.
7. Browse to the page output cache settings for the site collection.
MCT USE ONLY. STUDENT USE PROHIBITED
8-28 Developing Optimized Internet Sites
8. Verify the output cache is enabled, that the Anonymous Cache Profile has been set to Contoso
Anonymous, and that the Authenticated Cache Profile has been set to Disabled.
9. Browse to the image renditions settings for the site, and verify that an image rendition named
Masthead has been added.
Results: After completing this lab, the Internet-facing site collection at www.contoso.com configuration
will be configured for performance optimizations.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint 2013 Advanced Solutions 8-29
Review Question(s)
Question: What is the purpose of the robots.txt file? How is it configured in SharePoint?
Which type of SharePoint cache is targeted at static resources such as image files?
BLOB Cache
Distributed Cache
Session State
Page Cache
Verify the correctness of the statement by placing a mark in the column to the right.
Statement Answer
Which optimization technique describes combining multiple source files into a single file?
Minification
Bundling
Image Renditions
Module 9
Working with Business Connectivity Services
Contents:
Module Overview 9-1
Module Overview
Most organizations store information in a variety of disparate systems. In many cases, these organizations
want to be able to view, interact with, and update information from these disparate systems from a single
interface. This reduces the need for information workers to constantly switch between systems and creates
opportunities for power users or analysts to aggregate data from multiple sources.
Objectives
After completing this module, you will be able to:
Describe the key components of Business Connectivity Services in SharePoint Server 2013.
Create and configure Business Data Catalog (BDC) models by using SharePoint Designer.
Create and configure BDC models by using Microsoft Visual Studio® 2012.
MCT USE ONLY. STUDENT USE PROHIBITED
9-2 Working with Business Connectivity Services
Lesson 1
Business Connectivity Services in SharePoint 2013
In SharePoint 2013, BCS relies on interactions among a variety of components. To create a BCS solution
effectively, you must have a solid understanding of the roles performed by each of these components and
how they work together to provide access to external data. In this lesson, you will learn about the core
components of BCS and how to consume external data.
Lesson Objectives
After completing this lesson you will be able to:
Create external lists that enable you to interact with external data in a similar way to standard
SharePoint list data.
The BDC service application. This service application stores and manages BDC models. BDC model
data is stored in the BDC Metadata Store, and contains information used to access external systems to
execute CRUDQ operations on external content types.
The Secure Store service application. This service application enables you to map SharePoint users to
external system credentials. For example, you could map a group of SharePoint users to a set of
Microsoft SQL® Server credentials that provide access to a specific database.
BDC Runtime
The BDC runtime retrieves information from the BDC Metadata Store and uses that information to
connect to the external system and to execute operations based on the data stored in the BDC Metadata
Store and the request received from a client application. The BDC runtime establishes a connection to the
external data store by using the Connector Framework, and acts as a data access layer between the
external system and the client application.
Connector Framework
The Connector Framework receives requests from the BDC Runtime and manages a connection to the
external system based on the information provided by the BDC runtime. All data filtering and sorting
requested by the client application is done at the connector level, before the data is sent to the client
application. There are four connectors available out-of-the-box that can be used:
.NET Assembly. Uses a custom .NET Assembly created by a developer to access data.
Additional Reading: For more information on the core components of BCS in SharePoint
Server 2013, see Overview of Business Connectivity Services in SharePoint 2013 at
http://go.microsoft.com/fwlink/?LinkId=302076.
A BDC model is portable. You can export it and import it. You can create BDC models for the following
types of data sources:
MCT USE ONLY. STUDENT USE PROHIBITED
9-4 Working with Business Connectivity Services
You can create BDC models interactively in SharePoint Designer for SQL Server databases and WCF web
services. For OData web services and other types of data source, you can use Visual Studio templates to
create and develop the model.
A BDC model contains all the information required to connect to an external source and perform data
operations. A BDC model consists of the following components:
External system. Each BDC model can contain one or more external systems, which are represented by
LobSystem elements in the BDC model file. An external system is a general representation of an
external data source, such as a SQL Server database with specific tables.
System instance. Each external system can include one or more system instances, which are
represented by LobSystemInstance elements in the BDC model file. As the name suggests, a system
instance represents a specific instance of an external system—for example, an instance of your SQL
Server database hosted on a specific server with specific security settings. The system instance
includes connection details, such as the web service endpoint or the SQL Server connection string,
and details of how to authenticate to the external system instance.
Entities. Each external system can include one or more entities, which are represented as external
content types (ECTs).
Note: The BDCMetadata.xsd file used as the schema for BDC models can be found in the
Xml\Schemas folder in the installation folder for Visual Studio, or the TEMPLATE\XML folder In
the SharePoint hive.
Just below the Model element, you will find the AccessControlList element, containing the access
control entries for the BDC model.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 9-5
Edit. Allows users to execute operations that change the data in the external system.
Execute. Allows users to execute, or read, data from the external system.
SetPermissions. Allows users to manage access control entries for the BDC model.
SelectableInClients. Allows users to view external data in client applications that consume the BDC
model.
Below the access control list, you will find the LobSystems element. The LobSystems element contains a
list of LobSystem elements, representing different data connections and containing the necessary
information to connect to the external system.
In the example above, you can see that the external system is a SQL Server database named
ContosoRetailDW hosted on a server named LON-SP1, and that authentication settings are stored in the
Secure Store Service in SharePoint.
MCT USE ONLY. STUDENT USE PROHIBITED
9-6 Working with Business Connectivity Services
The LobSystem element also contains a list of Entity elements, defining each external content type. The
example below contains one entity, or external type, named Employee. There are two methods in the
Employee entity:
In the full contents of the file you would be able to see the actual SQL code used to retrieve both a list of
employees and a single employee.
External content types are usually based on tables or views in a database, on methods in a WCF or OData
service, or on entities in a .NET assembly. Depending on the type of object your ECT is based on, it may
have a limited set of operations. The full list of operations, or methods, that an ECT can have is:
Create. Used to create a new entity in the external system. For instance, in a database table this could
be achieved by using an INSERT statement.
Finder. Used to retrieve a list of entities from the external system. For instance, in a database table this
could be achieved by using a SELECT statement.
SpecificFinder. Used to retrieve a single entity from the external system. For instance in a database
table, this could be achieved by using a SELECT statement with a WHERE clause filtering by the
primary key.
Update. Used to modify an entity in the external system. For instance, in a database table this could
be achieved by using an UPDATE statement.
Delete. Used to delete an entity from the external system. For instance, in a database table, this could
be achieved by using a DELETE statement.
Note: SharePoint Designer uses friendly names for these stereotyped operations. Most
notably, the Finder operation is named ReadList in SharePoint Designer and the SpecificFinder
operation is named ReadItem.
Besides operations, ECTs contains one or more fields. Fields can be compared to columns in a SharePoint
list or database table. Fields are defined as TypeDescriptor elements in the BDC model file, and contain
the following properties:
Name. Name of the field.
RequiredInForms. Boolean property used to specify if the field is to be displayed on edit, update, and
create forms.
ShowInPicker. Boolean property used to specify if the field is to be displayed when end users are
selecting an instance of the ECT in custom list.
MCT USE ONLY. STUDENT USE PROHIBITED
9-8 Working with Business Connectivity Services
ECT Scope
In SharePoint 2010, all external content types created were scoped to the farm. Farm-scoped ECTs are
available for use in any Web Application, site collection, or site within a SharePoint farm. A user must have
sufficient permissions on the BDC metadata store to deploy an external content type.
In SharePoint 2013, ECTs can be scoped to a single app. Apps contain all the resources they need to run in
an isolated area. App-scoped ECTs provide access to external data within a SharePoint app.
OData. Allows connectivity to an OData service. When using an OData service, each ECT is
represented by an OData entity, and data is retrieved by using OData operations.
Custom .NET Assembly. Allows connectivity to custom .NET classes. When using a custom .NET
assembly, ECTs are represented as .NET classes, and accessed by methods created in the assembly.
This type of connection allows access to any data source, as long as the developer is able to create
code in .NET to access the data.
The following code shows an example of a LobSystemInstance element that uses a SQL Server
connection:
The main use of an external system (or LobSystemInstance) is to specify how authentication and
authorization will be performed when connecting to the external data source. Depending on the external
system being accessed, you will need to work together with the external system administrator to
determine how to allow users to access the system while promoting the least privileges principle. You will
either map a group of users of the BCS solution to a single account on the external system, or create a
one-to-one mapping of individual users of the BCS solution and accounts in the external system. The
account information for the external system can be stored and managed by the Secure Store Service. The
Secure store service stores all data related to accounts in an encrypted format in a SQL Server database.
Demonstration Steps
1. Connect to the 20489B-LON-SP-09 virtual machine. If you are not already logged on, log in as
CONTOSO\Administrator with password Pa$$w0rd.
2. On the Start screen, type Visual Studio, and then click Visual Studio 2012.
5. Note the message stating that the BDC Model Designer only supports editing models with a single
.NET LobSystem. The ContosoDW.bdcm file models a SQL Server connection.
6. In the BDC Explorer pane, expand the ContosoDW node.
8. In the Properties pane, in the drop-down list box at the top of the pane, notice that the name
includes the text Model. This indicates that the node represents the top-level Model element of the
BDC model.
10. In the Properties pane, in the drop-down list box at the top of the pane, notice that the name
includes the text LobSystem. This indicates that the node represents the LobSystem element of the
BDC model.
11. In the BDC Explorer pane, expand the second ContosoDW element, and then expand the
LobSystemInstances element.
12. Notice that the model includes a single LobSystemInstance element named ContosoDW. Explain
that this defines properties for a specific instance of an external system, such as connection strings
and authentication settings.
14. Notice that the ECT contains two methods: a ReadItem method and a ReadList method.
17. Briefly review the XML content of the ContosoDW.bdcm file. Try to relate the elements in the XML
file to the structure you explored in the BDC Explorer pane.
ECTs can also be accessed by using one of the following business data web parts:
Business Data Related List. Displays a list of items from an ECT that are related to a parent ECT.
Requires an association.
Business Data Item. Displays a single item from an ECT.
Business Data Item Builder. Creates an ECT item based on parameters from a URL string and provides
it to other Business Data Web Parts.
Business Data Actions. Displays actions for an ECT item.
Business Data Connectivity Filter. Filters the content of a connected Business Data Web Part by using a
list of values from an ECT.
When used in a custom list, an ECT is treated as a column type. When adding an item to the custom list,
users can retrieve a list of entities and view all fields in the ECT that have the ShowInPicker property set
to True in the BDC model.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 9-11
Lesson 2
Creating BDC Models in SharePoint Designer
SharePoint Designer can be used to create and deploy external systems by using connection to a SQL
Server database, WCF Service, or .NET Assembly. Once a data connection is created for the external
system, you can add ECTs and define filters, associations, and permissions.
Lesson Objectives
At the end of this lesson, you will be able to:
WCF Service. WCF Service connections can be used to access data by using a WCF Service. The WCF
Service must implement methods used to execute CRUDQ operations on the data being accessed.
When creating a WCF Service connection, you need to specify the following properties:
o Service Metadata URL. URL used to retrieve the WCF Service metadata.
.NET Type. .NET Type connections are used to access data by using a custom .NET assembly. The
assembly must contain classes defining the different external content types available, and methods
used to execute CRUDQ operations on the data exposed by the assembly. When creating a .NET Type
connection, you need to specify the following property:
MCT USE ONLY. STUDENT USE PROHIBITED
9-12 Working with Business Connectivity Services
o Assembly System. The custom assembly created to expose data. The assembly must be added to
the Global Assembly Cache before you can see it in SharePoint Designer.
Note: .NET Type connections require a custom assembly developed by using Visual Studio.
We will cover the use of Visual Studio later in this module.
The following code example shows how a SQL Server connection is represented in a BDC model file:
Impersonated Windows Identity. This option relies on the Secure Store Service to supply Windows
credentials with which to authenticate to the external system.
Impersonated Custom Identity. This option relies on the Secure Store Service to supply custom
credentials with which to authenticate to the external system.
BDC Identity. This option is also known as RevertToSelf authentication. The BDC runtime uses the
identity of the IIS application pool that runs the BDC service application to authenticate to the
external system.
Every user or account that will invoke calls to external data must have individually assigned
permissions on the back-end system.
Your environment must be configured for Kerberos. In an NTLM environment, the double-hop
limitation will prevent the BDC runtime from impersonating the caller.
In most cases, configuring the Secure Store Service provides a more manageable alternative to using pass-
through authentication.
You can configure a Secure Store target application to use two types of credential mappings:
Individual. The identities of individual SharePoint users are mapped to individual external system
credentials.
Group. The identities of a group of SharePoint users are mapped to a single set of external system
credentials.
In most cases, using a group mapping is the most convenient solution, because you only need to
configure a single set of permissions on the external system. If you need more granular control over
permissions on the external system, or you need to be able to audit access to the external system, you will
need to use an individual mapping instead.
Because of the security risks inherent in using RevertToSelf authentication, you must configure the BDC
service application to support RevertToSelf before you can configure your BDC models to use it.
MCT USE ONLY. STUDENT USE PROHIBITED
9-14 Working with Business Connectivity Services
You can use the following PowerShell commands to enable RevertToSelf authentication in a development
environment:
Operations
There are five operations that can be created for an
external content type. These operations can be
mapped back to methods in a WCF Service or .NET
Type connection, or statements in a SQL Server
connection:
ReadItem. Also referred to as Specific Finder. This operation is used to retrieve a single item from the
ECT based on a key. This is a required operation.
ReadList. Also referred to as Finder. This operation is used to retrieve a list of items from the ECT. This
is a required operation.
Create. This operation is used to create a new instance of an item in the ECT. In SQL Server
connections it maps to a stored procedure or INSERT statement.
Update. This operation is used to modify an existing instance in the ECT.
A ReadList Operation
<Method IsStatic="false" Name="EmployeeReadList">
<Properties>
<Property Name="RdbCommandType"
Type="System.Data.CommandType, System.Data, Version=4.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089">Text</Property>
<Property Name="RdbCommandText"
Type="System.String">SELECT TOP(@EmployeeKey) [EmployeeKey] , [FirstName] ,
[LastName] , [EmailAddress] , [DepartmentName]
FROM [dbo].[Employee] ORDER BY
[EmployeeKey]</Property>
<Property Name="BackEndObjectType" Type="System.String">SqlServerTable</Property>
<Property Name="BackEndObject" Type="System.String">DimEmployee</Property>
<Property Name="Schema" Type="System.String">dbo</Property>
</Properties>
By looking at the RdbCommandText property, you can see the actual SELECT statement used to retrieve
a list of employees from the external system by using a SQL Server connection.
Note: The TOP clause in the sample XML above represents a filter.
Identifiers
Each ECT must have a unique identifier. On SQL Server connections, unique identifiers are usually mapped
to primary keys on a table or view, and are represented in the Entity element as an Identifier child
element.
The following code shows an example Identifier element:
Filters
Filters can be created in the ReadList operation to filter the data brought back from the external system.
There are five types of filter that can be created by using SharePoint Designer:
Comparison. Used to filter data based on a comparison, similar to a WHERE clause in a SQL
statement.
Limit. Used to filter data by specifying the maximum number of rows retrieved from the external
system, similar to a TOP clause in a SQL statement.
Page Number. Used to retrieve a set number of items and provide pagination for an ECT. Also similar
to a TOP clause in a SQL statement. You cannot configure a Limit and a Page Number filter in the
same operation.
Timestamp. Used to retrieve data based on a time field. All items that have a timestamp greater than
the input parameter are retrieved.
Wildcard. Used to retrieve data based on a comparison that may contain wildcards. Similar to a
WHERE clause with a LIKE operator in a SQL statement.
MCT USE ONLY. STUDENT USE PROHIBITED
9-16 Working with Business Connectivity Services
A Limit Filter
<FilterDescriptors>
<FilterDescriptor Type="Limit" FilterField="EmployeeKey" Name="Filter">
<Properties>
<Property Name="UsedForDisambiguation" Type="System.Boolean">false</Property>
<Property Name="IsDefault" Type="System.Boolean">false</Property>
<Property Name="CaseSensitive" Type="System.Boolean">false</Property>
</Properties>
</FilterDescriptor>
</FilterDescriptors>
The following code shows an example of an input parameter for a filter on a ReadList method:
An Input Parameter
<Parameters>
<Parameter Direction="In" Name="@EmployeeKey">
<TypeDescriptor TypeName="System.Int64" AssociatedFilter="Filter" Name="EmployeeKey">
<DefaultValues>
<DefaultValue MethodInstanceName="DimEmployeeReadList"
Type="System.Int64">100</DefaultValue>
</DefaultValues>
</TypeDescriptor>
</Parameter>
Output parameters are usually more complex, since operations are used to retrieve not a single value, but
an individual item that may contain multiple fields or a collection of such items. The XML below shows a
sample output parameter for a ReadList operation:
The following code shows an example of an output parameter for a ReadList operation:
An Output Parameter
<Parameter Direction="Return" Name="EmployeeReadList">
<TypeDescriptor TypeName="System.Data.IDataReader, System.Data, Version=4.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089" IsCollection="true"
Name="DimEmployeeReadList">
<TypeDescriptors>
<TypeDescriptor TypeName="System.Data.IDataRecord, System.Data, Version=4.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089" Name="EmployeeReadListElement">
<TypeDescriptors>
<TypeDescriptor TypeName="System.Int32" ReadOnly="true"
IdentifierName="EmployeeKey" Name="EmployeeKey">
<Properties>
<Property Name="ShowInPicker" Type="System.Boolean">true</Property>
</Properties>
</TypeDescriptor>
<TypeDescriptor TypeName="System.String" Name="FirstName">
<Properties>
<Property Name="Size" Type="System.Int32">50</Property>
<Property Name="RequiredInForms" Type="System.Boolean">true</Property>
<Property Name="ShowInPicker" Type="System.Boolean">true</Property>
</Properties>
<Interpretation>
<NormalizeString FromLOB="NormalizeToNull" ToLOB="NormalizeToEmptyString"
/>
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 9-17
</Interpretation>
</TypeDescriptor>
<TypeDescriptor TypeName="System.String" Name="LastName">
<Properties>
<Property Name="Size" Type="System.Int32">50</Property>
<Property Name="RequiredInForms" Type="System.Boolean">true</Property>
<Property Name="ShowInPicker" Type="System.Boolean">true</Property>
</Properties>
<Interpretation>
<NormalizeString FromLOB="NormalizeToNull" ToLOB="NormalizeToEmptyString"
/>
</Interpretation>
</TypeDescriptor>
<TypeDescriptor TypeName="System.String" Name="EmailAddress">
<Properties>
<Property Name="Size" Type="System.Int32">50</Property>
</Properties>
<Interpretation>
<NormalizeString FromLOB="NormalizeToNull" ToLOB="NormalizeToNull" />
</Interpretation>
</TypeDescriptor>
<TypeDescriptor TypeName="System.String" Name="DepartmentName">
<Properties>
<Property Name="Size" Type="System.Int32">50</Property>
</Properties>
<Interpretation>
<NormalizeString FromLOB="NormalizeToNull" ToLOB="NormalizeToNull" />
</Interpretation>
</TypeDescriptor>
</TypeDescriptors>
</TypeDescriptor>
</TypeDescriptors>
</TypeDescriptor>
</Parameter>
</Parameters>
Associations
Associations can be compared to relationships in a database. They can describe either one-to-many
relationships, or many-to-many relationships. However, many-to-many relationships cannot be created by
using SharePoint Designer; they must be manually added to the BDC model file.
One-to-many associations (or forward associations, or simply associations) are created in SharePoint
Designer from the entity containing the foreign key (or many side of the relationship).
A reverse association is used to navigate from the many side of a one-to-many relationship to the one
side. Reverse associations are rarely used, since they are not needed for navigation in Business Data Web
Parts when an association is already available. Also, reverse associations can only be created by using
stored procedures in a SQL Server connection, or by using a method in a WCF Connection.
A BDC Association
<Association Name="SalesChannelAssociation" Type="AssociationNavigator"
ReturnParameterName="SalesChannelAssociation" DefaultDisplayName="Sales Channel
Association">
<Properties>
<Property Name="ForeignFieldMappings" Type="System.String"><?xml version="1.0"
encoding="utf-16"?>
<ForeignFieldMappings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ForeignFieldMappingsList>
<ForeignFieldMapping ForeignIdentifierName="ChannelKey"
ForeignIdentifierEntityName="Channel"
MCT USE ONLY. STUDENT USE PROHIBITED
9-18 Working with Business Connectivity Services
ForeignIdentifierEntityNamespace="http://sharepoint.contoso.com" FieldName="channelKey"
/>
</ForeignFieldMappingsList>
</ForeignFieldMappings></Property>
</Properties>
<AccessControlList>
<AccessControlEntry Principal="contoso\administrator">
<Right BdcRight="Edit" />
<Right BdcRight="Execute" />
<Right BdcRight="SetPermissions" />
<Right BdcRight="SelectableInClients" />
</AccessControlEntry>
</AccessControlList>
<SourceEntity Namespace="http://sharepoint.contoso.com" Name="Channel" />
<DestinationEntity Namespace="http://sharepoint.contoso.com" Name="Sales" />
</Association>
Note: There will be other elements related to the association in the BDC model file, such as
a method describing the association, and a type descriptor for the association foreign key in the
“many” external content type.
Profile Pages
2. Configure the BCS service to use the site created in step 1 as the profile site.
Actions
External content types can be associated with one or more actions. Actions are links that end users can
click to execute a task that can consume data from an ECT item. Any ECT field or combination of fields
can be used as parameters for the action. For instance, if an external content type contains information
about employees, and one of the fields is the employee’s email address, an action can be used to
compose an email to the employee by using the mailto: protocol and the email address of the employee
as a parameter. Another example would be to open the employee’s profile by using the http: protocol
and the user name as a parameter. Here are some sample actions you can use:
o URL: mailto:{0}
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 9-19
Display map
o URL: http://www.bing.com/maps/?v=2&where={0},{1},{2},{3}
From a SharePoint site. You can add an external list as an app to any SharePoint site, and when doing
so, select the external content type to be used. Once the list is created, you can view and edit the list
settings in the same way that you would manage a regular list. One of the main differences on the
settings for external lists is that you will be able to see and configure any filter created on the external
content type.
Demonstration Steps
1. On the Start screen, type SQL Server Management Studio, and then press Enter.
4. Explain that you are going to use the Administrator account to access the external database, so you
first need to grant the account the required permissions in SQL Server.
5. In the Login Properties - CONTOSO\Administrator dialog box, under Select a page, click User
Mapping.
7. Under Database role membership for: ContosoRetailDW, select db_datareader, and then click
OK.
9. On the Start screen, type Central Administration, and then press Enter.
10. On the Central Administration home page, under Application Management, click Manage service
applications.
11. On the list of service applications, click Contoso Secure Store Service Application.
12. Explain that you are now going to create a secure store target application that you will use to connect
to the external database.
13. On the ribbon, in the Manage Target Applications group, click New.
14. In the Target Application ID box, type ContosoDWApp.
15. In the Display Name box, type Contoso Retail Data Warehouse.
17. In the Target Application Type drop-down list box, click Group, and then click Next.
18. Leave the field names and field types unchanged and click Next.
20. In the Members box, type Everyone, and then click OK.
21. Explain that you have created a group target application that maps all users to a single set of
credentials. You will now set the credentials that the target application will use to connect to the
external database.
24. In the Set Credentials for Secure Store Target Application (Group) dialog box, in the Windows
User Name box, type CONTOSO\Administrator.
25. In the Windows Password and Confirm Windows Password boxes, type Pa$$w0rd, and then click
OK.
27. On the Start screen, type SharePoint Designer, and then press Enter.
29. In the Open Site dialog box, in the Site name box, type http://sharepoint.contoso.com, and then
click Open.
30. If you are prompted for credentials, log in as CONTOSO\Administrator with password Pa$$w0rd.
SharePoint Designer may take some time to open the site.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 9-21
31. When SharePoint Designer has finished loading the site, in the Navigation pane, click External
Content Types.
32. On the ribbon, in the New group, click External Content Type.
33. In the External Content Type Information pane, in the Name row, click New external content
type.
35. In the External System row, click Click here to discover external data sources.
37. In the External Data Source Type Selection dialog box, in the Data Source Type drop-down list
box, click SQL Server, and then click OK.
38. In the SQL Server Connection dialog box, in the Database Server box, type LONDON.
41. In the Secure Store Application ID box, type ContosoDWApp, and then click OK.
42. In the BCS Secure Store : ContosoDWApp dialog, log in as CONTOSO\Administrator with
password Pa$$w0rd.
43. On the Data Source Explorer tab, expand ContosoRetailDW, and then expand Tables.
44. If a dialog box displays the error message Cannot complete refresh, this because BCS does not
support some of the columns in the database. Click OK.
47. On the Parameters page, in the Data Source Elements list, clear ParentAccountKey,
AccountLabel, Operator, CustomMembers, ValueType, CustomMemberOptions, ETLLoadID,
LoadDate, and UpdateDate.
54. On the ribbon, in the Lists & Forms group, click Create Lists & Form.
56. In the Create List and Form for Account dialog box, in the List Name box, type Accounts, and then
click OK.
58. Notice that the External Lists pane now includes a list named Accounts.
60. The final high-level step is to grant users permission to use the external content type you have
created. On the Start screen, type Central Administration, and then press Enter.
61. On the Central Administration home page, under Application Management, click Manage service
applications.
62. On the list of service applications, click the Contoso Business Data Connectivity Service
Application link.
63. On the ribbon, in the Permissions group, click Set Metadata Store Permissions.
64. In the Set Metadata Store Permissions, type Administrator, and then click Add.
65. Under Permissions for CONTOSO\Administrator, select all four permissions.
66. Select Propagate permissions to all BDC Models, External Systems and External Content Types
in the BDC Metadata Store, and then click OK.
68. On the ribbon, in the Permissions group, click Set Object Permissions.
69. In the Set Object Permissions dialog box, type Everyone, and then click Add.
70. Under Permissions for Everyone, select Execute and Selectable In Clients, and then click OK.
71. In the Internet Explorer address bar, type http://sharepoint.contoso.com, and then press Enter.
72. If you are prompted for credentials, log in as CONTOSO\Administrator with password Pa$$w0rd.
73. When the page has finished loading, on the Quick Launch navigation menu, click Accounts.
74. Verify that the Regions list retrieves and displays a set of data from the external database.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 9-23
Lesson 3
Creating BDC Models in Visual Studio 2012
The ease of use of SharePoint Designer makes it a valuable tool for developers and SharePoint power
users. Users can now create external content types without developer knowledge or experience. However,
there are several limitations to SharePoint Designer that can be overcome only by using Visual Studio
2012. OData connections cannot be made by using SharePoint Designer, and any external content type
created in SharePoint Designer is scoped to the entire farm. .NET connector assemblies must also be
created programmatically. To overcome these limitations, you can create ECTs directly in Visual Studio,
and have them deployed to the farm or to a single SharePoint app.
Lesson Objectives
At the end of this lesson, you will be able to:
BDC Method Details Pane. The BDC Method Details Pane is used to define parameters, instances, and
filters for a given method. You can create the following types of methods from the BDC Method
Detail Pane:
o SpecificFinder. Specific Finder, or Read Item, methods are used to retrieve a single instance of the
entity based on its identifier. They contain two parameters:
id. The id parameter is an input parameter used to send the identifier of the instance to be
retrieved.
returnParameter. The return parameter represents the instance of the external content type
being returned by this method. Its data type must be the data type used to define the entity.
MCT USE ONLY. STUDENT USE PROHIBITED
9-24 Working with Business Connectivity Services
o Finder. Finder, or Read List, methods are used to retrieve a list of instances from the external
content type. By default, there is only one parameter for these methods:
returnParameter. The return parameter represents a collection of the external content type
being returned by this method.
Note: You should consider using filters for finder methods to restrict the number of
instances returned by a single operation. You can have multiple instances of this method for
different retrieval operations. For instance, when dealing with an employee content type, you
could have a finder method instance to retrieve all employees, another to retrieve all employees
in a given office, and another to retrieve all employees under a given manager.
Creator Method. Creator methods are used to create a new instance of an external content type. By
default, they contain the following parameters:
o ReturnParameter. The return parameter should use the entity class as its return type.
o newEntity. The new entity parameter should have the same data type as the return parameter.
You need to be sure that if the identifier property of the entity is marked as Read-Only in the
definition of the data type in the BDC Designer, you mark the identifier in this method as NOT
read-only.
Updater Method. Updater methods are used to modify the properties of a given instance of the
external content type. They contain a single parameter:
o Entity. The entity parameter must be of the same data type as the entity definition, and must
have its identifier set to NOT read-only.
Deleter Method. Deleter methods are used to delete an instance of the external content type. They
contain a single parameter:
o Identifier. The identifier parameter is an input parameter that represents the unique identifier of
the instance to be deleted.
BDC Explorer. The BDC Explorer displays a hierarchical view of the model, with all its entities,
methods, and properties.
To create a BDC model and an external content type by using the BDC Model Designer, execute the
following steps:
1. Create a new empty SharePoint Solution in Visual Studio 2012.
2. Add a new item of type Business Data Connectivity Model (Farm Solution only) to the empty
project.
3. In Solution Explorer, rename the Entity1.cs file to the name of the entity you want to create. An
entity represents an external content type.
4. In the renamed file, define the properties of the new entity. Properties represent fields in your
external content type.
5. In BDC Explorer, rename the Entity1 entity to the name of the entity being created, and rename its
identifier to the name of the property in the new entity that will be used for an identifier.
6. In BDC Explorer, rename the parameters for the ReadItem and ReadList methods to map back to the
properties of your new entity.
7. In the BDC Method Details pane, create any other necessary operations, such as Creator, Deleter, and
Updater.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 9-25
8. If necessary, fix the parameters for the new methods in BDC Explorer.
9. Right-click an operation in BDC Explorer and click View Code to view the method created for the
operation.
OData is a standard used to expose data from any data source such as a database by using an URL, thus
allowing for a simplified way to connect to data sources within a network.
OData uses HTTP, Atom, and JavaScript Object Notation (JSON) to empower developers to create
solutions that communicate with any data source. SharePoint uses a new OData connector to allow
communication by using the OData protocol.
BCS can use the OData connector to expose OData data sources as external content types without having
to write any code, other than the OData service itself.
2. Right-click the project, in the Add submenu click Content Types for an External Data Source, and
then follow the wizard to add an OData connection and entities.
Once entities have been added by using the OData connector, you can view their XML definition by right-
clicking the .ect file created for the entity, clicking Open With, and then selecting the XML Editor.
The following code shows an example association created automatically by the OData connector:
Additional Reading: For more information on how to convert an app-scoped BDC model
to farm-scoped model, see How to: Convert an app-scoped external content type to tenant-scoped
at http://go.microsoft.com/fwlink/?LinkId=321942.
Security Credentials
BCS supports authentication to OData services by using one of the following authentication modes:
PassThrough. Pass-through authentication is used to pass the credentials of the user accessing the
external content type to the OData service. Pass-through authentication cannot be used in
environments where two-factor authentication is used, since it can only pass the username and
password to the OData service. Consider using pass-through for testing environments.
RevertToSelf. Revert-to-self authentication uses the credentials of the application pool used to run
SharePoint for authentication.
Digest Credentials. Digest credentials are not stored in the Secure Store Service. Digest Credentials are
composed of username and password, and use the Message Digest encryption algorithm to secure
the user information while on the network.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 9-27
Credentials. You can use credentials authentication for custom identities. A custom identity might
contain several pieces of information, such as username, password, and application id. You can store
custom identity information in the Secure Store Service in the same manner as Windows credentials.
Custom Authentication using OData Extension Provider. You can also create your own custom
extension provider by inheriting from the ODataExtensionProvider and implementing you own
code for authentication.
The XML segments below show the authentication settings for an OData service used by a BDC Model.
The following code shows example authentication settings for an OData-based BDC model:
<LobSystemInstance Name="ContosoODataSource">
<Properties>
<Property Name="ODataServiceUrl"
Type="System.String">http://services.odata.org/Northwind/Northwind.svc</Property>
<Property Name="ODataServiceAuthenticationMode"
Type="System.String">PassThrough</Property>
<Property Name="ODataFormat" Type="System.String">application/atom+xml</Property>
<Property Name="HttpHeaderSetAcceptLanguage" Type="System.Boolean">true</Property>
</Properties>
</LobSystemInstance>
The first segment shows the authentication and connection settings used to retrieve the OData service
metadata. The second segment contains the settings to access the actual service.
If you need to manually create a new list instance for an app-scoped external data type, you must add a
new list instance to your project and change its elements.xml file manually by using the following
properties:
LobSystemInstance. Name of the Lob system instance defined in the BDC Model file. If you created
the data source by using the OData connector, this is the name of the data source you created.
EntityNamespace. Namespace for the entity. This information is retrieved from the OData metadata.
You can also get the namespace by opening the associated .ect file for the external content type in
the XML editor and looking for the Name attribute in the Model element.
Entity. Name of the external content type.
SpecificFinder. Name of the method used as a specific finder. You can also find this information in the
associated .ect file for the external content type.
MetadataCatalogFileName. Name of the BDC Model file. The auto-generated name in Visual Studio is
BDCMetadata.bdcm. You can find this information in the elements.xml file for the OData data
source.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 9-29
Default.aspx. You can customize the Default.aspx for the app to use app parts to display the contents
of the external list.
User navigation. Users can navigate to the external lists by changing the URL in their browser, using
the Quick Launch menu, or navigating to the list from the contents of the site.
MCT USE ONLY. STUDENT USE PROHIBITED
9-30 Working with Business Connectivity Services
Your task is to create a farm-scoped BDC Model to access data from the ContosoRetailDW database. You
will deploy the BDC model and test the model by creating sample pages to display a list of regions with a
corresponding list of customers.
In addition, managers want to enable better overview of the product inventory in selected parts of the
business. The IT department has developed an OData web service to expose parts of the database that are
used for inventory management. You will develop an App that includes a second BDC model, by using the
OData web service, that enables users to interact with the inventory management system through external
lists in SharePoint. The IT department will distribute the App to relevant departments within the business.
Objectives
In this lab, you will be able to:
Lab Setup
Estimated Time: 90 minutes
Virtual Machine: 20489B-LON-SP-09
Password: Pa$$w0rd
A warm-up script named WarmUp.ps1 runs automatically when you start the virtual machine. This script
helps to improve the performance of the virtual machine by downloading the home page of the root site
in each site collection on the server. Occasionally this script displays timeout errors; you can ignore these
errors. You should ensure this script has finished running before you start the lab.
1. Configure SQL Server and the Secure Store Service to Manage Authentication for BCS
5. Create an Association
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 9-31
Task 1: Configure SQL Server and the Secure Store Service to Manage Authentication
for BCS
1. Use SQL Server Management Studio to map the CONTOSO\Administrator user to the
ContosoRetailDW database with the db_datareader permission.
3. Use the Central Administration web site to create a new Secure Store Target Application with the
following properties:
Property Value
Application ID ContosoDWGeographyApp
4. Set the credentials for the ContosoDWGeographyApp target application to use the username
CONTOSO\Administrator, with the password Pa$$w0rd.
o Name: Geography
5. Use the DimGeography table in the database to create all operations for the Geography ECT. You
should use all elements as parameters, except ETLLoadID, LoadDate and UpdateDate. You should
map the GeographyKey element to the identifier, and you should include the following properties in
the picker:
o ContinentName
o CityName
MCT USE ONLY. STUDENT USE PROHIBITED
9-32 Working with Business Connectivity Services
o StateProvinceName
o RegionCountryName
7. Use the Central Administration web site to grant all permissions on the metadata store for the
Geography ECT to members of the CONTOSO\Domain Admins security group.
8. Grant the Execute and Selectable in clients permissions on the Geography object to the Everyone
security group.
9. Use Internet Explorer to browse to the http://sharepoint.contoso.com site, and then view the
Regions list. Verify that SharePoint displays data from the database correctly.
o Name: ByCountry
o Type: Comparison
o Operator: Equals
o Name: Customer
o Connection: ContosoRetailDWConnection
3. Select the DimCustomer table from the database, and then create the ReadItem operation for the
Customer ECT by using the following parameters:
o Name: ReadCustomer
o Identifier: CustomerKey
4. Create the ReadList operation for the Customer ECT by using the following parameters:
o Name: ReadCustomers
6. View the new external list, and verify that the list displays customer data.
7. Close Internet Explorer.
Name: CustomerGeographyNavigation
Return parameters:
o CustomerKey
o GeographyKey
o Title
o FirstName
o LastName
o EmailAddress
5. On the CustomersByCountry page, add a Business Data List web part by using the following
parameters:
o Type: Geography
6. Filter the contents of the list to show only regions in the Australia.
7. Add a Business Data Related List web part by using the following parameters:
o ECT: Customer
10. View the list of customers in Bendigo (click the double-arrow icon next to GeographyKey 425).
Results: After this exercise, you should have created two external content types named Geography and
Customer, exposed their data by using external lists and business data web parts.
2. In the ContosoODataWebServcice.svc file, review the InitializeService method. Notice that this
method exposes the DimProducts, DimProductCategories and DimProductSubcategories entities.
These map to the DimProduct, DimProductCategory and DimProductSubcategory database
tables.
3. Start the solution without debugging. You should leave this service running because you will use it in
the following tasks.
o Locations: E:\Labfiles\Starter
2. Configure the new app to use http://dev.contoso.com for debugging, and to deploy the app as a
SharePoint-Hosted app.
o Name: ContosoODataSource
o DimProductSubcategories
o DimProducts
6. Explore the DimProducts external content type. Note that the content type includes an association
between the DimProducts and DimProductSubcategories entities.
9. Review the Elements.xml file that defines the DimProducts list. Notice that the file defines a
connection to the external OData source.
3. Review the properties for the product with a ProductKey with the value 1.
4. Change the description for the product to New description.
7. In the ContosoRetailDW database, in the dbo.DimProduct table, view the top 1,000 rows. Verify
that the ProductDescription for row 1 has been updated to New description.
Results: After this exercise, you should have created two app-scoped external content types named
Product and Category by using an OData connection.
Question: You need to create an external content type to expose data from a SQL Server
database. The content type must be used in multiple Web Applications within your
SharePoint farm. What type of external content type would you create? What tool would you
use to create the ECT with the least amount of coding effort?
Question: You need to create an external content type to expose data from a custom data
source. The custom data source uses a binary file format documented by the developers who
created it. What tools would you use to create the ECT?
Question: You need to create an external content type to expose data from an OData
service created by another developer. What type of ECT would you create?
MCT USE ONLY. STUDENT USE PROHIBITED
9-36 Working with Business Connectivity Services
Module 10
Creating Advanced Business Data Connectivity Models
Contents:
Module Overview 10-1
Module Overview
Out-of-the-box search connectors provide many features that enable you to index common sources such
as file shares, Microsoft® SharePoint® sites, and web sites. However, there are many times when you
must index a non-common source such as a proprietary database or an in-house custom data store with
proprietary interfaces. When you are faced with these situations, it is important to know the tools that
SharePoint Business Connectivity Services (BCS) offers to index these complex sources of structured and
unstructured data. This module will explore how to create custom search connectors by using several
methodologies. You also will be shown the advanced SharePoint 2013 external event notification feature
that supports SharePoint list features such as alerts and event receivers when external data changes.
Objectives
After completing this module, you will be able to:
Lesson 1
Configuring BDC Models for Search
In this lesson, you will learn to extend SharePoint Search to index external data sources by using BDC
models. You will also learn to implement best practices when it comes to multi-part items such as security,
metadata, and file stream indexing.
Lesson Objectives
After completing this lesson, you will be able to:
Content Crawling. Content is indexed by SharePoint by using a connector, and search queries are
presented from the SharePoint search servers. This allows you to base the results on relevance-
ranking models, define how and when the content is indexed, and back up the index results locally.
SharePoint indexing connectors are implemented by using protocol handlers or Business Connectivity
Services connectors. These indexing connectors know how to connect, what to crawl, and how to crawl a
remote source. BCS connectors allow SharePoint to connect to any number of external systems and to
utilize those systems in several different ways throughout SharePoint sites. By using BCS to index external
data, users can submit search queries against that indexed data through the SharePoint Search APIs. BCS
provides several types of connectors for connecting to these external data sources, including simple
database connectivity, WCF, .NET, and Custom.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 10-3
Connector Components
Each connector is made up of two major components, these include:
BDC Model file. This file defines the structure of the data, the operations that need to be called, and
the connection information.
Connector Code. This is the main part of the Connector. This code fetches the remote data and
remotes it back to the search crawler for processing by the content processing components
As you learned in other modules, BCS utilizes the concept of a metadata store to hold the BDC model file,
or definition, of the external data source. As a review, these metadata models have the following major
pieces of information:
Entity information. The structure of the data; for example, the columns in the table of a database.
Operations. The methods used to access entity information, such as database SQL statements or the
web methods in a web service.
Note: In earlier versions of SharePoint, the task of extending search capabilities was done
by using protocol handlers built mainly in C++.
Connector Design
There are four important pieces of information that each BCS connector must have. They are:
Connectivity. The connector must define how to get to the content. This can be via basic TCP/IP or file
system operations. When implementing a TCP/IP protocol, you must know the specific application
level data formats (such as HTTP, FTP, SMTP, simple sockets, and so forth). You should implement the
connectivity by using best practices and that you don’t have any unhandled exceptions that will
prevent the crawler from processing all the content. This layer will also implement any security that is
required to authenticate to the target source.
Structure of repository. After you have connected to a content source, you can navigate the content
that is in that source. You can list the containers (such as folders) and the items in those containers
(such as files).
Incremental crawls. When crawling external sources, your connector should be intelligent enough to
determine when items have changed and when they have not. This can optimize the time it takes to
index the external data.
Securing data. How you read and apply security information to a set of crawled items when pulling
from a custom external source.
Tools
There are several tools provided by Microsoft to create BDC models that use custom connectors. The tools
include SharePoint Designer and Visual Studio. SharePoint Designer can be used to create the BDC model
based on several different types of connectors, including database, WCF, and .NET. SharePoint Designer
has limited functionality and does not provide the ability to implement custom logic for the methods; you
MCT USE ONLY. STUDENT USE PROHIBITED
10-4 Creating Advanced Business Data Connectivity Models
can only do this through Visual Studio. You can use SharePoint Designer to export models, which you can
then import into a BCS service application by using the Central Administration web site.
Enhancements in 2013
Several enhancements were made to the connector framework in 2013, including:
IdEnumerator. This method returns all items that exist in the target data source.
ChangedIdEnumerator. This method will tell the search crawler which items have changed and must
be re-indexed. It is optional but highly recommended that you implement this method.
DeletedIdEnumerator. This method will tell the search crawler what items have been deleted and must
be re-indexed. It is optional to implement.
BinarySecurityDescriptorAccessor. This method is responsible for building the security information for
an item. This information is then used to hide items in the search results to which the user does not
have access.
StreamAccessor. This downloads the binary of the content that must be indexed. Most commonly, this
would the file binary.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 10-5
OutputUriProcessor. Used to generate the URLs that will be given to items indexed by a custom
connector.
SystemUtilityTypeName. This property is used to point to the custom class and assembly that will
implement a custom connector.
Title. Specifies the title of the external content type to display in search results.
DefaultLocale. Used to specific the language. Can be overridden by the LCIDField or CultureField
properties.
RootFinder. Applied to a method to support search (required unless you implement search by using
an IDEnumerator).
WindowsSecurityDescriptorField. Used to tell search which field in the returned crawled properties
contains the ACL information.
AuthorField. Used to tell search what crawled property is the author field.
DisplayUriField. Used to tell search what crawled property is the URL that users will click in a search
result.
LCIDField. Used to tell search what crawled property will determine the language the item is in.
Extension. The file name extension for the crawlable stream, the default is .txt.
MimeType. Used to tell search what type of file the binary stream is. This overrides the Extension
property.
SynchronizationCookie. Used to tell the external content source what time the last crawl was
completed for use in the ChangedIdEnumerator and DeletedIDEnumerator.
MCT USE ONLY. STUDENT USE PROHIBITED
10-6 Creating Advanced Business Data Connectivity Models
Note: In order for your BDC model to show up for use in Search Service Applications, you
must set at least the ShowInSearchUI property. You should also provide either the RootFinder
property or implement an IDEnumerator method.
PassThrough
RevertToSelf
WindowsCredentials
Credentials
RDBCredentials
DigestCredentials
When the target system is using NTLM, you can choose to use PassThrough authentication for crawling. If
the target external application uses Windows authentication, then PassThrough is often the most
appropriate authentication option. However, profile pages may require you to use the Secure Store to get
login information because of the double hop problem. When this occurs, you should create two
LobSystemInstance instances. The first instance should be set up to use the Secure Store Credentials,
and the second one should be set up to use PassThrough. By setting the PassThrough method and the
ShowInSearchUI property, the search crawler will use the second instance. This property should be set at
the LobSystemInstance level and not at the LobSystem level.
The external system supports NTLM Access Control via Active Directory usernames and passwords.
The external system has its own username and password scheme.
In external systems that support NTLM via security descriptors, this is a relatively easy task by using the
WindowsSecurityDescriptorField. By using this field, you are telling the crawler which crawled property
contains the security information. Because the security information can get very large, caching will be
disabled any time you set this property.
Another option is to use a method that describes how to get the security information for a particular item.
This is called the BinarySecurityDescriptorAccessor method. This method would need to return an array
of bytes with the security information that needs to be added to the index. This is used for external
systems that do not support NTLM and need to have external users mapped to domain accounts and
ACLs.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 10-7
return secDes;
}
Once the data has been indexed and the security information included, only users that have access to the
items will see them in the search results.
Do not enumerate more than 100,000 items per call to the external system. You should utilize some
type of windowing or foldering scheme to balance out the items you are retrieving each time.
Try not to use too much memory. It is easy to store items in memory for quick retrieval, but use this
approach judiciously to avoid excessive resource consumption.
Note: The SharePoint Search Crawler will expect items to be returned within two minutes. If
it does not receive any items in that period, it will cancel the crawl.
MCT USE ONLY. STUDENT USE PROHIBITED
10-8 Creating Advanced Business Data Connectivity Models
UseClientCachingForSearch Property
This property can be used to cache items during the enumeration phase, which can improve incremental
crawl speeds. You should not use this property if your items are over 30KB in size, which could lead to
cache misses and eliminate performance gains.
Demonstration Steps
1. Start the 20489B-LON-SP-10 virtual machine.
7. Find the IdEnumerator, GetProductSecurity and GetProductFile methods in the model and in the
code.
Lesson 2
Developing Custom Connectivity Components
In this lesson you will build upon your knowledge of the BDC search methods to explore specific ways to
build search connectors. You will learn the advantages and disadvantages of the different connector
types, which will help you to better understand which one will support your business requirements. You
will also learn some basic troubleshooting and debugging skills when working with search connectors.
Lesson Objectives
After completing this lesson, you will be able to:
.NET BCS Connector. A custom repository connector that requires both a BDC model and a .NET
component. Both must implement the required operations.
Custom BCS Connector. A custom repository connector similar to a .NET BCS connector but defined
by the ISystemUtility interface in the code. As an example, the Exchange Public Folder indexing
feature of SharePoint utilizes a custom BCS Connector.
Database Connector
This connector type is the more simple type of connector to utilize when working with SQL Server sources.
This simplicity is driven by the fact that the end user tool SharePoint Designer has wizard support to help
you build a model without writing any code. When working with more advanced models, you can also use
Visual Studio to make the necessary changes to support those advanced requirements with wizard-based
support. In addition to supporting SQL Server, it is also possible to make calls to other database platforms
by using basic database access providers.
MCT USE ONLY. STUDENT USE PROHIBITED
10-10 Creating Advanced Business Data Connectivity Models
WCF Connector
A second approach to connecting to external systems it to build a WCF service that wraps the entities you
want to expose. The advantage to using this type of connector is that you can build a simple contract
interface that will never change, yet be able to make changes to the underlying code without having to
deploy any assemblies or cause down time in your SharePoint farm. A drawback is that all of the items
you are interfacing with must be serializable to be passed over the wire. When working with WCF,
SharePoint Designer is the preferred tool because it has the simpler wizards to do the BDC model design.
It is possible to do this in Visual Studio, but much more tedious.
.NET Connector
When using this approach, BCS will connect to a .NET assembly for the implementation logic. This
assembly will be deployed to the SharePoint servers and BCS will execute it when a crawl is needed. The
assembly is typically created by using Visual Studio, using the Business Data Connectivity Model project
template. This template has a set of visual designers and code-management features that make creating
the connector very simple. In terms of authentication, you must implement all authentication to the
external system inside the connector. It is also possible to utilize the Secure Store to retrieve username
and password credentials and to utilize the BDC Username and Password filters. Unlike the WCF
connector, your .NET connector can take advantage of non-serializable types.
3. Define class methods that map to the stereotyped operations. This step is the same as any type of
model you would build, and the class method name and parameters should match exactly.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 10-11
ISystemUtility
IConnectionManager
ITypeReflector
IAdminsitrableSystem
ISystemPropertyValidator
MCT USE ONLY. STUDENT USE PROHIBITED
10-12 Creating Advanced Business Data Connectivity Models
When a user submits a BDC operation, the Execute method of the ISystemUtility class is called. The
biggest advantage to using a custom connector is its ability to be changed in case the backend logic must
be changed. Since a .NET connector contains the logic in the assembly, any time a change must be made,
the assembly must be recompiled and redeployed.
The following code example shows a BDC model LobSystem element that specifies a custom connector
type:
Major Differences
In addition to the deployment differences, there are other significant changes that one must consider.
These include:
You can utilize any of the security authentication methods provided by BCS in your custom
connector. This is in contrast to being forced to use PassThrough in a .NET connector.
No tooling support via Visual Studio or SharePoint Designer for custom connectors.
Custom connectors are the recommended approach for implementing a connector for frequently
changing back-end interfaces.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 10-13
Store the credentials in an external source (non-SharePoint). You could save the credentials in an
external database and retrieve them via your code. There are no real drawbacks to this approach if
everything is designed properly
Store the credentials in SharePoint Secure Store. Since most service application and features in
SharePoint rely on this service, it may be better to utilize it in your search connector as well. This
requires you to make the call to the Secure Store and retrieve the credentials. This means that you
need to know the application id from which you want to retrieve the credentials.
If you decide to implement the Secure Store approach, you will need to specify in your code or in the BDC
model file which AppId has the credential you are looking for. The best approach is to put this AppId in
the BDC model file and then make the call to the secure store. In order to interrogate the BDC model
properties, you must implement the IContextProperty interface.
Match parameter names. Parameter names are case sensitive; make sure that your BDC model and
.NET assembly method signatures match.
Handle exceptions. In most cases (update operations are okay) it is not appropriate for an exception to
be passed to BDC. If something does not work, simply return a null value.
MCT USE ONLY. STUDENT USE PROHIBITED
10-14 Creating Advanced Business Data Connectivity Models
Crawl log shows two success messages and no errors. You didn’t specify a RootFinder in your BDC
model.
The model does not show up as available in the New Content Source page. You didn’t specify the
ShowInSearchUI property in your model.
An error displays about the database response being throttled. A typical BDC model will limit the
number of items to be returned before it will error. This is configured at the proxy level by using
Windows PowerShell.
Item ID is indexed, but no metadata is displayed. You have placed the UseClientCachingForSearch on
the IdEnumerator and Finder methods.
Error message doesn’t change even though you updated the model and code. Make sure that you
change the version number on the entity so that SharePoint knows something changed. You may
need to restart the Search Service to be certain that the old version is replaced correctly with the new
version.
Cannot see fields in the update and insert forms. Confirm that you have placed the UpdaterField and
CreaterField attributes on each TypeDescriptior that you want to display.
You get an identifier error when you attempt to update an item. Set all return identifiers to
ReadOnly=”true”.
The following code example shows how to disable throttling for BDC queries:
iisreset
These errors will display in the Crawl log in the Search Service Application. These are high-level errors, and
if you want to learn more about what has occurred you can utilize the ULS logs to find the BDC error. It is
best if you set the log level to Verbose to get all the stack trace log data.
Utilize the ULSView.exe tool to sort based on the mssdmn.exe process in real time. This can help you
diagnose what may be occurring in your connector. You can also connect to this process by using Visual
Studio to debug and step through your connector code.
MCT USE ONLY. STUDENT USE PROHIBITED
10-16 Creating Advanced Business Data Connectivity Models
Lesson 3
Working with External Events and Notifications
In the lesson you will learn to enable external lists to support event receivers. This process involves adding
special stereotyped operations to support subscriptions in SharePoint and in the external system. This also
means you must learn the basic elements needed to support subscriptions in the external system. This
lesson will provide you with the knowledge you need to design, implement, and troubleshoot these new
features in SharePoint 2013.
Lesson Objectives
After completing this lesson, you will be able to:
Remote Event Receivers. These allow SharePoint to make a call out to external sources when an event
occurs on a list in SharePoint.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 10-17
Polling\Notification Service
If you choose not to send the notifications in real time, you can have a polling service monitor for changes
in the external source and then have it send the changes to SharePoint. This can be done in any number
of ways, but the most common way is a Windows service.
LobSubscriptionId
EntityName
EntityNamespace
LsiName
ForwarderType
CallbackUrl
MCT USE ONLY. STUDENT USE PROHIBITED
10-18 Creating Advanced Business Data Connectivity Models
NotificationContext
EntityEventType
In order to activate the feature, you can activate the hidden BCSEvents feature via Windows PowerShell,
server-side object model, or the client-side object model. When activating this feature, it will make a call
to a feature event receiver that in turn activates the ExternalSubscriptions feature, which is not hidden and
will display in the SharePoint site’s settings page.
In order to create subscriptions and external event notification, you must create a hidden subscription list
via a feature:
clientContext.load(features);
clientContext.load(eventingFeature);
var onEventingFeatureActivated = function () {
alert("eventing feature activated");
};
clientContext.executeQueryAsync(Function.createDelegate(this,
onEventingFeatureActivated));
}
Once this list has been created, any calls to the Subscribe and Unsubscribe methods of the BDC model
will record the subscription in this hidden list.
IsOnBehalfOfField. This field will pass in the user data that requested the subscription.
When implementing these methods, the choice of your BDC model data is important. When utilizing
OData feeds, the set of properties you will use will be considerably different than if you were simply
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 10-19
connected to a simple database. You can see examples of the differences between the two in the
following code snippets. What you will see is that the database model is considerably easier to utilize,
since it is using only stored procedures. When working with the OData model, you must implement
several extra different properties, including:
ODataEntityUrl. The target URL directory (the prefix of the URL is taken from the LobSystemInstance)
of where the request should be sent. This will change based on if you are doing a POST or a GET
ODataPayloadKind. The type of ATOM body that should be sent; this is typically set to Entry or
Parameter.
ODataFormat. This is the Content-Type header that gets sent to your OData service.
ODataServiceOperation. A boolean to indicate if the endpoint is a basic WCF service operation or not.
In each example, you will see that a set of parameters is passed to the target, with the two most important
being the DeliveryAddress and the EventType. The DeliveryAddress is the SharePoint endpoint that will
contain a subscription ID that is recorded in a hidden list in the SharePoint site. When a post is received to
this endpoint, the subscription ID must exist in the list, or you will receive an HTTP 404 error. The event
type is used to designate if the event is an addition, modification, or a deletion. The enumerations are as
follows:
Addition = 1
Modification = 2
Deletion = 3
As a return parameter to the two different examples below, you will notice that you must pass back the
external systems subscription ID. This is later used for when a user wishes to remove an alert or the system
removes an event handler. When one of these actions occurs, SharePoint must send a request to the
external system with the subscription ID that the external system should delete.
The following code example illustrates the Subscribe and Unsubscribe methods for a database model:
<MethodInstances>
<MethodInstance Type="EventUnsubscriber" Name="Unsubscribe"
DefaultDisplayName="UnSubscriber">
<Properties>
<Property Name="LastDesignedOfficeItemType"
Type="System.String">None</Property>
</Properties>
</MethodInstance>
</MethodInstances>
</Method>
The following code example illustrates the Subscribe and Unsubscribe methods for an OData model:
<DefaultValue MethodInstanceName="SubscribeCustomer"
Type="System.String">*</DefaultValue>
</DefaultValues>
</TypeDescriptor>
</Parameter>
<Parameter Direction="Return" Name="SubscribeReturn">
<TypeDescriptor Name="SubscriptionId" TypeName="System.String" >
<Properties>
<Property Name="SubscriptionIdName"
Type="System.String">SubscriptionId</Property>
</Properties>
</TypeDescriptor>
</Parameter>
</Parameters>
<MethodInstances>
<MethodInstance Type="EventSubscriber"
ReturnParameterName="SubscribeReturn" ReturnTypeDescriptorPath="SubscriptionId"
Default="true" Name="SubscribeCustomer" DefaultDisplayName="Customer Subscribe">
<AccessControlList>
<AccessControlEntry Principal="NT Authority\Authenticated Users">
<Right BdcRight="Edit" />
<Right BdcRight="Execute" />
<Right BdcRight="SetPermissions" />
<Right BdcRight="SelectableInClients" />
</AccessControlEntry>
</AccessControlList>
</MethodInstance>
</MethodInstances>
</Method>
<Method Name="UnSubscribeCustomer" DefaultDisplayName="Customer Unsubscribe">
<Properties>
<Property Name="ODataEntityUrl"
Type="System.String">/UnSubscribe?ID='@ID'</Property>
<Property Name="ODataHttpMethod" Type="System.String">GET</Property>
<Property Name="ODataPayloadKind"
Type="System.String">Property</Property>
<Property Name="ODataServiceOperation"
Type="System.Boolean">false</Property>
</Properties>
<AccessControlList>
<AccessControlEntry Principal="NT Authority\Authenticated Users">
<Right BdcRight="Edit" />
<Right BdcRight="Execute" />
<Right BdcRight="SetPermissions" />
<Right BdcRight="SelectableInClients" />
</AccessControlEntry>
</AccessControlList>
<Parameters>
<Parameter Name="@ID" Direction="In">
<TypeDescriptor Name="ID" TypeName="System.Int32">
<Properties>
<Property Name="SubscriptionIdName"
Type="System.String">ID</Property>
</Properties>
<Interpretation>
<ConvertType LOBType="System.Int32" BDCType="System.String" />
</Interpretation>
</TypeDescriptor>
</Parameter>
</Parameters>
<MethodInstances>
<MethodInstance Name="UnSubscribeExpenseReport"
DefaultDisplayName="ExpenseReport
Unsubscribe" Type="EventUnsubscriber" Default="true">
<AccessControlList>
<AccessControlEntry Principal="NT Authority\Authenticated Users">
<Right BdcRight="Edit" />
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 10-23
Notification Parsers
When the external system needs to report information about a change back to SharePoint, the format
must be very specific. There are two out-of-the-box formats that you can implement. They are:
IdentityParser. Accepts an Atom message with a set of identities in the message body.
Custom. A notification parser that you build that must inherit from NotificationParser class.
If you do not specify a content parser in your BDC method signature then the default will be
IdentityParser. If you want to customize the message format then you can also implement a custom
parser using the NotificationParser abstract class. To specify which parser you want to implement you
add the NotificationParserType entry to the model method.
The following code example shows a NotificationParserType entry:
When using the Identity parser, you must have a message that has a valid XPath to the identity values.
The valid XPath is /a:feed/a:entry/a:content/m:properties/b:BcsItemIdentity. When using the
ODataEntryContentNotificationParser, the valid XPath is /a:entry/a:link/m:inline/a:entry.
When using the default Identity parser, you should send a response formatted with a simple set of
identities passed in the xml:
xmlns:d=""http://schemas.microsoft.com/ado/2007/08/dataservices""
xmlns:m=""http://schemas.microsoft.com/ado/2007/08/dataservices/metadata""
xmlns:b=""http://schemas.microsoft.com/bcs/2012/""
xmlns=""http://www.w3.org/2005/Atom"">
<entry>
<title type=""text"">Customers</title>
<id>http://www.northwind.com/customers</id>
<author>
<name>External System</name>
</author>
<content type=""application/xml"">
<m:properties>
<b:BcsItemIdentity m:type=""Edm.String""><CustomerID>{0}</CustomerID></b:BcsItemIdentity>
<d:Name>Customer</d:Name>
</m:properties>
</content>
</entry>
</feed>
MCT USE ONLY. STUDENT USE PROHIBITED
10-24 Creating Advanced Business Data Connectivity Models
";
Initiating Subscriptions
Once you have set up both SharePoint and the
external system to support notification events, users
can create subscriptions. A subscription can be
created by clicking a button that has custom code,
creating an alert, some kind of code that adds an
event handler to an external list, or a workflow that
wants to listen for events on an external list. The
entire flow of the subscription process is:
6. LOB saves the subscription and sends back the subscription ID to SharePoint.
Note: A common mistake when doing development with subscriptions is that you may not
see the Alerts button in the ribbon on an external list. This is because you have not set up
outgoing email at the Farm level, and therefore the alert button will not display on any lists.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 10-25
Subscriptions must be created (explicitly or implicitly) in order to receive external notification events:
You should be aware that you can have multiple subscriptions for the same event, yet for different
individuals. You should plan accordingly to be sure that your external system can support sending several
hundreds or thousands of notifications within small windows.
Because the architecture of the notification feature is abstracted from the main SharePoint UIs, all features
will work, including alerts and workflows. The biggest difference is the ExternalNotificationMessage
property of the SPItemEventProperties class. This message is of type ReadOnlyCollection<byte>, and
any data received from the external event will be present in this property. This is a UTF8 encoding string
that can be converted back to the message by passing in the property as a byte array to the
Encoding.UTF8.GetString method.
Note: When creating an event receiver, you must create an assembly and deploy it to the
GAC of each server in the SharePoint farm. This is best done with a SharePoint Farm solution.
The following code example illustrates how to add an event receiver to an external list:
string msg =
Encoding.UTF8.GetString(properties.ExternalNotificationMessage.ToArray());
}
}
Demonstration Steps
Note: These instructions include all of the steps required to complete the demonstration.
The instructor may complete some of these steps before the students begin the demonstration.
5. In Solution Explorer, notice that the solution has five projects. The ExternalListEventReceiver project
is an event receiver that will interrogate an external message and should be placed on an external list.
The NorthwindApp project is a SharePoint App that deploys a BDC OData Model and has a default
page that has a button to subscribe to events and enable the required features. The
NorthwindService project is the OData project that exposes the back-end database as an OData
feed. It has also been extended to have subscription methods. The NotificationTesting project
allows you to send a response to the SharePoint endpoint for event testing. The PollingService
project is a Windows service that will poll for changes in the database and then send events to
SharePoint based on those changes.
7. Right-click NorthwindService, point to Debug, and then click Start new instance.
Explain that this deploys the OData service used by the BDC model.
8. On the Windows Start page, type SharePoint, and then click SharePoint 2013 Central
Administration.
15. On the BDC Model was successfully imported page, click OK.
16. Select the NorthwindModel check box.
17. On the ribbon, in the Permissions section, click Set Object Permissions.
18. In the Set Object Permissions dialog box, in the People Picker box, type administrator, and then
click Add.
19. Under Permissions for CONTOSO\administrator, select all the check boxes, and then click OK.
22. On the ribbon, in the Permissions section, click Set Object Permissions.
23. In the Set Object Permissions dialog box, in the People Picker box, type administrator, and then
click Add.
24. Under Permissions for CONTOSO\administrator, select all the check boxes, and then click OK.
25. Open a new browser tab. In the address bar, type http://team.contoso.com, and then press Enter.
29. In the Adding External List dialog box, in the Name box, type Customer.
30. In the External Content Type box, click Select External Content Type.
31. In the External Content Type Picker dialog box, click Northwind, and then click OK.
33. On the Site Contents page, click the Customer link. It should display data from the OData feed,
which is in turn coming from the database.
36. Right-click the first line of the Subscribe method, point to Breakpoint, and then click Insert
Breakpoint.
37. On the Windows Start page, type SQL, and then click SQL Server Management Studio.
39. In Object Explorer, expand Databases, expand Northwind, and then expand Tables.
40. Right-click dbo.EntitySubscribe, click Select Top 1000 Rows. Notice that there are no rows in the
table.
MCT USE ONLY. STUDENT USE PROHIBITED
10-28 Creating Advanced Business Data Connectivity Models
41. On the Windows Start page, type SharePoint, right-click SharePoint 2013 Management Shell, and
then click Run as administrator.
42. At the command prompt, type E:\Democode\SetupeventReceiver.ps1, and then press Enter.
Monitor Visual Studio for the breakpoint to be hit. Highlight the method variables to see that the
values were sent from SharePoint.
44. Switch back to SQL Server Management Studio, click Execute to refresh the table rows. You should
now see one row. Notice the DeliveryURL address.
45. Switch back to Visual Studio, in the NotificationTesting project, double-click Program.cs. Notice
how it simply gets the latest delivery address and then sends an http post to that address. Notice also
that the message that is sent is an Atom Feed.
47. In the Attach to Process dialog box, select the Show processes from all users check box.
48. Select all the w3wp.exe processes, and then click Attach.
49. In the Attach Security Warning dialog box, click Attach.
54. In the Attach to Process dialog box, click the OWSTIMER.exe process, and then click Attach.
57. Right-click the following line of code, point to Breakpoint, and then click Insert Breakpoint:
base.ItemAdded(properties);
58. In Solution Explorer, right-click NotificationTesting, point to Debug, and then click Start new
instance. When the break point gets hit in your event receiver, SharePoint has successfully received
the message.
64. On the ribbon, in the View section, in the list, click BDC Models.
Contoso has a subsidiary company called Northwind that would like to use the Contoso SharePoint Farm
to index their product data. They have asked you as the Contoso Senior SharePoint Developer to help
them architect and build a solution. The basic requirements are that the users would like to be able to
search on product data from multiple data sources using SharePoint Search and be able to update that
data using SharePoint interfaces. The product data is spread across two separate databases. They have
asked you to present all the data in the two databases as a single item in the search results and in an
external list. You have been tasked with using BCS Search Connector framework to accomplish this
business requirement.
Objectives
After completing this lab, you will be able to:
Lab Setup
Estimated Time: 90 minutes
Password: Pa$$w0rd
A warm-up script named WarmUp.ps1 runs automatically when you start the virtual machine. This script
helps to improve the performance of the virtual machine by downloading the home page of the root site
in each site collection on the server. Occasionally this script displays timeout errors; you can ignore these
errors. You should ensure this script has finished running before you start the lab.
2. If you are not already logged on, log on to the LONDON machine as CONTOSO\Administrator with
password Pa$$w0rd.
3. In Visual Studio create a new project named NorthwindModel. You should use the following
properties to create the project:
Property Value
Location E:\Labfiles\Starter
2. In the Product entity class, add the following code to define the properties:
2. Complete the implementation of the ReadList method based on the properties of the Product class.
5. In the Insert File dialog box, browse to E:\Labfiles\Starter, and in the file extension list, click Text
Files (*.txt).
7. Review the method definitions you have just added to the model.
o C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Microsoft.Office.SecureStoreService\v4.0_15.0.0.
0__71e9bce111e9429c\Microsoft.Office.SecureStoreService.dll.
o C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Microsoft.Office.SecureStoreService.Server.Securi
ty\v4.0_15.0.0.0__71e9bce111e9429c\Microsoft.Office.SecureStoreService.Server.Security.dll.
o System.Web.
2. Add using statements for the following namespaces (you can find a copy of these using statements in
the E:\Labfiles\Starter\UsingStatements.txt file):
o System.Data
o System.Data.SqlClient
o System.IO
o System.Runtime.InteropServices
o System.Security
o System.Security.AccessControl
o System.Security.Principal
o Microsoft.Office.SecureStoreService.Server
o Microsoft.BusinessData.Infrastructure.SecureStore
o Microsoft.BusinessData.Infrastructure.SecureStore
o Microsoft.BusinessData.SystemSpecific
o Microsoft.BusinessData.Runtime
o Microsoft.BusinessData.MetadataModel
o Microsoft.SharePoint
o Microsoft.BusinessData.MetadataModel.Collections
9. Review the code you have just added to the code file.
2. Declare a public static variable named username of type string. Initialize the variable to an empty
string.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 10-33
3. Declare a public static variable named password of type string. Initialize the variable to an empty
string.
4. Add properties to the class to implement the IContextProperty interface. You should implement the
properties by automatic properties.
5. In the ProductService class, after the last of the property declarations, press Enter.
7. In the Insert File dialog box, browse to E:\Labfiles\Starter, and in the file extension list, click Text
Files (*.txt).
8. Click SecureStoreCode.txt, and then click Open.
10. Use the Central Administration web site to create a new Secure Store Application called Northwind
with the following properties:
Property Value
11. Set the credentials for the Northwind application to use the username sqluser, and the password
Pa$$w0rd.
12. In Visual Studio in the NorthwindModel.bdcm file, in the LobSystemInstances element, add a
LobSystemInstance element with a Name attribute with the value NorthwindModel.
14. Add a child Property element with the value Northwind, and the following attributes:
Attribute Value
Name AppId
Type System.String
2. Add a new property to the ReadItem Method, with the name RootFinder, and the value Empty.
2. Configure Visual Studio to always force installation of the Feature1 Feature when the solution is
deployed.
4. Use the Central Administration web site to verify that the NorthwindModel Feature1 farm-scoped
Feature is active.
5. Use Windows PowerShell to deploy the search connector assembly. You can find the commands in
the E:\Labfiles\Starter\DeploySearchConnector.ps1 file.
6. Use the Central Administration web site to grant permissions on the Product external content type.
You should grant the CONTOSO\Domain Users security group the Edit, Execute, Selectable in
Clients, and Set Permissions permissions. You should propagate permissions to all methods of the
content type.
Note: If you discover an error after deploying the search connector, you must retract the
solution by using Visual Studio, and then restart IIS before you can re-deploy the solution. If you
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 10-35
do not restart IIS after the retraction, SharePoint will use the previous version of the assembly and
you will get unexpected results.
Task 2: Test the .NET Connectivity Solution by Using a BCS Web Part
1. Browse to the team site located at http://team.contoso.com.
3. On the new page, add a Business Data List web part to the page.
4. Configure the Business Data List web part to use the NorthwindModel.NorthwindModel.Product
external content type.
Property Value
Name Product
Property Value
Name Test
RetailPrice 26.50
QuantityPerUnit 12
Manufacturer Contoso
4. Verify that the new product has been added to the list (you will need to use the paging controls, as
the item will have been added to the end of the list).
2. Create a new search content source named Northwind. Configure the content source to crawl the
NorthwindModel external data source.
MCT USE ONLY. STUDENT USE PROHIBITED
10-36 Creating Advanced Business Data Connectivity Models
3. Start a full crawl of the Northwind content source. Wait for the crawl to complete before you
continue.
4. View the crawl log for the Northwind content source. The log should indicate that more than 80
items have been crawled. Many items will have returned a warning, and some items might have
returned an error. You should not have more than five errors, but you may have a lot of warnings.
Question: What is the most important thing to double check when building your entity
model methods and your entity class methods?
Question: What is the reason for having multiple methods that retrieve information about
single items such as metadata, security, and file contents?
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 10-37
Review Question(s)
Test Your Knowledge
Question
IdEnumerator
EventSubscriber
Finder
SpecificFinder
StreamAccessor
MCT USE ONLY. STUDENT USE PROHIBITED
10-38 Creating Advanced Business Data Connectivity Models
.NET Connector
Custom Connector
WCF Connector
COM Connector
Database Connector
Verify the correctness of the statement by placing a mark in the column to the right.
Statement Answer
Verify the correctness of the statement by placing a mark in the column to the right.
Statement Answer
Module 11
Working with Business Data
Contents:
Module Overview 11-1
Module Overview
In this module we will explore how Business Connectivity Services (BCS) integrates with other Microsoft®
SharePoint® front-end features such as external lists, external columns, and workflows. After looking at
how SharePoint out-of-box features work with BCS, you will learn how to integrate your own applications
with BCS solutions by using the various programming APIs provided. Additionally, we will look at how
Microsoft Office clients interact with BCS solutions and how that interaction is architected.
Objectives
After completing this module, you will be able to:
Utilize the various APIs available, such as CSOM, JSOM, and REST.
Lesson 1
Working with Business Data in Composite Solutions
In this lesson you will learn how SharePoint UI features interact with BCS solutions. One of the first things
you will explore is how to create external lists to leverage the same look and feel as native lists in
SharePoint, and to understand the differences between external lists and native lists. In addition, you will
see how native lists can utilize BCS data by using Business Data columns. Finally, you will learn how to
work with BCS data by using SharePoint 2010 and 2013 workflows.
Lesson Objectives
After completing this lesson, you will be able to:
From a SharePoint site. You can add an external list as an app to any SharePoint site by using the add
an app link on the Site Contents page.
External lists provide several advantages for both developers and users. For example, external lists are:
Easy to implement. Users can create an external list without the need for custom code.
Easy to use. Users can work with external lists in the same manner that they interact with regular lists
in SharePoint.
Easy to access from server-side code. Developers can access external lists by using the SPList class.
Easy to access from client-side code. Developers can access external lists by using the CSOM and REST
API.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 11-3
You can resolve these limitations in various ways. The first is to be sure to create the proper Associator
methods between entities. This can provided a more enhanced experience for the users. But in addition to
creating the Associator, you must also be sure that you designate a “Title” column so the user sees a
meaningful selection rather than a number (“Alaska” instead of “1”). The second option is to de-normalize
the data in your back-end to something that can be easily consumed by SharePoint and users. The
process of de-normalization involves collapsing all the reference columns into their respective values.
Finally, another option is to create a custom InfoPath form that shows the user what options they have to
select before submitting the data to SharePoint.
You should also be aware that Business Connectivity Services is limited by the number of items it will
retrieve from the external system. By default, this limit is 2,000.
The following code example shows how you can use PowerShell to change the BDC throttling limits:
Note: There are third-party ISVs that build synchronization tools that can bring data into
native SharePoint lists, which enables you to take advantage of SharePoint features for external
data.
MCT USE ONLY. STUDENT USE PROHIBITED
11-4 Working with Business Data
For comprehensive information on the differences between native and external lists, please see:
Business Data Related List. Displays a list of items from an ECT that are related to a parent ECT.
Requires an association be created in the BDC model.
Business Data Item Builder. Creates an ECT item based on parameters from a URL string, and provides
it to other Business Data Web Parts.
Business Data Actions. Displays actions for an ECT item.
Business Data Connectivity Filter. Filters the content of a connected Business Data Web Part by using a
list of values from an ECT.
Each business data web part relies on the BDC model containing the supporting stereotyped methods. For
example:
Combining Business Data models with external lists and business data web parts provides some very
interesting no-code solution possibilities. Some examples include:
Display product data. You use the Business Data List to show products and their prices on a sales
representative’s support site.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 11-5
Implement master-child relationships. You can create a customer orders page that displays a list of
customers by using the Business Data List web part. You can then connect that web part to the
Business Data Related List web part to display a set of orders for a selected customer
Entity Profile pages. You can create a CRM system that uses the primary key of the customer on an
ECT profile page to add a Business Data Item web part, but then also add custom web parts that do
other look ups to back-end data on the same page. All customer data can be put in one place for
employees in order to increase customer satisfaction when calling in to inquire about the status of
their account. Similarly, you can create a product page that shows all details of a product
Search. Search will utilize profile pages that contain the Business Data Item web part to display
custom data when users click on the search result.
The following code example shows how to define Business Data Actions in the BDC model by using an
Actions element:
When you enable an entity profile page, the default action will be set to the profile page URL. This is
required for when you integrate search results with your BCS solutions.
MCT USE ONLY. STUDENT USE PROHIBITED
11-6 Working with Business Data
Links are formed by taking the columns defined in the entity and arranging them in a meaningful way.
Some examples of using Business Data Actions include:
Redirect a user to search for a commonly used property of an entity by using SharePoint search or an
external search provider such as Bing.
Business Data Actions travel with the entity no matter where it is displayed. For example, Business Data
Actions are accessible from both Business Data Web Parts and Business Data Columns.
Note: Although a similar solution can be achieved with Managed Metadata columns, the
external system may be the system of record for the values and is more frequently updated.
When adding an item to the custom list, users will be able to retrieve a list of entities and view all fields in
the ECT that have the ShowInPicker property set to True in the BDC model.
To add an external column to any list in SharePoint, execute the following steps:
2. From the LIST ribbon, in the Settings group, click List Settings.
3. From the List Settings page, under Columns, click Create column.
4. From the Create Column page, in the Column name text box, type the name of the column to be
created.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 11-7
6. To the right of the External Content Type text box, click the Select External Content Type button.
7. In the External Content Type Picker dialog box, select the ECT to use, and then click OK.
8. In the Select the field to be shown in this column drop-down list, select the field to be displayed in
the list, and then click OK.
Once you have created a business data column, you can then create items in a list by using values from
the ECT.
Demonstration Steps
1. Open a File Explorer window and browse to E:\Democode\NorthwindService.
2. Right-click NorthwindService.sln, point to Open with, and then click Microsoft Visual Studio
2012.
3. Press F5 to start the service. This is an example OData service that provides data from a back-end
database.
4. Without closing Microsoft Visual Studio® or Internet Explorer, return to the Start screen, type Central
Administration, and then press Enter.
5. On the Central Administration home page, under Application Management, click Manage service
applications.
8. On the Add Action page, in the Action Name box, type Search Company.
Note: You can also use external URLs in ECT actions. However, in a classroom environment
the virtual machine is not connected to an external network.
10. Under Launch the action in a new Web browser window (applies to External Data Web Parts
only), click Yes.
12. Under Parameter Property, in the drop-down list box, click CompanyName.
17. In the Adding External List dialog box, in the Name box, type Customers.
18. Under External Content Type, click the Select External Content Type icon.
19. In the External Content Type Picker dialog box, click Customers, and then click OK.
22. Verify that the Customers page displays several rows of data.
23. In any row, click the ellipsis, and then click Search Company.
24. Verify that Internet Explorer opens a new tab that displays a page named Search, where the search
text is the company name of the item you selected.
Note: The Search page will not display any results because the search service is not
configured on this virtual machine.
25. Close the Internet Explorer tab that contains the Search page.
28. In the Adding Custom List dialog box, type CustomerExt, and then click Create.
32. Under The type of information in this column is, click External Data.
33. Under External Content Type, click the Select External Content Type icon.
34. In the External Content Type Picker dialog box, click Customers, and then click OK.
35. Under Select the Field to be shown on this column, in the drop-down list box, click CustomerID.
36. Under Add a column to show each of these additional fields, select CompanyName and
ContactName.
40. Next to the CustomerID box, click the Select External Item(s) icon.
41. In the Choose Customers dialog box, click ALFKI, and then click OK.
43. Verify that the external list displays data in the TestZ, TestZ: CompanyName, and TestZ: Maria
Anders columns.
If you choose to use the BDC Identity, you will need to enable the Business Connectivity Service
Application to support the RevertToSelf method.
The following code example shows how you can use PowerShell to configure Business Connectivity
Services to use RevertToSelf authentication:
Note: Using RevertToSelf authentication is not a best practice. The application pool
account used for most application pools will have a high level of privileges. These privileges
include being able to write farm configuration settings that most users should never be allowed
to have.
Using RevertToSelf authentication is not a best practice. The application pool account used for most
application pools will have a high level of privileges. These privileges include being able to write farm
configuration settings that most users should never be allowed to have.
To reiterate, even if you place the activities inside a workflow Impersonation step, the actual work will be
done via a service account or the Secure Store Identity. The user running the workflow will never have
their credentials passed to the external service.
Here are some helpful hints when working with workflows and business data:
Creating an item in a workflow must use the identity that is returned to later make changes to the
item.
Only the fields defined in the SpecificFinder method will be displayed in SharePoint Designer.
When you build Visual Studio workflows, you will utilize the Server or Client object model to interact with
external lists. These APIs are discussed in the next lesson.
Demonstration Steps
1. Open a File Explorer window and browse to E:\Democode\NorthwindService.
2. Right-click NorthwindService.sln, point to Open with, and then click Microsoft Visual Studio
2012.
3. Press F5 to start the service. Explain that you have started an example OData service that provides
data from a backend database.
4. Without closing Visual Studio or Internet Explorer, open a new Internet Explorer window and browse
to http://team.contoso.com.
7. Point out that the first row of the list contains a CustomerID value of ALFKI, and that this
corresponds to a CompanyName value of Alfreds Futterkiste.
8. Close the current Internet Explorer window only.
9. On the Start screen, type SharePoint Designer, and then press Enter.
12. On the ribbon, click List Workflow. Point out that the Customers external list is not listed because
you cannot create list workflows for external lists.
14. In the Create Site Workflow dialog box, in the Name box, type External List Workflow.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 11-11
Note: This demonstration uses SharePoint 2010 workflow mode for simplicity, because
using SharePoint 2013 workflow requires additional configuration that would place additional
load on the virtual machine. In a SharePoint 2013 workflow, you would use the Call Web Service
activity to interact with the external list through the REST API.
16. On the ribbon, in the Insert group, on the Action drop-down menu, click Set Workflow Variable.
17. Click workflow variable, and then click Create a new variable.
18. In the Edit Variable dialog box, in the Name box, type CompanyName.
19. In the Type drop-down list box, click String, and then click OK.
21. In the Lookup for String dialog box, in the Data source drop-down list box, click Customers.
22. In the Field from source drop-down list box, click CompanyName.
23. In the Field drop-down list box, click CustomerID.
24. In the Value box, type ALFKI, and then click OK.
27. On the ribbon, on the Action drop-down menu, click Log to History List.
30. In the Field from source drop-down list box, click Variable: CompanyName, and then click OK.
32. Under Start Options, ensure Allow this workflow to be manually started is selected.
38. When the workflow has finished running, under My Completed Workflows, click External List
Workflow.
39. Point out that the Description column contains the value Alfreds Futterkiste. This is the company
name that corresponds to the customer ID you provided.
Lesson 2
Working with Business Data in Custom Solutions
Business Data can be accessed in several different ways. This plethora of different APIs enable your custom
applications to access back-end data and use it in ways other than as an external list, business data
column, or composite application. As with many other features of SharePoint, you can interact with
business data by using any of the standard APIs. In this lesson, you will learn how to use both server-side
and client-side code to interact with business data.
Lesson Objectives
At the end of this lesson, you will be able to:
Build applications that utilize the Server, Client, JavaScript, and REST APIs.
Learn to use the SPList class and its methods to interact with external lists.
Server-side object model (OM). A set of .NET assemblies that must be run on a SharePoint server.
Client-side object model (CSOM). A set of .NET assemblies that can be run on any .NET-supported
platform.
JavaScript Object Model (JSOM). A set of JS libraries that you can use from SharePoint applications to
interact with your ECTs.
REST API (REST). An HTTP-based API callable from any platform supporting HTTP.
When comparing the features available among external lists, business data web parts, and custom-built
applications using the various BDC APIs, only the BDC APIs give you full access to the capabilities that
BDC offers. For more information on the capabilities of the BDC APIs, see:
As you may have guessed, the applications you can build by using the BDC APIs are almost endless.
One of the biggest reasons the Client side object model and REST APIs exist is because you are not
allowed to deploy BCS solutions that have any supporting code (such as custom and .NET connectors) in
Office 365™. Additionally, you cannot deploy applications that utilize the server object model to Office
365. The only supported BDC models in Office 365 are solutions that use WCF service end points or
OData. Because of the unpredictability of the external data, currently Office 365 does not allow you to
index these BDC models.
You should keep these limitations in mind if you are considering developing BCS solutions and moving
from on-premise to Microsoft cloud-based solutions in the future.
Microsoft.SharePoint.Administration;
Microsoft.SharePoint.BusinessData.*;
You can create Business Data Models by using the server side object model:
LobSystemInstance adventureWorksLobSystemInstance =
adventureWorksLobSystem.LobSystemInstances.Create(
"AdventureWorks", true);
}
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 11-15
In addition to programmatically creating a model, you can deploy your pre-defined models by using
server-side object model.
try
{
// Get the model.
strXmlData2Import = File.ReadAllText(strXmlFile);
int iNumOfNoncriticalErrors =
strarrNoncriticalErrors.Length;
if (iNumOfNoncriticalErrors > 0)
{
Console.WriteLine("Noncritical Errors");
for (int iCtr = 0;
iCtr < iNumOfNoncriticalErrors;
iCtr++)
{
Console.WriteLine(
strarrNoncriticalErrors[iCtr]);
}
MCT USE ONLY. STUDENT USE PROHIBITED
11-16 Working with Business Data
In addition to deploying BDC models, you can also work with them directly via the server object model.
This includes calling any of the stereotyped methods (such as the CRUD methods).
As part of the object model, you also have access to various helper methods such as the CreateDataTable
method that automatically populates a DataTable object with the query results from a Finder method.
Below are several examples of how to call various methods, but not all instances are included. To learn
more about how to make calls to all types of stereotyped methods from server side code, see:
Code Snippets: Executing Methods Using the BDC Runtime Object Model
http://go.microsoft.com/fwlink/?LinkId=327906
Retrieving BDC Entities can also be achieved using the server object model:
Code that Gets a Specific Customer Entity by Using the SpecificFinder Method of a BDC Model
return instance;
}
You can call the creator method in your models from server side code:
Example of How to Call a Creator Method to Create a New Entity in the External System
service.GetDatabaseBackedMetadataCatalog(
SPServiceContext.Current);
IEntity entity =
catalog.GetEntity(nameSpace, entityName);
ILobSystemInstance LobSysteminstance =
entity.GetLobSystem().
GetLobSystemInstances()[0].Value;
fieldValueDictionary["CustomerID"] = "JDOE";
fieldValueDictionary["FirstName"] = "John";
fieldValueDictionary["LastName"] = "Doe";
fieldValueDictionary["ModifiedDate"] = DateTime.Now;
Identity id = entity.Create(fieldValueDictionary,
LobSysteminstance);
}
}
}
IMetadataCatalog catalog =
service.GetDatabaseBackedMetadataCatalog(
SPServiceContext.Current);
ILobSystemInstance LobSysteminstance =
entity.GetLobSystem().
GetLobSystemInstances()[0].Value;
IEntityInstanceEnumerator ientityInstanceEnumerator =
entity.FindFiltered(methodInstance.GetFilters(),
LobSysteminstance);
MCT USE ONLY. STUDENT USE PROHIBITED
11-18 Working with Business Data
while (ientityInstanceEnumerator.MoveNext())
{
foreach (IField field in fieldCollection)
{
Console.Write(
ientityInstanceEnumerator.
Current[field.Name].ToString().PadRight(20));
}
Console.WriteLine();
}
}
Console.ReadKey();
}
Finder methods can allow you to find entities based on a set of filer parameters:
if (!string.IsNullOrEmpty(customerId))
{
WildcardFilter filter = (WildcardFilter)filters[0];
filter.Value = customerId;
}
IEntityInstanceEnumerator enumerator =
entity.FindFiltered(filters, lobSystemInstance);
return entity.Catalog.Helper.CreateDataTable(enumerator);
}
You can make calls to the Association methods by using the Server Object Model:
return entity.Catalog.Helper.CreateDataTable(associatedInstances);
}
IMethodInstance method =
entityInstance.Entity.GetMethodInstances(MethodInstanceType.SpecificFinder)[0].Value;
ITypeDescriptorCollection oDescriptors =
method.GetReturnTypeDescriptor().GetChildTypeDescriptors()[0].GetChildTypeDescriptors();
listItem.UpdateOverwriteVersion();
MCT USE ONLY. STUDENT USE PROHIBITED
11-20 Working with Business Data
Microsoft.SharePoint.Client.Runtime.dll
Microsoft.SharePoint.Client.dll
For a complete look at all the available classes and methods available in the BDC CSOM, see:
You can retrieve a reference to an external content type by using the GetEntity method:
An Example Code Segment Used to Retrieve an Entity Definition Called Product From a SharePoint
Site
ClientContext ctx = new ClientContext("http://team.contoso.com");
Web web = ctx.Web;
ctx.Load(web);
Entity entity = ctx.Web.GetEntity("http://team.contoso.com", "Product");
ctx.Load(entity);
ctx.ExecuteQuery();
Once you have a reference to an entity object, you can call any method exposed by the external content
type by name, as shown in this code snippet.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 11-21
You can run any method exposed by an external content type by name:
The code segment above retrieves all instance of the Product external content type. One of the issues of
writing code similar to the one above is the fact that the external content type may contain thousands or
even millions of instances. Usually, you will retrieve instances by using filters, and even then bring in only a
certain number of instances at a time.
You can use filters exposed by an external content type to retrieve instances from the entity:
An Example of Using a Filter on the Product External Content Type to Retrieve Data.
FilterCollection productFilters = entity.GetFilters(“ReadList”);
ctx.Load(productFilters);
ctx.ExecuteQuery();
The code segment uses a filter to reduce the number of instances retrieved from the entity. However, we
still do not have control over how many instances are being retrieved. You can limit the number of
instances retrieved by using paging.
You can use limit filters to retrieve a specific set of instances for a given entity:
As you may know, the new App Model in SharePoint 2013 is the recommended way for building
applications that extend and add functionality to SharePoint. When you build an App for SharePoint and
choose to work in JavaScript, most of the time you will be working with your JavaScript code via the
App.js file. Although you can certainly have more .js files, this file is provided by the App for SharePoint
project template as a starting point.
JSOM is exposed by a series of JavaScript files on the web server, the main file being SP.js. It contains
various namespaces that deal with external content types. By using tools such as .NET Reflector, you can
find the available methods of the various Client OM BCS related classes in the
Microsoft.SharePoint.BusinessData.MetadataModel.ClientOM namespace of the Microsoft.SharePoint.dll.
In this namespace you will find a class called Entity that has the following CSOM and JSOM exposed
methods:
BuildEntityInstanceCollection(IEntityInstanceEnumerator entityInstances);
GetCreatorView(string methodInstanceName);
GetDefaultSpecificFinderView();
GetFilters(string methodInstanceName);
GetFinderView(string methodInstanceName);
GetIdentifierCount();
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 11-23
GetIdentifiers();
GetLobSystem();
GetSpecificFinderView(string specificFinderName);
GetUpdaterView(string updaterName);
"_api/lists/getbytitle('Product')/items?$select=BdcIdentity,ProductID,ProductName",
headers: {
"accept": "application/json",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: this.showItems
});
},
showItems: function (data) {
var items = [];
items.push("<table>");
items.push('<tr><td>Product ID</td><td>Product Name</td></tr>');
$.each(data.d.results, function (key, val) {
MCT USE ONLY. STUDENT USE PROHIBITED
11-24 Working with Business Data
function getProducts () {
var grid = new AppLevelECT.Grid($("#displayDiv"),
spPageContextInfo.webServerRelativeUrl);
grid.init();
}
Note: The REST API can only be used to access external content types by using an external
list.
The following code example shows how to use the SPListItem class to update items in an external list:
The following code example shows how to create items in an external list by using the SPList and
SPListItem classes:
The following code example shows how to use the SPList and SPListItem classes to delete items in an
external list:
The examples above retrieve all items from an external list. In real life, you would use CAML or filters to
retrieve only a limited set of items.
MCT USE ONLY. STUDENT USE PROHIBITED
11-26 Working with Business Data
Lesson 3
Working with Business Data in Client Applications
In this lesson you will learn to how BCS solutions can be used by Office client-side applications such as
Microsoft Outlook®, Word, and Visio®. In addition, you will learn how these client-side applications
utilize a client-side runtime and client-side cache with subscriptions to keep data stored locally, and how
this client-side runtime architecture synchronizes changes back to the external systems.
Lesson Objectives
After completing this lesson, you will be able to:
Describe typical scenarios where external data can be accessed from Office applications.
Some examples of using BCS to integrate with Office client applications include:
Import a set of client contacts from your CRM system into your Outlook client.
Automate the creation and populate of form and document data by using business data.
Implement a color map on a Visio diagram based on values in the back-end database.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 11-27
When an office application makes a call to Business Data, it typically will do so through a BCS Client
Runtime in a process that works like the following:
3. BDC Client Runtime queries the BDC model in the BDC client-side cache.
4. If credentials are needed, user is prompted for them, and credentials are stored.
6. Data is retrieved from external data source and passed up the chain.
Support for disconnected scenarios. Users can continue to manipulate external data seamlessly and
efficiently, even when connectivity is slow, intermittent, or unavailable.
The client cache persistence store is implemented as a SQL Compact Edition database. The database cache
works at an entity level, which means that you can store one entity or many specified entities, but not
MCT USE ONLY. STUDENT USE PROHIBITED
11-28 Working with Business Data
parts of entities. When the cache is running, you will notice a process called BCSSync.exe running on your
client computer. It is the job of this process to provide automatic cache refresh and data synchronization
of the entity instances.
Whenever an operation such as Read, Create, Update, or Delete is performed on an entity instance in the
client application, calls are not routed directly to the external application. Instead, operations are stacked
in a queue and then executed one-by-one depending on the availability of the external application. The
BCSSync.exe process also tries to refresh the cache from the external application at certain intervals.
However, the exact time at which the cache is refreshed cannot be predicted and depends on several
factors.
Note: You should not edit the cache database directly. Instead, you should use the Cache
object model to get access to the client cache.
The BCSSync.exe process makes as many SpecificFinder calls as there are explicit identities in the
subscription, and populates the cache with the entity instances that are returned by the method instance.
Finally, it populates the cache with related entity instances if there are any enabled associations in the
subscription. To do this, it makes as many Associate method instance calls as there are entity instances in
the cache for this subscription. This returns the IDs of the related entity instances. Then it calls the
SpecificFinder on each of the returned IDs to fetch the other fields.
Cache Subscriptions
A subscription defines what data gets populated in the client cache and is automatically generated by BCS
during deployment of a BCS solution. It is represented as an XML file (subscription.xml) and can be found
in the deployment folder. Although a subscription is auto-generated at deployment time, you can modify
a subscription programmatically by using the object model. Subscriptions contain the following objects:
Queries. The queries (Finders) that must be executed to get the entity instances into the client cache.
The following list provides sample queries:
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 11-29
o GetProducts,filter value = Computers (returns products that are part of the Computers category)
Explicit identities. Any additional entity instances that you want to bring from the external data source
by providing their identities explicitly. For instance, you can edit the .xml subscription file and add an
entry to retrieve product #23 (where 23 is the unique identifier for the product).
You can programmatically edit the subscription file to add or remove items:
Cached. In this mode the cache is used. Cache is populated with the entity instances from the external
data source at deployment time and data is refreshed from the external data source at specified
intervals. Operations are not immediately routed to the external data source, but are routed to the
cache. The cache puts these operations in the operation queue and executes them one-by-one.
Fresh. The entity was just received from the external source and the cache refresh interval has not
passed
Invalid. The data is not useful and a refresh of the entity via the SpecificFinder method should be
performed
Obsolete. The runtime that the BCSSync.exe process has already been notified that it must refresh the
entity based on changes in the external system
Stale. The entity is due to be refreshed, but the BCSSync.exe has no reason to believe the entity has
changed
You can work with the client cache programmatically to retrieve entities when the client is offline. The
following code example shows how to enumerate the items in an ECT in the client cache:
You may have instances where you need to programmatically request the BCSSync.exe service to refresh
the cache:
2. Configure SharePoint services and accounts. Add and configure Business Data Connectivity Services
and Secure Store Services. Make sure you create an application in Secure Store Services that maps to
the required account or accounts needed to access the external data source.
3. Configure Business Data Connectivity Services. Make sure BCS is configured to allow users who will
create external content types to add metadata to BCS.
4. Activate the Offline Synchronization for External Lists feature. This must be done on each SharePoint
web. If it is not completed, you will not see the ability to Connect the external lists to office client
applications
Outlook
One of the easiest applications to integrate with BCS data is Outlook. You can easily access external lists
from within Outlook, as long as the external lists expose an external content type (ECT) that is Office
compatible. The overall process for allowing access to an external list from Outlook is the following:
1. Create an external content type. Create an Outlook-supported external content type. Office-
supported content types must have the Offline Sync support option enabled, and they must be
created by selecting an Office Item Type for the external content type when creating the ECT by
using SharePoint Designer. The following Office item types are supported:
a. Appointment
b. Contact
c. Post
d. Task
2. Map corresponding fields. You must map the fields available in the ECT with fields expected for the
selected Office item type. Not all fields must be mapped, but you must map the following fields by
Office item type:
a. Appointment: Subject
b. Contact: LastName
c. Post: Subject
3. Create an external list. You must create an external list based on the new ECT to allow Outlook to
access it.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 11-33
4. Install Office prerequisites for using BCS. Client computers must be running Windows 7 or later with
SQL Server Compact 4.0, .NET Framework 4, and WCF Data Services 5.0 for OData V3.
5. Connect the external list to Outlook. Navigate to the newly create external list and from the List
ribbon, click Connect to Outlook.
Note: The Connect to Outlook button may not do anything when you click it. This is due
to your SharePoint site not being trusted by the browser.
Word
You can use QuickParts in Word to expose data from columns added to a document library. These
columns can contain any type of data available to SharePoint, including external content type. The
process for making an ECT available to Word documents is the following:
1. Create an external content type. Create the ECT by using SharePoint Designer, custom code, or
importing a BDC model. In this case, you do not need to specify any special type of Office item type.
2. Create a document library. Create a document library that uses a Word document as a template.
3. Add a column to the document library. Change the document library settings and add a new column
of type External data that maps to the ECT you want to use.
4. Edit the template used in the document library. From the document library settings, click Advanced
settings, and then click Edit Template. Once the template is open in Word, from the Insert ribbon,
click Quick Parts, navigate to Document Property, and then click on the name of the column you
added to the document library. Save and close the template.
5. Create a new document. Create a new document in the document library and notice that the
document property added has a button named Select. When you click the Select button, the ECT
item picker is displayed.
Visio
You can add data from any list in SharePoint to Visio. Therefore, to add from an ECT in a Visio diagram, all
you need to do is create an external list based on an ECT, and then in a Visio file, link data to any shape.
The overall process for adding ECT data to Visio diagrams is the following:
1. Create an external content type. Create the ECT by using SharePoint Designer, custom code, or
importing a BDC model.
2. Create an external list. You must create an external list based on the new ECT to allow Outlook to
access it.
3. Install Office pre-requisites for using BCS. Client computers must be running Windows 7 or later with
SQL Server Compact 4.0, .NET Framework 4, and WCF Data Services 5.0 for OData V3.
4. Add ECT data to a Visio diagram. Open a Visio diagram, or create a new one, and from the Data
ribbon, click Link Data to Shapes, and then select Microsoft SharePoint Foundation.
Demonstration Steps
1. On the Start screen, type SharePoint Designer, and then press Enter.
3. In the Open Site dialog box, in the Site name box, type http://team.contoso.com, and then click
Open.
4. If you are prompted for credentials, log in as CONTOSO\Administrator with password Pa$$w0rd.
7. In the External Content Type Information pane, next to Name, click New external content type.
10. In the External Content Type Operations pane, click Click here to discover external data sources
and define operations.
13. In the SQL Server Connection dialog box, in the Database Server box, type London.
14. In the Database Name box, type ContosoRetailDW.
15. Click Connect with Impersonated Windows Identity, and then in the Secure Store Application ID
box, type ContosoDW.
16. Click OK.
17. In the BCS Secure Store : ContosoDW dialog box, in the User name box, type
CONTOSO\Administrator.
18. In the Password box, type Pa$$w0rd, and then click OK.
19. On the Data Source Explorer tab, expand ContosoRetailDW, and then expand Table.
20. When the Microsoft SharePoint Designer dialog box appears, explain that the unsupported types
will not affect the demonstration, and then click OK.
21. Under Tables, right-click DimCustomer, and then click Create All Operations.
24. In the Properties pane, in the Office Property drop-down list box, click First Name (FirstName).
25. Under Parameters Configuration, click LastName (the text, not the check box).
26. In the Properties pane, in the Office Property drop-down list box, click Last Name (LastName),
and then click Next.
27. On the Filter Parameters Configuration page, click Add Filter Parameter.
29. In the Filter Configuration dialog box, in the Filter Type drop-down list box, click Limit, and then
click OK.
30. In the Properties pane, in the Default Value box, type 25, and then click Finish.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 11-35
33. In the Create List and Form for Customer Contacts dialog, in the List name box, type Customer
Contacts, and then click OK.
37. On the list of service applications, click Business Data Connectivity Service.
38. On the list of external content types, on the Customer Contacts drop-down menu, click Set
Permissions.
39. In the Set Object Permissions dialog box, type Everyone, and then click Add.
40. Under Permissions for Everyone, select Execute and Selectable in Clients, and then click OK.
42. If you are prompted for credentials, log on as CONTOSO\Administrator with password Pa$$w0rd.
45. On the Site Features page, in the Offline Synchronization for External Lists row, click Activate.
48. In the Microsoft Office Customization Installer dialog box, click Install.
49. When the Microsoft Office Customization Installer dialog box reports that the customization was
successfully installed, click Close.
50. When the BCS has finished generating the installation package, Outlook will open automatically.
Point out the list of customer contacts.
Objectives
In this lab, you will be able to:
Use the JavaScript object model to interact with external content types.
Lab Setup
Estimated Time: 60 minutes
Password: Pa$$w0rd
A warm-up script named WarmUp.ps1 runs automatically when you start the virtual machine. This script
helps to improve the performance of the virtual machine by downloading the home page of the root site
in each site collection on the server. Occasionally this script displays timeout errors; you can ignore these
errors. You should ensure this script has finished running before you start the lab.
2. In the ContosoODataWebServcice.svc file, review the InitializeService method. Notice that this
method exposes the DimProducts, DimProductCategories, and DimProductSubcategories
entities. These map to the DimProduct, DimProductCategory, and DimProductSubcategory
database tables.
3. Start the solution without debugging. You should leave this service running, because you will use it in
the following tasks.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 11-37
o Name: AssetApp
o Locations: E:\Labfiles\Starter
2. Configure the new app to use http://dev.contoso.com for debugging, and to deploy the app as a
SharePoint-Hosted app.
o Name: ContosoODataSource
o DimProductSubcategories
o DimProducts
Note: Use HTML to define the button. Do not use any server controls.
4. Open the App.js file, and delete the contents of the file.
a. Create a RESTful URL that retrieves all items from the DimProducts external list on the app web.
6. Define a function named onReturnData. This function should retrieve the results of the HTTP request
and store the results in a variable named oDataResult.
7. Bind the onGetProducts method to the click event of the cmdGetProducts button.
8. Add a breakpoint to the line that sets the value of oDataResult, and then start debugging.
9. When the page has finished loading, in Internet Explorer, click Get Products.
10. When the debugger reaches the breakpoint, in Visual Studio, press F10.
11. Hover over the text odataResult, and then on the context menu, expand odataResult.
12. Verify that the odataResult variable contains multiple sets of data, and then on the DEBUG menu,
click Stop Debugging.
MCT USE ONLY. STUDENT USE PROHIBITED
11-38 Working with Business Data
Note: Sample code for the App.js file is available in the E:\Labfiles\Starter\App01.txt file.
2. In the onReturnData function, define the markup for an HTML table with the following header
labels:
a. Product
b. Class
c. Brand
d. Unit Price
3. Iterate over the oDataResult variable. For each item in the oDataResult variable, construct an HTML
table row containing the following columns from the data source:
a. ProductName
b. ClassName
c. BrandName
d. UnitPrice
4. Append each row to the table you created, and then add the table to the displayDiv element.
6. When the page loads, click Get Products. Verify that the app displays a table containing product
data.
Results: After this exercise, you should have retrieved a list of products that are older than three years.
2. Immediately above the input element, add a select element with an id value of lstClass.
3. Add the following options to the select element:
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 11-39
a. An option with a value of 'Economy' (including the single quotation marks) that displays the text
Economy.
b. An option with a value of 'Regular' (including the single quotation marks) that displays the text
Regular.
c. An option with a value of 'Deluxe' (including the single quotation marks) that displays the text
Deluxe.
5. In the onGetProducts function, add a line of code to the top of the function that retrieves the value
of the lstClass element.
6. Modify the line of code that constructs the RESTful URL to include an OData filter expression. The
expression should return only those items in which the value of ClassName column is equal to the
value of the lstClass element.
3. Notice that the page only displays items with a Class value of Economy.
4. In the drop-down list box, click Regular, and then click Get Products.
5. Notice that the page displays only items with a Class value of Regular.
6. In the drop-down list box, click Deluxe, and then click Get Products.
7. Notice that the page displays only items with a Class value of Deluxe.
Results: After this exercise, you should have filtered the data retrieved from the OData by class name.
Question: You need to access an external content type hosted in a SharePoint site from a
client Windows-based application. What object model should you use?
Question: You need to access an external content type hosted in a SharePoint site from a
SharePoint sandboxed solution. What object model should you use?
Question: You need to access an external list hosted in a SharePoint site from a SharePoint
app. What object model should you use?
Verify the correctness of the statement by placing a mark in the column to the right.
Statement Answer
What is the name of the process that manages the Business Connectivity Service Client Cache?
W3wp.exe
Mssearch.exe
BCSSync.exe
Noderunner.exe
Verify the correctness of the statement by placing a mark in the column to the right.
Statement Answer
You were exposed to four different APIs with which you can interact with external lists, and the
advantages and disadvantages of each. The preference is to utilize the CSOM and REST APIs via App for
SharePoint development.
Finally, you learned about the complex client-side runtime that allows applications to cache subscriptions
to data stored in external systems for use in Office client applications, thus putting data in the hands of
users via familiar Office applications.
MCT USE ONLY. STUDENT USE PROHIBITED
MCT USE ONLY. STUDENT USE PROHIBITED
12-1
Module 12
Managing and Accessing User Profile Data
Contents:
Module Overview 12-1
Module Overview
User profiles enable you to access and collect a range of information about your users. You can use user
profile information to personalize your solutions for your users, and to make the solution more engaging
for your users. In this module, you will review key aspects of the user profile service and see how you can
write client-side and server-side code to access, update, and manage user profile properties.
Objectives
After completing this module, you will be able to:
Explain how user profile data is used in Microsoft® SharePoint® 2013.
Describe the options and restrictions for accessing user profile data.
Use client-side code and server-side code to access and update user profile data.
Lesson 1
User Profile Data in SharePoint 2013
User profiles provide you with significant information about your users, but it is important to understand
the source of this information, the security implications of exposing the information, and how profile
properties are structured. In this lesson, you will learn about how profile properties are structured, the
data sources that SharePoint aggregates to produce a user profile, and the security risks that can be
introduced by exposing information in a user profile property. Finally, in this lesson you will learn about
the basic requirements to configure a development environment to develop user profile solutions.
Lesson Objectives
After completing this lesson, you will be able to:
Describe the various data sources that SharePoint aggregates in user profiles.
Explain the data security risks introduced by user profiles, and how to mitigate those risks.
Describe the basic configuration requirements for a development environment that enables
developing solutions that utilize user profile data.
Profile Subtypes
In your organization, you may have many users who fit into different logical categories. You may need to
store different information about different categories of users. For example, for production staff you may
store only basic information, but for managers you may need to store additional information. You can
define profile subtypes to enable you to store different information about different types of users. Each
user is then added to a subtype. You can create profile subtypes by using the Central Administration web
site or by using code.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 12-3
When you install the User Profile Service Application, SharePoint creates a default user subtype; by
default, all users are added to the default user subtype.
Directory services
User (SharePoint)
Directory Services
Profile information often comes from a directory service, for example Active Directory®. When you
configure a directory service, it may be read only or read/write. The implementation of SharePoint
integration with your directory service will determine the access you have to user profile properties from a
directory service.
User
Users can provide data that is stored in SharePoint databases. You can change properties where the value
provided by the user is stored in SharePoint without risk of the value being updated during
synchronization with a back-end system.
Additional Reading: You can set the default privacy setting for a user profile property by
using code. For more information on setting privacy settings on user profile properties, see How
to: Set Privacy Policies for User Profile Properties at
http://go.microsoft.com/fwlink/?LinkId=321955
Demonstration Steps
1. Start the 20489B-LON-SP-12 virtual machine.
4. Browse to the management page for the Contoso User Profile Service Application service
application.
6. View the properties of the First name property. Notice that this property is a single valued string
property with a maximum length of 250 characters. Review the default privacy settings for this
property.
7. Return to the management page for the Contoso User Profile Service service application.
8. Review the synchronization settings. Notice that the service application is configured for basic Active
Directory import, but that you can choose to use full SharePoint Profile Synchronization, or use an
external identity manager.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 12-5
The choice between the User Profile Service and User Profile Synchronization Service Windows service is
normally made during the design phase by SharePoint IT professionals, but it is important for developers
to understand the implication of the decision.
MCT USE ONLY. STUDENT USE PROHIBITED
12-6 Managing and Accessing User Profile Data
Lesson 2
Options for Accessing User Profile Data
Like most of the workloads in SharePoint 2013, development options have been extended significantly
when compared to earlier version of SharePoint. There is specific emphasis on providing client-side
options for developing solutions. This helps to make sure that solutions are compatible with SharePoint
Online®. However, there are still important considerations for choosing between client-side and server-
side code. In addition to choosing between development platforms, you will also need to learn how to
retrieve user profiles. While the options for retrieving a single user are straightforward, to retrieve multiple
users you can choose between enumerating users and searching for users. Your choice will normally
depend on the purpose of your solution.
In this lesson, you will learn about the development options and restriction in SharePoint 2013, as well as
see how to enumerate users, how to search for users, and why you might choose each of these options.
Lesson Objectives
After completing this lesson, you will be able to:
You can continue to user server-side code to manage user profile properties. In server-side code, you
have full read/write access to user profile properties.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 12-7
Enumerating Users
In SharePoint 2013, you can enumerate users. You
can either enumerate users at a site level, or
enumerate users at the user profile service
application level.
The following code example shows how to enumerate users at the site level by using server-side code:
The following code example shows how to enumerate users at the user profile service application level by
using server-side code:
While enumerating users can be appropriate if you need to update each user in a site or to make a
change to every user, often you will not need to perform an operation on every user. Enumerating users
often means processing user profile unnecessarily; you can use search to access only the required user
profiles.
MCT USE ONLY. STUDENT USE PROHIBITED
12-8 Managing and Accessing User Profile Data
The following code example shows how to perform a people search by using the JavaScript client-side
object model:
query.set_queryText(queryText);
query.set_sourceId("B09A7990-05EA-4AF9-81EF-EDFAB16C4E31");
clientContext.executeQueryAsync(function () {
$.each(results.m_value.ResultTables[0].ResultRows, function () {
var accountName = this.AccountName;
var preferredName = this.PreferredName;
}
}, function () {
alert("Error performing search.");
});
Note: Before you use people search, you must be certain that the search service is
configured correctly and is configured to crawl the My Sites web application. If the search service
does not crawl the My Sites site collection, people search will not function correctly.
Additional Reading: For more information on how to configure people search, see Deploy
people search in SharePoint Server 2013 at http://go.microsoft.com/fwlink/?LinkId=321954
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 12-9
Lesson 3
Managing User Profile Data
As part of a solution that uses user profile data, you will often need to retrieve user profile properties. You
may also need to update user profile properties. In this lesson, you will review the options for creating a
user profile, and how you can use both server-side and client-side code to retrieve user profile properties.
Finally, you will see how to use code to update profile properties.
Lesson Objectives
After completing this lesson, you will be able to:
The following code example shows how to create a user profile for a user by using server-side code:
UserProfile = userProfileManager.CreateUserProfile("CONTOSO\Mike");
MCT USE ONLY. STUDENT USE PROHIBITED
12-10 Managing and Accessing User Profile Data
The following code example shows how to retrieve user properties by using client side code:
For profile properties that the UserProfile class does not expose as a property (including custom
properties), you can use an indexer on the UserProfile instance to access the property. You must specify
the property name in the indexer. When you use the indexer to retrieve a property, you must then use the
Value property of the object returned by the indexer in order to retrieve the property value. For out-of-
the-box properties that are not exposed as properties of the UserProfile class, you can use the
PropertyConstants enumeration in the indexer; this reduces the risk of introducing a runtime exception,
and (by using Microsoft IntelliSense®) enables you to choose a property without the need to remember
(or look up) the exact property name. Obviously, the PropertyConstants enumeration does not include
the name of any custom properties you may create, so for custom properties you must use a string with
the indexer.
Some properties contain multiple values. For these properties, you must use a slightly different technique
to obtain the value of the property. You can choose to either enumerate each of the values stored in the
property (by using the GetEnumerator method), or you can use an indexer to access each value.
The following code example shows how to retrieve user profile values for a given user by using server-side
code:
// Obtain a reference to the user profile for the current user (if the current user does
not already have
// a profile, create one).
UserProfile user = userProfileManager.GetUserProfile(true) ;
Note: The UserProfileManager class exposes a GetUserProfile method that you can use
to obtain a single user profile. You can use this method to retrieve the user profile of the current
user, or you can use this method to retrieve the user profile of a different user by providing the
user name. This method will also create a user profile, if necessary.
Demonstration Steps
1. Start the 20489B-LON-SP-12 virtual machine.
3. On the Start screen, type Visual Studio, and then click Visual Studio 2012.
4. In Microsoft Visual Studio®, on the FILE menu, point to Open, and then click Project/Solution.
7. The code in this class obtains a reference to the user profile service application, and then enumerates
the properties of the default profile subtype.
8. In Solution Explorer, right-click ManageUserProfileProperties, point to Debug, and then click Start
new instance.
11. In Solution Explorer, expand Loader, and then under Loader, double-click Program.cs.
12. Review the code. To connect to the user profile service application, the account requires specific
permissions. The Administrator account does not have these permissions, but the SPFarm account
does. This code grants the SPFarm account the necessary permissions to run an interactive
application (by adding the account to the Domain Admins security group) before starting the
ManageUserProfileProperties application in the context of the SPFarm account. This enables the
application to connect to the user profile service application. Finally, the code removes the SPFarm
account from the Domain Admins security group.
After you update the value or add a new value to a multi-valued property, you must call the Commit
method of the UserProfile class to save the changes to the database.
The following code example shows how to update user profile property values by using server-side code:
// Multi-valued properties.
userProfile[PropertyConstants.Skills].Add("SharePoint Development");
userProfile[PropertyConstants.Skills][0] = "Web Development";
// Persist changes.
userProfile.Commit();
Note: SharePoint does not permit you to update a user profile property during a page GET
request. You can override this by setting the AllowUnsafeUpdates property of the SPWeb class
to true.
While generally you cannot use client-side code to update a user profile property, the profile picture is an
exception to this rule. You can update a user's profile picture by using the setMyProfilePicture method
exposed by the PeopleManager class in client-side code.
Additional Reading: For more information on working with user profiles in SharePoint
2013, see Work with user profiles in SharePoint 2013 at
http://go.microsoft.com/fwlink/?LinkId=321953
MCT USE ONLY. STUDENT USE PROHIBITED
12-14 Managing and Accessing User Profile Data
Objectives
After completing this lab, you will be able to:
Lab Setup
Estimated Time: 30 minutes
Password: Pa$$w0rd
A warm-up script named WarmUp.ps1 runs automatically when you start the virtual machine. This script
helps to improve the performance of the virtual machine by downloading the home page of the root site
in each site collection on the server. Occasionally this script displays timeout errors; you can ignore these
errors. You should ensure this script has finished running before you start the lab.
2. Review the markup in the Default.aspx file. Notice that the file contains a div element with the id
search, and a div element with the id results.
2. Add markup to the div with the id search to define a paragraph that contains a label with the text
Name, and a text box with the id name.
3. Add markup to the div with the id search to define a paragraph that contains a label with the text
Department, and a text box with the id department.
4. Add markup to the div with the id search to define a paragraph that contains a button with the text
Search, and a text box with the id submitSearch.
5. Add markup to the div with the id results to define a paragraph that contains an anchor tag with the
text New Search. When the user clicks the anchor tag, the browser should invoke the
Contoso.UserProfileApp.showSearch function.
6. Add markup to the div with the id results to define a div tag with the id users.
7. Review the markup in the App.css file. Notice that the markup defines the layout for the elements
you have added in this task
a. Clear any existing results by setting the inner HTML of the users div to an empty string.
b. Construct a query string by using the values from the accountName, name and department
text boxes. The query string should contain only properties where a value has been provided by
the user, and should include the following property mappings:
accountName AccountName
department Department
d. Set the queryText property of the query object to the query string you constructed.
g. Define a new variable named results and initialize it to the result of invoking the executeQuery
method of the searchExecutor class by using the query object as a parameter.
i. If the query returns successfully, hide the search div and show the results div.
j. If the query returns successfully, reset the values of the accountName, name, and department
text boxes.
k. If the query returns successfully, but the result set does not contain any users, display the
message No users for your search criteria. in the users div.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 12-17
l. If the query returns successfully, and the result set does contain users, append an h1 tag with the
text Users to the users div.
m. If the query returns successfully, and the result set does contain users, for each user, append a div
element to the users div. The div element should contain an anchor element with the following
properties:
Property Value
n. If the query does not return successfully, displays an alert message with the text Error
performing search.
3. Add code to the return statement of the Contoso.UserProfileApp function to expose the
searchUsers method.
4. Add code to add the searchUsers method as the click event handler for the submitSearch button
when the page is ready.
3. Verify that a single user is returned with the display name Administrator.
11. In the Name box, type Smith, in the Department box type Marketing, and then click Search.
12. Verify that a single user is returned with the display name Denise Smith.
Results: After completing this exercise, you should have added search functionality to an app.
a. Create a new array named requiredProperties that contains the following values:
i. AccountName
ii. FirstName
iii. LastName
iv. PreferredName
v. Department
vi. Company
b. Retrieve the username of the required profile by using the value of the data-username attribute
of the link passed as a parameter to the function. Store the username in a new variable named
username.
g. If the query returns successfully, display the results in the profile div. Display each property on a
new line, and label each property.
h. If the query does not return successfully, display an alert message with the text Error retrieving
user profile.
3. Add code to the return statement of the Contoso.UserProfileApp function to expose the
displayProfile method.
4. Modify the searchUsers function to clear any existing profile data from the profile div by setting the
inner HTML to an empty string; you should perform this step immediately after the code that clears
the users div.
5. Modify the searchUsers function to render each search result as a link. When a user clicks the link,
the browser should invoke the Contoso.UserProfileApp.displayProfile method, and pass itself as a
parameter.
2. On the User Profile Search page, in the Name box, type Smith, and then click Search.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 12-19
4. Verify that the app displays the profile information for Denise Smith.
Results: After completing this exercise, you should have modified an app to retrieve a user profile.
MCT USE ONLY. STUDENT USE PROHIBITED
12-20 Managing and Accessing User Profile Data
Lesson 4
Managing User Profile Properties
In addition to working with existing user profile properties, you may need to create new user profile
properties or update an existing user profile property, for example, by changing the default privacy
setting for the property. In this lesson, you will learn how to manage user profile properties, and how to
create new user subtypes.
Lesson Objectives
After completing this lesson, you will be able to:
CreateSubtype. The CreateSubtype method enables you to create a new subtype. When you create a
new subtype, you must specify a profile type. The profiles types are defined in the ProfileType
enumeration. You must specify the ProfileType.User value in order to create a new user profile
subtype.
DeleteSubtype. The DeleteSubtype method enables you to delete an existing subtype. You must
specify the name of the subtype as a parameter.
The following code example shows how to use the ProfielSubtypeManager class to manage user profile
subtypes:
Note: If you have a valid instance of the ProfilePropertyManager class defined in your
code, you must call the Reset method of the ProfilePropertyManager class to invalidate the in-
memory cache before you use a new profile subtype in your code.
To create profile properties, you must use manager classes for each type of property. You obtain
references to the manager classes by using the ProfilePropertyManager property of the
UserProfileConfigManager class.
MCT USE ONLY. STUDENT USE PROHIBITED
12-22 Managing and Accessing User Profile Data
The following code example shows how to define a user profile property:
// Create a new core property by using the Create method of the CorePropertyManager
class.
// Specify false to indicate the core property is a property not a section.
CoreProperty coreProp = corePropManager.Create(false);
Note: To manage user profile properties requires permissions on the User Profile Service
Application. The permissions must be granted to the account under which the code is running;
for example, the current user, the web application service account, or another service account.
After you delete a property, you should always call the Reset method of the ProfilePropertyManager
instance to invalidate the in-memory cache of properties. If you do not invalidate the in-memory cache,
your code may not work as expected.
Additional Reading: For more information on working with user profiles in server-side
code, see How to: Work with user profiles and organization profiles by using the server object
model in SharePoint 2013 at http://go.microsoft.com/fwlink/?LinkId=321952
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 12-25
Objectives
After completing this lab, you will be able to:
Lab Setup
Estimated Time: 30 minutes
Password: Pa$$w0rd
A warm-up script named WarmUp.ps1 runs automatically when you start the virtual machine. This script
helps to improve the performance of the virtual machine by downloading the home page of the root site
in each site collection on the server. Occasionally this script displays timeout errors; you can ignore these
errors. You should ensure this script has finished running before you start the lab.
1. Grant the Domain Admins Account Administrative Permissions on the User Profile Service Application
Task 1: Grant the Domain Admins Account Administrative Permissions on the User
Profile Service Application
1. Open the Central Administration web site.
3. Grant the Domain Admins Active Directory security group the Manage Profiles permission on the
Contoso User Profile Service Application service application.
2. Review the ContosoManagePropertiesWebPart.ascx file. Notice that the file defines a text box, two
buttons and a table.
e. Iterate through each property in the properties enumerator. For each property perform the
following tasks:
i. Verify that the property is a property; if the property is a section, skips the property.
iii. Add a cell to the row. Set the Text property of the cell to the Name property of the current
profile property.
iv. Add another cell to the row. The cell should contain a drop down list with the values Private
and Public as options.
v. Set the selected item in the drop down list based on the default privacy setting of the current
property.
vi. Add an attribute to the drop down list named data-propertyName, with the value set to the
Name property of the current property.
vii. Set the ID property of the drop down list to the concatenation of UserProfileProperty-
PrivacySetting- with the Name property of the current property.
viii. Specify an event handler for the drop down list’s SelectedIndexChanged event named
privacyOptions_SelectedIndexChanged (you will implement this method in the next
exercise).
ix. Add another cell to the row. The cell should contain a button with the text Delete.
x. Add an attribute to the button named data-propertyName, with the value set to the Name
property of the current property.
xii. Specify an event handler for the button’s Click event named deleteButton_Click (you will
implement this method later in the next exercise).
xiii. Add the row to the Rows collection property of the propertiesTable table.
9. Add a new private method named addProperty_Click to the class. The method should take two
parameters, an object named sender, and an EventArgs named e. You will implement this method
in the next exercise. The method should not return anything.
10. Add a new private method named deleteButton_Click to the class. The method should take two
parameters, an object named sender, and an EventArgs named e. You will implement this method
in the next exercise. The method should not return anything.
2. Add the ContosoManagePropertiesWebPart web part to the Contoso Development Site home
page.
Results: After completing this exercise, you should have added code to display user profile properties on
a web part.
Property Value
Data length 50
IsVisibleOnViewer true
IsUserEditable true
UserOverridePrivacy true
a. Retrieve the selected property by using the data-propertyName attribute of the drop-down list
control to identify the user profile property.
b. Update the DefaultPrivacy property of the user profile property based on the selected value of
the drop-down list.
2. Add a new property with the name New Property. After you click Add Property, the page may take
some time to update. Wait for the page to update before you continue. Do not click Add Property
twice, or the code may throw an exception.
3. Change the default privacy for the New Property property to Private.
Results: After completing this exercise, you should have updated a web part to include functionality to
manage user profile properties.
MCT USE ONLY. STUDENT USE PROHIBITED
12-30 Managing and Accessing User Profile Data
Review Question(s)
Verify the correctness of the statement by placing a mark in the column to the right.
Statement Answer
Verify the correctness of the statement by placing a mark in the column to the right.
Statement Answer
You can update all user profile properties by using either server-side or client-side code.
You can update all user profile properties by using server-side code only.
You can update all user profile properties by using client-side code only.
You can update all user profile properties by using server-side code, and the user profile
picture by using client-side code.
You can update all user profile properties by using client-side code, and the user profile
picture by using server-side code.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 12-31
Verify the correctness of the statement by placing a mark in the column to the right.
Statement Answer
Module 13
Customizing the Social Workload
Contents:
Module Overview 13-1
Module Overview
Enterprises of all sizes are integrating social solutions into their workplaces. With proper use, social
solutions can help to improve productivity, encourage innovation, and increase morale. Microsoft®
SharePoint® 2013 includes many social features that are either new or have been significantly updated. In
this module, you will see some of the social features in SharePoint 2013, and you will see how you can
develop apps that extend and customize the social workload, tailoring the experience for your business
needs.
Objectives
After completing this module, you will be able to:
Describe the main components of the social workload.
Create solutions that make use of the newsfeed functionality in SharePoint Server 2013.
MCT USE ONLY. STUDENT USE PROHIBITED
13-2 Customizing the Social Workload
Lesson 1
Overview of the Social Workload
In this lesson you will review the social workload in SharePoint 2013. You will consider some of the
changes from the social features in the previous versions of SharePoint, and you will learn about how to
configure a development environment to support social solutions.
Lesson Objectives
After completing this lesson, you will be able to:
then appear in their list of followed sites. Similarly, sites can have newsfeeds. From a newsfeed, users can
follow other users, hashtags, or other social entities. The user’s interactions are reflected throughout
SharePoint; for example, if you are following a user you will get options to stop following that user instead
of options to follow them. The following data is still stored in the My Site.
The three main hubs of the user’s My Site can now be accessed directly from most SharePoint pages. This
ensures that a user does not need to navigate to a My Site landing page and then to a specific page on
their My Site; the access is much more direct.
The newsfeed hub provides access to a user’s feed, where they can post updates similar to posting on
other social networks. For the newsfeed hub, users can also view profile information and edit their own
profile information. In addition, the newsfeed hub provides access to the user’s blog, task list, and other
apps that the user has added.
The SkyDrive hub provides access to documents that the user has stored in the cloud. The files stored in
the cloud can be synchronized with a Windows PC, so users can simply edit the file locally and the
changes will be mirrored to the SkyDrive document store. The SkyDrive hub (also known as SkyDrive Pro)
provides functionality similar to Microsoft SkyDrive, but with the files being stored on a user’s My Site
instead of in SkyDrive cloud storage. Files added to the SkyDrive hub can easily be shared with other users
within the organization.
The Sites hub enables the user to manage their followed sites. In addition, the user can see suggested sites
(users can suggest sites to other users). Also, users can use the Sites hub to create new sites if they have
the necessary permissions.
Demonstration Steps
1. Start the 20489B-LON-SP-13 virtual machine.
2. Log on to the LONDON machine as CONTOSO\Administrator with password Pa$$w0rd.
4. In Internet Explorer, in the address bar, type http://my.contoso.com, and then press Enter.
5. If SharePoint displays the We’re still collecting the latest news. You may see more if you try
again a little later message, periodically refresh the page. This may take many minutes. Explain that
SharePoint uses timer jobs to populate the newsfeed and that as a result of the virtual machine being
shut down for extended periods, these timer jobs must execute before the feed is populated. This is
unlikely to happen in a production environment.
6. Point out the Newsfeed page including the Following, Everyone, and Mentions feeds.
7. On the Quick Launch menu, click About me.
17. Point out the list of documents, and on the Quick Launch menu, point out the Followed Documents
link.
18. On the SharePoint menu bar, click Sites.
State Service
Managed Metadata Service
In addition to the service applications, there are a number of services that must be running for social
features to work correctly. You should confirm that the following services are running.
Distributed Cache
Social solutions often use search. To simplify your development, you should confirm that the search
service has permissions to access all of the site collections and web applications in your environment,
including the web application that is hosting My Site sites. You should also consider configuring the
content source to continuously crawl content. This can help to ensure that new items appear in search
results promptly, and without running a manual search crawl each time. You should be aware that despite
a crawl running all of the time, there will normally still be a delay between when a new item is added to
SharePoint and when that item appears in search results.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 13-5
Lesson 2
Developing Social Solutions
In this lesson, you will learn about how to develop social solutions. You will learn about the permissions
required when developing a social app, and you will learn about how to follow and like entities by using
code.
Lesson Objectives
After completing this lesson, you will be able to:
Demonstration Steps
1. Start the 20489B-LON-SP-13 virtual machine.
4. In Internet Explorer, in the address bar, type http://project.contoso.com, and then press Enter.
6. On the Newsfeed page, in the Start a conversation text box, type This is a #newtag, and then click
Post.
10. In the I’m following list, above tags, click the number 1.
To simplify development, you can choose to use the Tenant scope (http://sharepoint/content/tenant).
The Tenant scope provides access to the whole tenancy; this includes the Core Social and Microfeed
permission scopes. After development and for final testing you should use more restrictive permission
scopes.
For final testing and production, you should deploy your app by using an app catalog. If you attempt to
debug an app that uses social features without specifying the Tenant scope, you must deploy your app
by using an app catalog. You may get unexpected errors if you do not use an app catalog.
Note: When you choose permissions levels (for example, read or read and write), if you
choose the full control permission level you cannot deploy your app to Office 365. The office
store blocks any app that request the full control level for any permission.
Because many social solutions make use of search, you may also need to specify the Search scope
(http://sharepoint/search), and specify the QueryAsUserIgnoreAppPrincipal permission level. This
permission enables an app to perform a search query by using the permissions of the user, as opposed to
the permissions granted to the app.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 13-7
Actors
When you develop social solutions, entities such as
users, sites, tags, and documents are referred to as
actors. Actions that you can perform in the social
workload are normally performed on a set of actors.
For example, an actor can follow another actor
much as a user can follow a site.
ActorType All The type of the actor 0=User 1=Document 2=Site 3=Tag.
IsFollowed All A Boolean value showing whether or not the current user
follows the specified actor.
TagGuid Tag The unique GUID that identifies the specified tag.
Additional Reading: For more information about the properties available in the
SocialActor class, see the SocialActor members page at
http:/go.microsoft.com/fwlink/?LinkId=321957
Following Entities
Commonly, a user may choose to follow an actor.
You can create solutions that enable a user to
follow actors. In SharePoint 2013, you should
normally develop a client-side application to enable
a user to follow an actor. You can use REST, the
.NET Client-side Object Model, or the JavaScript
Object Model to follow an actor.
administrator has disabled the Follow Content Feature, you can still follow actors on that site by using a
custom solution.
http://<appWebUrl>/_api/social.following/follow<feedOptions>
The feedOptions that follow depend on the type of actor that you want to follow. The following table
shows the parameters used for each type of actor:
User http://
<appWebUrl>/_api/social.following/follow(ActorType=0,AccountName=@v,Id=null)?@v
='contoso\pat’
Document http://<appWebUrl>/_api/social.following/follow(ActorType=1,ContentUri=@v,Id=null)?
@v='http://server/Shared%20Documents/fileName.docx’
Site http://<appWebUrl>/_api/social.following/follow(ActorType=2,ContentUri=@v,Id=null)?
@v='http://server/site’
Tag http://<appWebUrl>/_api/social.following/follow(ActorType=3,TagGuid='19a4a484-
c1dc-4bc5-8c93-bb96245ce928',Id=null)
User
'actor': {
'__metadata': {
type: 'SP.Social.SocialActorInfo'
},
'ActorType': 0,
'AccountName': "domain\\user",
'Id': null
}
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 13-9
Document
'actor':{
'__metadata':{
'type': 'SP.Social.SocialActorInfo'
},
'ActorType': 1,
'ContentUri': 'http://server/Shared%20Documents/File.docx',
'Id':null
}
Site
'actor':{
'__metadata':{
'type': 'SP.Social.SocialActorInfo'
},
'ActorType':2,
'ContentUri':'http://siteCollection/site',
'Id':null
}
Tag
'actor':{
'__metadata':{
'type': 'SP.Social.SocialActorInfo'
},
'ActorType': 3,
'TagGuid': '69a4c382-b1dc-4bc5-3c93-eb96245ce923',
'Id':null
}
Note: The TagGuid cannot be obtained by using REST. You must use either the .NET Object
Model or the JavaScript Object Model.
The following code example shows how to follow a user by using REST:
function followUserRequestBody() {
$.ajax({
url: appWebUrl + "/_api/social.following/follow",
type: 'POST',
data: JSON.stringify({
'actor': {
'__metadata': {
MCT USE ONLY. STUDENT USE PROHIBITED
13-10 Customizing the Social Workload
type: 'SP.Social.SocialActorInfo'
},
'ActorType': 0,
'AccountName': 'contoso\\pat',
'Id': null
}
}),
headers: {
'accept': 'application/json;odata=verbose',
'content-type': 'application/json;odata=verbose',
'X-RequestDigest': $('#__REQUESTDIGEST').val()
},
success: followSuccess,
error: followFail
});
}
function followSuccess(data) {
var followResult = data.d.Follow;
}
FollowResult
The request returns a result of type SP.Social.SocialFollowResult. The following table shows the possible
values that can be returned.
Status Result
0 OK
1 AlreadyFollowing
2 LimitReached
3 InternalError
SocialFollowingManager
The SocialFollowingManager class is similar to the SocialRestFollowingManager resource. It is used to
manage the list of actors that the current user follows. A key subset of the methods available in the
SocialFollowingManager class include:
Follow Adds the specified actor to the current user’s SocialActorInfo – The actor
list of followed actors. that is to be followed.
IsFollowed Returns true if the current user is already SocialActorInfo – The actor
following the specified actor. that is being queried.
StopFollowing Removes the specified actor from the SocialActorInfo – The actor
current user’s list of followed actors. that is to be unfollowed.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 13-11
SocialActorInfo
The SocialActorInfo class determines which type of actor you want to deal with and has the following
properties available.
AccountName User The account name of the specified user (e.g. contoso\pat).
The following code example shows how to follow a user by using the .NET Object Model:
followingManager.Follow(socialActorInfo);
clientContext.ExecuteQuery();
The following example shows how to follow a user by using the JavaScript Object Model:
followingManager.follow(actorInfo);
clientContext.executeQueryAsync(followSuccess, followFail);
MCT USE ONLY. STUDENT USE PROHIBITED
13-12 Customizing the Social Workload
Managing Following
Any site, tag, or document can be followed. For
these types of actors, you will normally want to
provide a toggling option that switches state
between follow and stop following. When your app
starts, you should be sure that any controls to
enable a user to follow an actor are in the correct
initial state.
For users, you can obtain actor properties to determine what are valid options.
The following code example shows how to manage following by using REST:
if (actorInfo.CanFollow == true) {
if (actorInfo.isFollowed == false) {
followUser(actorInfo.AccountName);
} else {
stopFollowingUser(actorInfo.AccountName);
}
}
void CanFollow(socialActor) {
If (socialActor.CanFollow == true) {
FollowToggle(socialActorInfo);
}
void FollowToggle(socialActorInfo) {
ClientResult<SocialFollowResult> result = followingManager.Follow(socialActorInfo);
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 13-13
clientContext.ExecuteQuery();
if (result.Value == SocialFollowResult.AlreadyFollowing)
{
followingManager.StopFollowing(socialActorInfo);
clientContext.ExecuteQuery();
}
}
function follow(socialActor) {
var socialActor = getSocialActor();
if(socialActor.get_canFollow() == true) {
clientContext.executeQueryAsync(followToggle, followFail);
}
}
function followToggle() {
var isFollowed = followingManager.isFollowed(actorInfo);
if (isFollowed.get_value()==true) {
followingManager.stopFollowing(actorInfo);
} else {
followingManager.follow(actorInfo);
}
clientContext.executeQueryAsync(followToggleSuccess, followToggleFail);
}
Liking Posts
As well as following actors, you can also like posts.
Any post you follow appears in the Likes section of
your My Site. You don’t have to be following the
user in order to like their post. While following an
actor gives you updates about that actor, liking a
post is more of a way of keeping a history posts or
replies that interest you.
After you have determined if the post can be liked, you must determine if the current user already likes
that post. The IncludesCurrentUser property defined in LikerInfo provides a Boolean value to indicate if
that post is currently liked or not.
The following example shows how to like a post by using the JavaScript Object Model. The code is very
similar to following a post. Liking a post by using the .NET Client Object Model and REST are not included
here, but follow the same pattern as following a post in the previous topics:
if (likerInfo != null) {
if (likerInfo.get_includesCurrentUser() == false) {
feedManager.likePost(postId);
clientContext.load(feedManager);
clientContext.executeQueryAsync(postLiked, postLikedFail);
}
else {
feedManager.unlikePost(postId);
clientContext.load(feedManager);
clientContext.executeQueryAsync(postUnliked, postUnlikeFail);
}
}
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 13-15
Lesson 3
Working with Feeds
In this lesson, you will learn how to work with feeds in SharePoint 2013. You will learn how to retrieve a
feed from either a My Site or another site, and then you will learn how to post messages to a feed. Finally,
this lesson covers how to include hashtags and mentions in a newsfeed post.
Lesson Objectives
After completing this lesson, you will be able to:
Introducing Feeds
SharePoint 2013 introduces newsfeeds. Users can
post updates to a feed, as well as links to pictures
and sites.
Retrieving Feeds
A feed consists of a number of threads. Each thread
consists of a root post and any number of replies.
To retrieve a feed, you must first retrieve the social
feed that contains details about the threads
included in the feed, in addition to other actor
information such as actor information for post
authors, as well as information on any tags or
mentions included in a post.
REST
To retrieve a feed by using REST, you must make a
GET request to the site that is hosting the
SharePoint Project/App. The structure of the site
URL depends on which type of entity you want to retrieve a feed from.
Site http://<appWebUr>l/_api/social.feed/actor(item=@v)/feed?@v='http://<teamSiteUri>/new
sfeed.aspx’
The code example shows how to retrieve the current user’s personal feed by using REST:
function retrieveMyFeedSuccess(data) {
var feedThreads = datat.d.SocialFeed.Threads.results;
}
SocialFeedManager
The SocialFeedManager class provides the gateway to access social elements by using the .NET Client
Object Model. Methods are provided to create posts, modify existing threads, and access the social feeds
of users and sites.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 13-17
GetFeed Gets the current user’s activity feed. SocialFeedType – The type of feed that is
The activity of content and people to be retrieved.
followed by the current user can SocialFeedOptions – Options to define
also be retrieved. how the feed should be retrieved.
GetFeedFor Retrieves a feed for a specified site actorId – A string that contains either the
or user. account name or email address of a user
or the feed address of a site.
Additional Reading: For more information about the SocialFeedManager class, see the
SocialFeedManager members MSDN page at http://go.microsoft.com/fwlink/?LinkId=321960
The following code example shows how to retrieve the current user’s personal feed by using the .NET
Client Object Model:
Retrieve Current User’s Personal Feed by Using the .NET Client Object Model
ClientContext clientContext = new ClientContext(serverUrl);
Retrieve the Current Users Personal Feed by Using the JavaScript Object Model
var personalFeed;
function getMyPersonalFeed() {
var clientContext = SP.ClientContext.get_current();
var feedManager = new SP.Social.SocialFeedManager(clientContext);
clientContext.load(feedManager);
clientContext.executeQueryAsync(getMyPersonalFeedSuccess, getMyPersonalFeedFail);
}
function getMyPersonalFeedSuccess() {
var personalfeedThreads = personalFeed.get_threads();
}
Demonstration Steps
1. Start the 20489B-LON-SP-13 virtual machine.
3. On the Start screen type Visual Studio, and then click Visual Studio 2012.
4. In Visual Studio, on the FILE menu, point to Open and then click Project/Solution.
7. Review the contents of the Default.aspx page. Notice the additional JavaScript file reference for the
sp.userprofiles.js script file, and the empty posts div.
8. In Solution Explorer, expand Scripts, and then double-click App.js.
9. Review the contents of the App.js file. The getNewsFeed and getNewsFeedSuccess functions, load
the newsfeed for the current user and add the root post of each of the newsfeed threads to the page.
10. Notice the code that invokes the getNewsFeed function when the page loads, and then
subsequently every five seconds.
12. In the App Manifest designer, on the Permissions tab, notice that this app requires the User Profiles
(Social) and Tenant permissions to enable it to access the user’s newsfeed.
15. In a new instance of Internet Explorer, browse to http://my.contoso.com. Arrange the two instances
of Internet Explorer so that they can be seen side by side.
16. On the Newsfeed page, in the Start a conversation box, type A new post and then click Post.
17. Notice that the post appears in the newsfeed on the My Site newsfeed, and that the post also appears
in the app (the Newsfeed Posts page).
19. In the Reply text box, type A reply, and then under the Reply text box, click Post.
20. Notice that although the reply is displayed on the My Site, it is not displayed in the app. This is
because the app is only displaying the root post for each thread.
Posting to a Feed
You can post in the context of the current user. A
user cannot create a root post on another user’s My
Site; however, you can post a root post on the
current user’s My Site, or on a SharePoint site. You
can also post a reply to an existing post. You can
reply to a post on either a SharePoint site or a My
Site, including another user’s My Site.
http://<appWebUrl>/_api/social.feed/my/feed/
post
To post to the newsfeed of a specific SharePoint site, use the following endpoint URI structure:
http://<appWebUrl>/_api/social.feed/actor(item=@v)/feed/post?@v='http://project.contoso.com/ne
wsfeed.aspx’
The following code example shows how to send a post to the current user’s My Site feed by using REST:
SocialPostCreationData
The SocialPostCreationData class contains information about the post that is to be posted to the
specified news feed. A key subset of the properties provided in this class include:
Property Parameters
The following code example shows how to send a post to the current user’s My Site feed by using the
.NET Client Object Model:
Post to the Current User’s My Site by Using the .NET Client Object Model
ClientContext clientContext = new ClientContext(serverUrl);
feedManager.CreatePost(null, postCreationData);
clientContext.ExecuteQuery();
Post to the Current User’s My Site Feed by Using the JavaScript Object Model
var clientContext = SP.ClientContext.get_current();
var feedManager = new SP.Social.SocialFeedManager(clientContext);
feedManager.createPost(null, postCreationData);
clientContext.executeQueryAsync(postSent, postFailed);
String.Format method). For example, if a user types @Pat Hello #World, you should submit @{0} Hello
{1} with an array of SocialDataItem instances that contain Pat and #World.
Note: When a new hashtag is used in a post, it is added to the SharePoint tag library.
Text Tag string - The text of the gat that is to be added to the post.
Uri Site/Document Uri - The Uri of the site or document that is to be added to
the post.
Additional Reading: For more information about the SocialDataItem class, see the
SocialDataItem members MSDN page at http://go.microsoft.com/fwlink/?LinkId=321965
REST
The following code example shows how to create a hashtag and mention and add them to a post by
using REST:
$.ajax({
url: appWebUrl + "/_api/social.feed/my/feed/post",
type: 'POST',
data: JSON.stringify({
'restCreationData': {
'creationData': {
'__metadata': {
'type': 'SP.Social.SocialPostCreationData'
},
'ContentItems': {
'results': postItems
},
'ContentText': '@{0} Post sent by using {1}',
'UpdateStatusText': false
MCT USE ONLY. STUDENT USE PROHIBITED
13-22 Customizing the Social Workload
}
}
}),
headers: {
'accept': 'application/json;odata=verbose',
'content-type': 'application/json;odata=verbose',
'X-RequestDigest': $('#__REQUESTDIGEST').val(),
},
success: postWithItemsSuccess,
error: postWithItemsFail
});
Add a Mention and Hashtag to a Post by Using the .NET Client Object Model
ClientContext = new ClientContext(serverUrl);
SocialFeedManager feedManager = new SocialFeedManager(clientContext);
feedManager.CreatePost(null, postCreationData);
clientContext.ExecuteQuery();
Add a Mention and a Hashtag to a Post by Using the JavaScript Object Model
var mention = new SP.Social.SocialDataItem();
mention.set_itemType(SP.Social.SocialDataItemType.user);
mention.set_accountName("contoso\\pat");
feedManager.createPost(null, postCreationData);
clientContext.executeQueryAsync(postSent, postFailed);
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 13-23
Objectives
After completing this lab, you will be able to:
Use REST to retrieve a site newsfeed.
Use the JavaScript Object Model (JSOM) to search for newsfeed posts on My Site newsfeeds.
Lab Setup
Estimated Time: 60 minutes
Password: Pa$$w0rd
A warm-up script named WarmUp.ps1 runs automatically when you start the virtual machine. This script
helps to improve the performance of the virtual machine by downloading the home page of the root site
in each site collection on the server. Occasionally this script displays timeout errors; you can ignore these
errors. You should ensure this script has finished running before you start the lab.
Scope Permission
Tenant Write
Note: The Tenant permission simplifies the debugging process. In a production app you
should use the most restrictive permissions requirements that are necessary for your app.
2. Use the Utilities.appWebUrl and Utilities.hostWebUrl properties to make an Ajax call to retrieve
the project site newsfeed.
3. If successful, the Ajax GET request must return the thread results of the feed in reverse order, set the
feed to Contoso.NewsfeedApp.feedPosts and update the display.
4. Locate the // TODO: Add code to update the newsfeed when the app launches. comment.
5. After the comment you have just located, add code to invoke the
Contoso.NewsfeedApp.updateFeed function when the app launches. This will update the display
with the posts you retrieved by using the Ajax GET request.
2. On the Project Site home page, add the ContosoFeedAppPart Title app part to the top section of
the page.
3. Verify that a newsfeed is displayed with a single post, with the message Welcome to the project site
for project 2822.
Results: After completing this exercise, you should have modified an app part to display a newsfeed from
a project site.
2. In the Source view locate the <!-- TODO: Add textarea and button. --> comment.
3. After the comment, add a text area to the app part with the following attributes:
Attribute Value
Id StatusTextArea
cols 50
rows 2
4. Next to the text area, add a button to the app part with the following attributes:
Attribute Value
Id PostStatus
Type button
5. In the App.js file, locate the comment // TODO: Add code to add a click event handler to the
post button.
6. After the comment, add code to invoke the Contoso.NewsfeedApp.post function when the user
clicks the PostStatus button.
This function sets the Utilities.projectSiteCode variable by retrieving the project code that is stored
in the site property bag. This function is self-invoking, and so runs as soon as the app starts.
2. Locate the following comment // TODO: Add code to send the new post to SharePoint.
3. Add code to retrieve content from the StatusText text area. You should store the value in a new
variable named userContent.
4. Add code to append the project site code to the userContent variable as a hashtag. Use the
Utilities.projectSiteCode property to retrieve the project site code.
5. Add code to declare a new variable named tags, and initialize it as a new array.
7. Add code to parse the userContent variable. The code should split the string into words, and then
replace any hashtags with a placeholder in the format {0}. You should create a new
SP.Social.SocialDataItem instance for each hashtag. You should add the SocialDataItem instance to
the tags array, and increment the tagCount variable to track the number of hashtags in the content.
When you replace the tag with a placeholder you should use the current value of tagCount as the
MCT USE ONLY. STUDENT USE PROHIBITED
13-26 Customizing the Social Workload
number in the placeholder. The result of your code should be an array of SocialDataItem objects and
a string variable that contains the manipulated post content.
8. Add an Ajax POST request that submits the post containing the hashtag items to the host web. Use
the Utilities.appWebUrl and Utilities.hostWebUrl properties to construct the REST endpoint
address.
10. Locate the following comment // TODO: Add code to update the feed after a post is successfully
added.
11. After the comment, add code to update the feed after the post is submitted successfully.
2. Use the app to send the message Sent from the app, and then verify that the newsfeed is updated
with the message, and that #P2822 has been appended to the end of the post.
3. View the newsfeed for the site by viewing the out-of-the-box newsfeed and verify that the post
appears correctly.
4. Close Internet Explorer.
Results: After completing this exercise, you should have added controls and code to an app part to
support posting a message to a newsfeed.
2. In the getSiteFeedSuccess function, add code to define a new variable named queryString, and
initialize it to "(ContentTypeId:0x01FD4FB0210AB50249908EAA47E6BD3CFE8B* OR
ContentTypeId:0x01FD59A0DF25F1E14AB882D2C87D4874CF84* OR
ContentTypeId:0x012002* OR ContentTypeId:0x0107* OR
WebTemplate=COMMUNITY)owstaxIdMetadataAllTagsInfo:" + Utilities.projectSiteCode
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 13-27
Note: The query string specifies that the search result must be a post on a My Site or
community site. The query string also states that the items must be tagged with the project site
code. You may find it easier to copy the query string from the solution code.
4. Add code to set the queryText property of the keywordQuery object to the queryString variable.
5. Add code to retrieve the sortList property of the keywordQuery object, and store it in a new
variable named sortList.
6. Add code to add a new entry to the sortList object. The new entry should specify that the results
should be sorted by the last modified date (LastModifiedTime), and should be in ascending order
(Microsoft,SharePoint.Client.Search.Query.SortDirection.Ascending).
7. Add code to set the enableSorting property of the keywordQuery object to true.
9. Add code to declare a new variable named results, and initialize it to the result of calling the
executeQuery function of the searchExecutor object by using the keywordQuery object as a
parameter.
10. Remove the existing call to the Display.updateDisplay function from the getSiteFeedSuccess
function.
11. Add code to call the executeQueryAsync function of the Utilities.clientContext object. The
function should set the Contoso.NewsfeedApp.searchResults property to the search results from
the results.m_value.ResultTables[0].ResultRows property. It should then set the
Contoso.NewsfeedApp.feedPosts property to the feedPosts property. Finally, it should invoke the
Display.updateDisplay function. If the request fails, the call should display an error message in an
alert window.
In the updateDisplay function, data from both the newsfeed and search results are merged. Because
the results from the search service are not in the same format as the posts from the current site, the
updateDisplay function uses a utility function named getActorInfo to retrieve missing information
about the post author.
3. Review the code in the addToFeed function. In this function, individual posts are parsed and HTML
markup added to a variable for display on the page.
4. Locate the following comment // TODO: Add code to retrieve the actor for the specified account.
5. Add code to make an Ajax GET request to retrieve the actor information for the user account passed
as a parameter to the function. You should specify that the request should run synchronously, and
you should display the error message in an alert box if the request fails.
MCT USE ONLY. STUDENT USE PROHIBITED
13-28 Customizing the Social Workload
2. Add the app part to the top section of the project site home page.
3. Verify that the feed now includes a message from Pat Coleman asking for help on a case study she is
producing. This post is from Pat’s My Site newsfeed.
Results: After completing this exercise, you should have modified the app part to display posts retrieved
by using the search service.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 13-29
Review Question(s)
Which of the following service applications is not commonly required when developing a
social app?
Site
Document
Post
User
Tag
Verify the correctness of the statement by placing a mark in the column to the right.
Statement Answer
Module 14
Monitoring and Troubleshooting Custom SharePoint
Solutions
Contents:
Module Overview 14-1
Module Overview
Like any coded solutions, Microsoft® SharePoint® 2013 apps and solutions may contain bugs from a
variety of sources. You should aim to identify and eliminate as many bugs as possible during the
development phase of your project. There are versatile tools to help you do this in both Microsoft Visual
Studio® and Internet Explorer® and you should incorporate debugging into your development workflow
early in the project. However, some bugs may make it through testing and only become apparent when
the solution or app is deployed. To diagnose these, you can use tracing techniques that log error details.
With these details, you can remove the bugs in subsequent versions. In addition to debugging techniques,
this module introduces methods that you can use to improve the performance and scalability of solutions
and apps.
Objectives
After completing this module, you will be able to:
Describe how to identify, diagnose, and remove bugs in SharePoint apps during development.
Describe how to record information about issues that arise in deployed SharePoint apps.
Describe how developers optimize the performance of SharePoint apps by implementing best
practices, measuring performance, and load testing.
MCT USE ONLY. STUDENT USE PROHIBITED
14-2 Monitoring and Troubleshooting Custom SharePoint Solutions
Lesson 1
Debugging SharePoint Apps in Visual Studio
In the perfect scenario, all bugs are removed during the development of a project and the resulting
solutions work precisely as designed in the production environment. By incorporating the Visual Studio
and Internet Explorer debugging tools into your development processes, and by enforcing a strict testing
regime, you can approach this ideal and produce high-quality software. In this lesson, you will see how to
use these debugging tools and how to debug code in the unique architecture used by SharePoint apps.
Lesson Objectives
After completing this lesson, you will be able to:
Configure a SharePoint site for debugging code during the development of SharePoint solutions and
SharePoint-hosted apps.
Configure a remote web for debugging code during the development of cloud-hosted apps.
Use Visual Studio and Internet Explorer to debug JavaScript code in SharePoint apps.
The Call Stack Window. This window shows all the current calls in the call stack. This can be extremely
helpful when there are many methods in different code files executing simultaneously.
The IntelliTrace® window. The IntelliTrace window shows the current event and previous events that
occurred in the application. By selecting a previous event, you can examine not only the state of the
application when the error occurred, but also the state of the application at earlier times. This enables
you to trace an exception back to the event where unexpected behavior began.
In order to use debugging mode, the application must be compiled with debugging symbols in the
assembly. These symbols are included whenever you compile in the Debug configuration. If you choose
the Release configuration, execution cannot stop for debugging.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 14-3
In debugging mode, execution also stops when Visual Studio reaches a line in the code where you have
set a break point. This enables you to focus on an event earlier than the one that caused the exception.
You can also use a break point to ensure that the application behaves as expected when there is no
exception. When the code is halted, you can step through lines of code one-by-one to examine the state
of the application and how it changed.
Best Practice: You should enable debugging only in development, testing, and staging
sites. Never enable debugging in production sites, because debugging information can help
malicious users to find out about your configuration and software. This may enable those users to
mount an effective attack against your site.
When you start a web application in debugging mode for the first time, Visual Studio may ask whether
you want to enable debugging in the web site. If you answer yes, the debug attribute is set to true for
you.
In addition to enabling debugging, you can obtain additional information about errors by disabling
custom errors in the customErrors element, and configuring SharePoint to display the full call stack for
errors by using the SafeMode element. To disable custom error pages, set the mode attribute of the
customErrors element to Off. To enable full call stack information, set the CallStack attribute of the
SafeMode element to true.
When you develop an app in Visual Studio 2012, you must select a debugging site based on the
Developer Site template. If you do not select such a site, you will receive the following error when you
start the app in debugging mode: "Sideloading of apps is not enabled on this site". If this situation arises,
you can resolve it by enabling the Developer Site collection feature. However, the Developer Site
collection feature is a hidden feature, so you must use PowerShell to enable it.
The following code shows how to enable the Developer site collection feature:
In a production environment, JavaScript files should be as small as possible to ensure that they download
rapidly. This is particularly important in large JavaScript libraries such as jQuery or the core SharePoint
libraries. For each of these libraries, two versions are available:
Development Version. This version is human-readable and includes white space and helpful variable
names. In jQuery, the development version of the library is named jquery.js. SharePoint development
libraries have the suffix .debug.js.
Minimized Version. This version is not easy to read because white space has been removed and
variables have short, non-descriptive names. In jQuery, the minimized version of the library is named
jquery.min.js. SharePoint minimized libraries have no .debug in the suffix.
During the development, testing, and staging phases of a project, make sure that you link to the
development version of each JavaScript library. The structure and variable names in these versions make
debugging easier and make mistakes obvious.
Best Practice: Make sure all developers realize that they should switch to minimized
versions of all the JavaScript libraries just before the project is deployed. In addition, you should
bundle custom JavaScript into larger libraries to improve performance.
The Internet Explorer debugger enables you to explore any of the JavaScript files linked to by the
currently loaded page and to set break points. There are Call Stack, Locals, and Watch windows that
enable you to examine the state of the application.
Demonstration Steps
In the App.js file, insert a breakpoint on the call to the getTaxonomySession() function.
1. Start the app in debug mode, and trust the app.
Note: Visual Studio enters break mode at the break point you specified.
2. Point out that all the JavaScript files used by the app have been added to the Script Documents
folder. Click some script documents and examine the code within students.
3. Step into the executing code four times. Point out that the debugger steps into code in the
SP.Taxonomy.js file and then sp.runtime.debug.js file.
4. Stop debugging.
5. Start the app without debugging. Point out that the breakpoint is not hit, because the Visual Studio
debugger is not running.
7. Start the Profiler, refresh the page in Internet Explorer, and then stop the Profiler.
8. In the list of functions, locate the line for the loadTermStore function. Point out how long the
function took to complete.
When you call REST APIs, responses are returned in XML or JSON formats. These are text formats that
JavaScript code can easily de-serialize in order to create objects with easy-to-access properties, collections
and so forth. However, because these responses can be large and complex, it can be hard to diagnose
when a REST call returns something unexpected. In such circumstances, you may cause exceptions, for
example by coding against a property that has not been returned.
It is therefore helpful to be able to debug your app by examining XML and JSON responses from REST
calls.
To determine what properties to expect from a REST request, use the JavaScript Client Side Object Model
(CSOM) reference documentation. Because the JavaScript CSOM is built on the REST API, the properties
returned by a REST call match those of the corresponding object in the CSOM. For example, a request to
an URL like http://dev.contoso.com/_api/web returns the same properties as the SP.Web object in the
JavaScript CSOM.
Because Fiddler includes interpreters for XML and JSON, it is an ideal tool to use to examine REST requests
and responses as you debug a SharePoint cloud-hosted app. To examine a request made by your app,
complete the following steps:
1. Start the app and navigate to the page, button, or action that you want to test in Internet Explorer.
2. Start Fiddler. Fiddler automatically connects to all the current Internet Explorer web server sessions.
The first session in the list is a request to check for Fiddler updates.
3. Click the button, reload the page, or initiate whatever action you wish to test in Internet Explorer.
4. When the action is complete, switch to Fiddler. You will see one session for every request and
response in the list on the left.
5. Select a session. Fiddler displays the request details in the top right and the response details in the
bottom right.
6. Select a view. For example, if the request headers specified JSON, select the JSON viewer to see the
response from the server.
Fiddler
http://go.microsoft.com/fwlink/?LinkId=154773
The remote web runs in IIS Express or the Visual Studio Development Server on the developer's
computer.
In this scenario, SharePoint may not be able to reach the WCF service because it is not in the location
specified in the Element.xml file.
To configure a Windows Azure Service Bus for remote event debugging, complete the following steps:
1. Register for a Windows Azure account.
2. Create a new service bus. A service bus requires you to create a unique name and select a region
close to you.
3. Copy the connection string from the properties of the new service bus.
7. Paste the connection string into the Windows Azure Service Bus connection string box.
Lesson 2
Diagnosing Faults in Deployed Apps
In a perfect world, all bugs would be identified and removed before the app is deployed to the
production environment. In practice, this is rarely achieved and complex situations, which are difficult to
properly simulate during testing, may result in users experiencing exceptions. When such exceptions
occur, it is helpful to have access to as much information about the exception as possible so that you can
diagnose the problem, code a solution, and deploy a new version as quickly as possible. In this lesson, you
will see how to arrange for an app to record much more information than you could obtain from the user.
Lesson Objectives
After completing this lesson, you will be able to:
Enable the user to switch on IIS tracing to collect information about an exception.
Add profiling packages from the NuGet package manager and use them to record an app's behavior.
3. Click DETAILS.
Under Errors, the app monitoring user interface displays the numbers of installation errors and upgrade
errors. It also displays the number of runtime errors in the last four days. If the user clicks on the number
of runtime errors, details of each error are displayed. The following values are included:
The following code illustrates how to use the logCustomAppError() method to log an exception in a
SharePoint-hosted app:
try
{
//Place the operation that may cause an exception in a try block
}
catch (Exception e)
{
//Log the exception in the corresponding catch block
SP.Utilities.Utility.logCustomAppError(context, "The operation caused an exception.
The details were: "
+ e.Message);
}
IIS Tracing
The ASP.NET processing pipeline includes a tracing
facility that can record rich information about every
page. This information includes pages that load and
execute without exceptions, as well as pages that
cause problems. Developers can also use the
System.Diagnostics.Trace.Write() method to
record custom information. You can access the
trace logs through the trace.axd file.
Start by adding a <trace> element to the web.config file. The following code illustrates how to do this:
Notice that the above XML disables tracing by default, but configures values such as the trace mode and
the request limit.
Next, create code that enables tracing. The following code, for example, may run when the user clicks an
Enable Tracing button in the app user interface:
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 14-11
Enabling Tracing in C#
//Get the current ASP.NET config
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
Best Practice: Make sure to provide the user with a second button or other method to
disable tracing when diagnostic information has been recorded.
To enable the user to view trace logs, link to the trace.axd page, as in the following HTML example:
Linking to trace.axd
<a href="~/trace.axd" target="traceinfo">View The Trace Log</a>
If a user experiences a persistent problem, have them complete the following steps to provide full
diagnostic information:
1. Enable tracing.
3. Disable tracing.
5. Copy and paste the trace log into an email or other communication and send it to you.
NuGet Client Tools. The client tools enable developers to both create NuGet packages and install
NuGet packages to use them in a Visual Studio project.
NuGet Gallery. The gallery is a repository of third-party NuGet packages. There are more than 15,000
packages currently available in the library for many purposes.
MCT USE ONLY. STUDENT USE PROHIBITED
14-12 Monitoring and Troubleshooting Custom SharePoint Solutions
A new get package is a single file with a .nupkg extension. All files that the package adds to a Visual
Studio project are bundled into this file, together with a manifest file that Visual Studio uses to install or
remove the package.
ELMAH
ELMAH is a popular error-logging package that you can add to your app to record unhandled exceptions.
ELMAH stands for Error Logging Modules and Handlers, and it consists of ASP.NET modules and handlers
that intercept exceptions. ELMAH does not modify error handling in your app; users see either a standard
ASP.NET error page or a custom page (if you have implemented one). ELMAH records exception numbers,
messages, and other details to create a log that you can use to assess the health of your app and to
diagnose any faults or bugs.
ELMAH intercepts errors by using the ASP.NET HttpApplication.Error event. Any errors that are caught
and gracefully handled, for example in catch blocks, do not reach ELMAH. If the code calls the
Server.ClearError() method, the exception does not reach ELMAH. ELMAH can only record unhandled
exceptions.
You configure ELMAH in the web.config file, and you can instruct it to log exception information to a SQL
Server® database or other locations.
To view the exception logs, ELMAH adds the /elmah/default.aspx page to your project. This displays a list
of all exceptions. For each exception you can view a details page that shows trace information, error
numbers, and messages. Administrators and developers can also subscribe to an RSS feed that alerts them
about new exceptions as they arise. You can read more information about ELMAH and browse the project
WIKI at the following location:
ELMAH Project
http:/go.microsoft.com/fwlink/?LinkId=321983
MiniProfiler
MiniProfiler is a NuGet package that can profile the behavior and performance of an ASP.NET application,
including a SharePoint cloud-hosted app. Because you have granular control over which operations are
recorded, you can use MiniProfiler in a production environment, where other profiling packages may
negatively affect performance. The information MiniProfiler displays can include all the methods called to
render a page and their timings. This information can be extremely helpful in diagnosing bugs in
deployed ASP.NET apps.
An important advantage of MiniProfiler is that you can run checks against the ASP.NET request before
starting the profiler. For example, you could run the profiler only when the request is from a local browser,
when the request is from an administrator, or when the request includes a certain parameter in the query
string.
In the following ASP.NET example, MiniProfiler is enabled only when the query string includes
"Profile=true":
{
//Make sure you stop the profiler as early as possible to reduce the performance
impact
MiniProfiler.Stop();
}
When MiniProfiler is enabled, it adds a link to each profiled page that displays performance information.
You can find more information about using MiniProfiler at the following location:
MiniProfiler
http://go.microsoft.com/fwlink/?LinkId=321984
Server info. This tab displays general information about the request, such as the start time, duration,
CPU time, memory, and correlation ID associated with the request.
Scopes. This tab provides a breakdown of how long the request spends at each point in the call stack.
SQL. This tab provides details of any database calls made during the processing of the request.
SPRequests. This tab provides details of any background requests that occurred in addition to the
page request.
Asserts. This tab identifies any assert calls made during the request. Assert calls are used by
developers to write details of unexpected conditions to an output window.
Service Calls. This tab provides details of any calls to web services made during the request.
ULS. This tab contains all the trace log entries associated with the current request.
Cache Calls. This tab provides details of any cache calls made during the request.
Note: In addition to the base functionality, you can now extend the developer dashboard
by injecting custom JavaScript code into the developer dashboard.
To access the developer dashboard, you must first enable it. You use PowerShell to enable the developer
dashboard on a farm-wide basis.
MCT USE ONLY. STUDENT USE PROHIBITED
14-14 Monitoring and Troubleshooting Custom SharePoint Solutions
The following code sample shows how to enable the developer dashboard for a SharePoint farm by using
PowerShell cmdlets:
After you have enabled the developer dashboard, you can open it from any SharePoint page. SharePoint
will add a Launch the Developer Dashboard button to the ribbon on each page while the dashboard is
enabled.
The following code sample shows how to disable the developer dashboard for a SharePoint farm by using
PowerShell cmdlets:
Lesson 3
Testing Performance and Scalability
The SharePoint app architecture is by its nature highly scalable because much of the code runs on the
client side, as JavaScript executed by the browser. Such a design reduces the likelihood of contention for
server memory and processing resources. However, even with such a scalable architecture, your code may
still be slow to execute for many reasons that are not obvious at design time. In this lesson, you will learn
how to investigate the behavior and performance of a SharePoint app, remove bottlenecks, and assess the
limits on its scalability.
Lesson Objectives
After completing this lesson, you will be able to:
List the boundary and supported limits for scaling apps in SharePoint 2013.
Maximum
Limit Type Notes
Value
Number of apps in the Boundary 2,000 If you exceed this number of apps, you
Manage Licenses page can manage licenses in the Site Contents
page of a site where a user has installed
the app.
Number of app Supported 1,000,000 If you purchase more than 1,000,000 total
Licenses in a single licenses for all the apps in a tenancy, you
tenancy may cause a severe reduction in
performance.
Number of apps Boundary 240 If there are more than 240 apps available
displayed in the Add an for installation in a site, a message shows
App page that you can use the search tool to locate
an app for installation.
MCT USE ONLY. STUDENT USE PROHIBITED
14-16 Monitoring and Troubleshooting Custom SharePoint Solutions
Maximum
Limit Type Notes
Value
Number of app licenses Boundary 2,000 If managers assign more than 2,000 app
that a single user can licenses to a single SharePoint user, that
view user will not see any apps in the Add an
App view. Instead the user will be directed
to search for apps.
Number of apps that a Boundary 500 If there are more than 500 apps available
user can see in the for a user to install, that user will not see
corporate catalog any apps in the corporate catalog. Instead
the user will be directed to search for
apps.
The above limits generally restrict the scalability of apps, but note that none of these limits affects a single
app. If you design an app or a set of apps carefully, you should not reach the limits described or cause any
of your customers to reach these limits.
To learn about all the published boundaries and supported limits for SharePoint 2013, see the following
location:
For the purposes of analyzing performance, two tools are especially helpful:
Profiler. To use the Profiler tool, click Start profiling and then refresh the page, click a button, or use
some other method to trigger the action you want to investigate. When the action is complete, click
Stop profiling. The view shows a list of every JavaScript function that was called while you were
profiling. For each function, you can also see how many times it executed and the time it took to
complete. You can use these timings to spot slow functions.
Network. To use the Network tool, click Start capturing and then refresh the page, click a button, or
use some other method to trigger the action you want to investigate. When the action is complete,
click Stop capturing. The view shows a list of every network call made while you were capturing. This
includes requests for HTML pages and CSS style sheets, images and other files, and JavaScript calls
(for example, calls to web services). For each request, you can see the URL, HTTP method, result code,
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 14-17
and type of content. You can also see how long the request took to receive a response. The Timings
column shows how long it took to receive all the response data.
Fiddler
You have already seen that the Fiddler web debugging tool can help to investigate an app's REST calls
and XML or JSON responses. It also has features that can be used to profile app performance and spot
bottlenecks. These features include:
The Statistics Tab. This tab shows summary statistics for all the selected sessions. This summary
information includes the total number of web requests, the number of bytes sent and received,
timings, DNS lookup performance, and response codes.
Custom Rules. In Fiddler, rules are used to highlight sessions that match certain criteria. You can
create custom rules to, for example, display sessions in red with large responses. Such sessions may
result in slow page load times.
The Timeline. The timeline shows the start time and duration of every selected session. The sessions
are shown in a waterfall display with time increasing to the right. This display makes slow sessions
obvious, and also highlights closed connections and instances where connection limits prevented
sessions from starting.
Note: The performance analysis tools in Internet Explorer and Fiddler are designed to work
with HTTP, HTML, CSS, and JavaScript. They cannot profile or analyze server-side .NET managed
code such as C# code in ASP.NET Web Forms in a cloud-hosted app. To analyze server-side code,
you must use Visual Studio.
Command Line Profiling Tools. The command line profiling tools enable you to configure profiling
sessions by issuing commands at the prompt. You can also create a script that configures profiling.
Performance Explorer. After a profiling session has been run, reports are displayed in the Performance
Explorer window.
Web Performance and Load Tests. Web Performance and Load Tests are a set of tools designed to
enable developers to test how their app handles realistic loads and stress tests. You can record a set
of user actions and then replay those actions many times in order to simulate the kind of load that
may occur in the production environment.
Note: Web Performance and Load Tests is a set of tools that is only available in Visual
Studio Ultimate edition.
MCT USE ONLY. STUDENT USE PROHIBITED
14-18 Monitoring and Troubleshooting Custom SharePoint Solutions
Profiling an App
In application development, profiling is the process
of observing and recording the performance of a
solution as it runs. You can perform profiling at
every stage of development, but it is often done
late in a project, as an application approaches
completion. Profiling ensures that the application
behaves as designed, has optimal performance, and
responds to users as quickly as possible. You can
use profiling to identify problems such as the
following:
Bottlenecks. Bottlenecks are segments of code that limit the performance of the application as a
whole. By identifying bottlenecks, you determine where optimizations make the most difference to
the performance experienced by the user.
Unintended Calls. When you use many APIs or multiple JavaScript libraries, it can be difficult to fully
understand all method calls as you write the code. By profiling the application, you can observe all
method calls and diagnose those that are unnecessary and can be improved by selecting other
methods.
Profiling Methods
In Visual Studio, to profile an application such as a SharePoint app, you first create and configure a
profiling session. You can then run the session and view reports that show how the application behaved.
When you configure the profiling session, you specify the aspects of behavior that interest you. You can
select from the following profiling methods:
Sampling. This method interrupts the CPU at fixed intervals and collects information about the
current call stack. This method is useful for initial investigations and for observing the load your app
places on the CPU. The method has a relatively small impact on the performance of the app.
Instrumentation. This method adds code into your app's binary files to collect detailed timing
information for each function call. This method is particularly useful for identifying bottlenecks.
Concurrency. This method collects information about multiple threads in the app and how they
contend for resources such as CPU time. Contention is a common cause of bottlenecks because
threads are forced to wait for access to memory or processing time.
.NET Memory. This method interrupts the CPU whenever a .NET object is assigned to memory. The
method also interrupts the CPU during garbage collection, when unused objects are removed from
memory. You can use this method to study memory use in detail.
Tier Interaction. In a SharePoint app, you can use this method to collect information about the calls
between ASP.NET server-side code and the database.
Profiling Process
To profile an app by using Visual Studio, you must complete the following steps:
Configure a Profiling Session. You can use the Performance Wizard or the command line profiling
tools to configure a session. You must specify the profiling methods that you want to execute and
select the binary files that you want to target.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 14-19
Launch the Profiling Session and Perform Actions. When you start the profiling session, Visual Studio
compiles and launches the app. You must takes actions such as clicking links, buttons, uploading
documents, and taking whatever other actions you want to test. When you close the app, Visual
Studio saves the profiling data in a Sample Profiling Report.
Investigate the Profiled Data. You can view summary and detailed information from the profiling
session in the Performance Explorer window.
Data in Performance Explorer may help you to identify hotspots, bottlenecks, and other performance
problems in your code. It is important to take an iterative approach. That is, after you have edited the app
to remove a bottleneck, rerun the performance session to observe the difference you have made.
Stress testing requires many assumptions about users. For example, it is difficult to precisely predict the
actions a user will take in a typical session. For this reason, you should regard stress-testing results as
approximations of real-world scenarios. Nevertheless, stress testing results are extremely useful, especially
before you have any real-world deployments of you app to measure.
1. Record web performance tests. A web performance test is a recorded set of actions. Usually such a test
records the steps a single user takes to perform a simple task. For example, you may record a web
performance test in which a user creates a new SharePoint item by using your app. You should record
web performance tests for each common function of an app.
2. Configure a load test. During a load test, one or more web performance tests are executed by Visual
Studio multiple times simultaneously in order to simulate the load generated by many concurrent
users in a real deployment. To configure load tests, you choose the web performance tests to run and
specify the number of users to simulate, together with other parameters.
MCT USE ONLY. STUDENT USE PROHIBITED
14-20 Monitoring and Troubleshooting Custom SharePoint Solutions
3. Execute a load test. When your load test configuration is complete, you can use Visual Studio to run
the simulation and execute the web performance tests.
4. Analyze load test results. Visual Studio includes the Web Performance Test Results Viewer, which you
can use to view statistics about a single instance of a web performance test, whether that test was run
individually or as part of a load test. To analyze data that summarizes the load test as a whole, use the
Load Test Analyzer tool
In order to increase your confidence in the accuracy of web performance tests, you can define two types
of rules:
Validation Rules. Validation rules check the existence of text, HTML tags, and HTML attributes in the
page returned by a web request. For example, when your web performance test requests a SharePoint
item, you could define a validation rule to check that the returned page included a <div> tag with
the ID "Title".
Extraction Rules. Extraction rules check that values are present in form fields and query strings
parameters. For example, you could define an extraction rule that checked an item's GUID.
For more information about stress testing SharePoint apps by using Visual Studio Ultimate, see:
Web Performance and Load Testing SharePoint 2010 and 2013 Applications
http://go.microsoft.com/fwlink/?LinkId=322150
Identification of a Bug
You have deployed your provider-hosted app. All is running smoothly, but occasionally users complain of
an error message. You are unable to replicate this error message. How can you obtain more information
about the error?
Optimization of a Procedure
You add JavaScript code to your provider-hosted app that calls a third-party web service to obtain
industry news stories. You notice a reduction in performance of the app. You want to determine whether
the slow performance is due to your new code or to some other problem.
MCT USE ONLY. STUDENT USE PROHIBITED
14-22 Monitoring and Troubleshooting Custom SharePoint Solutions
Objectives
After completing this lab, you will be able to:
Create a diagnostic tools page on which users can enable and disable tracing.
Lab Setup
Estimated Time: 45 minutes
Password: Pa$$w0rd
A warm-up script named WarmUp.ps1 runs automatically when you start the virtual machine. This script
helps to improve the performance of the virtual machine by downloading the home page of the root site
in each site collection on the server. Occasionally this script displays timeout errors; you can ignore these
errors. You should ensure this script has finished running before you start the lab.
2. Add a new method to the HomeController class in the Controllers\HomeController.cs code file.
Use the following information:
o Scope: public
o Name: Diagnostics
3. In the new Diagnostics method, return a View named Diagnostics.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 14-23
o Folder: Views/Home
Note: The app displays the Diagnostics view, but there is no content other than the title.
1. Edit Web.config
2. Insert a new <trace> element within the <system.web> element. Use the following information:
o Enabled: false
o Local Only: false
2. From the currentConfig object, get the trace section and store it in a new TraceSection object
named traceSection.
3. Store the value of the traceSection.Enabled property in a new ViewBag property named
TracingStatus.
4. In the Diagnostics.cshtml view, add a Razor if…else code block that checks the
ViewBag.TracingStatus property.
5. If ViewBag.TracingStatus is true, display a <p> element that tells the user that tracing is enabled.
6. If ViewBag.TracingStatus is false, display a <p> element that tells the user that tracing is disabled.
o Scope: public
o Return type: ActionResult
o Name: ToggleTracing
3. From the currentConfig object, get the trace section and store it in a new TraceSection object
named traceSection.
6. Store the value of the switchOn property in a new ViewBag property named TracingStatus.
7. Return the Diagnostics view.
o Helper: Html.ActionLink()
o Controller: Home
o switchOn: false
2. After the Switch Off Tracing link, render a link to the ~/trace.axd page.
3. If the tracing status is disabled, render a link that enables users to switch on tracing. Use the following
information:
o Helper: Html.ActionLink()
o Link Text: Switch On Tracing
o Controller: Home
o switchOn: true
1. Enable Tracing
MCT USE ONLY. STUDENT USE PROHIBITED
14-26 Monitoring and Troubleshooting Custom SharePoint Solutions
o Miles: 100
3. For the POST request for the MileageClaim/Create address, record the value of the ReasonForTrip
parameter.
Results: A SharePoint auto-hosted app in which users can enable tracing and view tracing logs to supply
information about bugs and other issues.
Question: In Exercise 2, Task 1, you added a new <trace> element to the web.config file
with the enabled attribute set to false. Why is it necessary to create this element, when code
in the ToggleTracing action sets the enabled attribute to true?
Question: What are the consequences of leaving tracing enabled after you have diagnosed a
bug?
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft SharePoint Server 2013 Advanced Solutions 14-27
Best Practice: Use debugging JavaScript libraries when you want to browse and step
through the code in those libraries. For production environments, switch to minimized JavaScript
libraries to ensure that the app downloads to the browser as fast as possible.
Review Question(s)
Question: You want make recommendations for the server hardware necessary to run a
SharePoint remote-hosted app. You expect several thousand concurrent users at peak times.
Should you use profiling or stress testing to determine appropriate hardware?
Verify the correctness of the statement by placing a mark in the column to the right.
Statement Answer
Course Evaluation
Your evaluation of this course will help Microsoft understand the quality of your learning experience.
Please work with your training provider to access the course evaluation form.
Microsoft will keep your answers to this survey private and confidential and will use your responses to
improve your future learning experience. Your open and honest feedback is valuable and appreciated.
MCT USE ONLY. STUDENT USE PROHIBITED
L1-1
3. On the Windows Start page, type Visual Studio, and then click Visual Studio 2012.
5. In the New Project dialog box, in the navigation pane, expand Visual C#, expand
Office/SharePoint, and then click Apps.
9. In the New app for SharePoint dialog box, under What is the name of your app for SharePoint,
type SharePoint Health Scores.
10. Under What SharePoint site do you want to use for debugging your app, type
http://dev.contoso.com.
11. In the How do you want to host your app for SharePoint list, click SharePoint-hosted, and then
click Finish.
2. In the Add New Item - SharePointHealthScores dialog box, click Client Web Part (Host Web).
4. In the Create Client Web Part dialog box, ensure Create a new client web part page is selected,
and then click Finish.
6. In the ClientWebPart element, change the value of the Title attribute to SharePoint Health Scores.
7. Change the value of the Description attribute to Displays the current health score for the
SharePoint web application.
3. In Solution Explorer, right-click the SharePointHealthScores project node, point to Add, and then
click New Item.
6. In Solution Explorer, under SiteAssets, right-click Sample.txt, and then click Delete.
7. In the Microsoft Visual Studio dialog box, click OK.
8. In Solution Explorer, right-click SiteAssets, point to Add, and then click Existing Item.
10. In Solution Explorer, right-click SiteAssets, point to Add, and then click New Folder.
2. Immediately below the title element, on a new line, add the following code:
4. Immediately below the code you just located, on a new line, add the following code:
5. Within the body element, on a new line, add the following code:
<p id="healthPara">Click Start Polling to poll the server for health scores.</p>
<div id="healthBar"></div>
<br />
<button>Start Polling</button>
<button>Stop Polling</button>
2. In the Add New Item - SharePointHealthScores dialog box, in the navigation pane, under Visual
C# Items, click Web.
'use strict';
MCT USE ONLY. STUDENT USE PROHIBITED
L1-3
$(document).ready(function () {
$('button').button();
$('#healthBar').progressbar({
max: 10,
value: 5
});
$('#healthPara').text("Current health score: 5");
});
Note: The code you just added displays a progress bar with a static value. This enables
you to ensure that your app part is configured correctly before you add custom logic.
9. Immediately below the final closing script tag, on a new line, add the following code:
2. If you are prompted for credentials, log in as CONTOSO\Administrator with password Pa$$w0rd.
3. In Internet Explorer, when the page has finished loading, click Contoso Development Site.
4. On the Contoso Development Site home page, on the ribbon, click EDIT.
5. On the Get started with Apps for Office and SharePoint web part, click REMOVE THIS.
6. Click inside the content area above the Apps in Testing web part, and then on the ribbon, on the
INSERT tab, click App Part.
7. In the Parts list, click SharePoint Health Scores, and then click Add.
8. On the ribbon, click SAVE.
Results: After completing this exercise, you should have created, configured, and deployed an app part.
MCT USE ONLY. STUDENT USE PROHIBITED
L1-4 Developing Microsoft SharePoint Server 2013 Advanced Solutions
'use strict';
Contoso.HealthScores = function () {
}();
5. On a new line between the curly braces you just added, add the following code:
$('button').button();
var healthScore;
var pollInterval;
6. Immediately below the code you just added, on a new line, add the following code:
2. Locate the button element with a value of Start Polling, and edit the element as follows:
3. Locate the button element with a value of Stop Polling, and edit the element as follows:
2. If you are prompted for credentials, log in as CONTOSO\Administrator with password Pa$$w0rd.
3. In Internet Explorer, when the page has finished loading, click Contoso Development Site.
4. On the Contoso Development Site home page, on the SharePoint Health Scores web part, click
Start Polling.
5. Verify that the web part displays a server health score and a progress bar indicator.
Note: The health score is likely to remain static at 0 at this point, as the server is under very little
load.
6. Without closing Internet Explorer, open a File Explorer window and browse to E:\Labfiles\Starter.
Note: If the PowerShell window displays an Execution Policy Change message, type Y,
and then press Enter.
MCT USE ONLY. STUDENT USE PROHIBITED
L1-6 Developing Microsoft SharePoint Server 2013 Advanced Solutions
8. Switch back to Internet Explorer, and verify that the web part displays an increased server health
score.
Note: It may take several seconds before the increase in load is reflected by the health score.
9. Click Stop Polling, and verify that the progress bar is removed from the web part.
Results: After completing this exercise, you should have configured an app part to poll the server for
health scores.
MCT USE ONLY. STUDENT USE PROHIBITED
L2-1
5. In the New Project dialog box, under Templates, expand Visual C#, expand Office/SharePoint, and
then click Apps.
9. In the Project Location dialog box, browse to E:\Labfiles\Starter, and then click Select Folder.
12. In the What SharePoint site do you want to use for debugging your app box, type
http://dev.contoso.com.
13. In the How do you want to host your app for SharePoint list, click SharePoint-hosted, and then
click Finish.
3. In the How do you want to open this type of file (.txt)? dialog box, click Notepad.
7. In the Default.aspx file, delete everything between the <div> tag and the </div> tag.
8. Place the cursor between the two div tags, and then on the Edit menu, click Paste.
12. In Solution Explorer, right-click Scripts, point to Add, and then click Existing Item.
MCT USE ONLY. STUDENT USE PROHIBITED
L2-2 Developing Microsoft SharePoint Server 2013 Advanced Solutions
13. In the Add Existing Item - CorporateStructureApp dialog box, browse to E:\Labfiles\Starting
Code.
2. Immediately after the located code, on a new line, insert the following line of code:
3. In the list of permissions, click the empty cell in the Scope column, and then click Taxonomy.
4. Click the empty cell in the Permission column, and then click Write.
5. In the list of permissions, click the empty cell in the Scope column, and then click Web.
6. Click the empty cell in the Permission column, and then click FullControl.
Results: A new SharePoint hosted app with a JavaScript framework, user interface, and JavaScript library
links is completed.
taxonomySession = SP.Taxonomy.TaxonomySession.getTaxonomySession(context);
4. Press Enter.
6. Press Enter.
MCT USE ONLY. STUDENT USE PROHIBITED
L2-3
context.load(taxonomySession);
context.load(termStore);
8. Press Enter.
context.executeQueryAsync(
function () {
},
function (sender, args) {
});
10. Place the cursor in the first of the two anonymous functions.
checkGroups();
14. Place the cursor in the second of the two anonymous functions.
3. Place the cursor within the checkGroups function you just created.
5. Press Enter.
context.load(groups);
7. Press Enter.
MCT USE ONLY. STUDENT USE PROHIBITED
L2-4 Developing Microsoft SharePoint Server 2013 Advanced Solutions
context.executeQueryAsync(
function () {
},
function (sender, args) {
});
9. Place the cursor within the first of the two anonymous functions, and type the following code:
$("#groups-list").children().remove();
while (groupEnum.moveNext()) {
}
14. Place the cursor in the while loop you just created.
groupDiv.appendChild(document.createTextNode(currentGroup.get_name()));
$("#groups-list").append(groupDiv);
24. Place the cursor within the second of the two anonymous functions.
29. In the Windows Security dialog box, in the User name box, type Administrator.
30. In the Password box, type Pa$$w0rd, and then click OK.
31. On the Do you trust Corporate Structure App page, click Trust it.
32. When the page loads, under Existing Groups, verify that the app displays the text System.
Results: A SharePoint-hosted app that can display groups from the Managed Metadata service
application.
3. Press Enter.
5. Press Enter.
6. Type the following code:
context.load(corporateGroup);
7. Press Enter.
9. Press Enter.
context.load(corporateTermSet);
context.executeQueryAsync(function () {
}, function (sender, args) {
});
13. Place the cursor in the first of the two anonymous functions.
createTerms();
17. Place the cursor in the second of the two anonymous functions.
18. Type the following code:
$("#status-message").text("Creating terms…");
5. Press Enter.
7. Press Enter.
context.load(hrTerm);
9. Press Enter.
context.load(salesTerm);
context.load(technicalTerm);
context.load(engineeringTerm);
context.load(softwareTerm);
context.load(supportTerm);
context.executeQueryAsync(
function () {
},
function (sender, args) {
});
31. Place the cursor within the first of the two anonymous functions.
$("#status-message").text("Terms created.");
checkGroups();
35. Place the cursor within the second of the two anonymous functions.
2. In the Windows Security dialog box, in the User name box, type Administrator.
3. In the Password box, type Pa$$w0rd, and then click OK.
4. In Internet Explorer, on the Do you trust Corporate Structure App? page, click Trust It.
5. In the Windows Security dialog box, in the User name box, type Administrator.
6. In the Password box, type Pa$$w0rd, and then click OK.
7. In Internet Explorer, on the Page Title page, examine the taxonomy groups that already exist.
12. On the Windows Start page, type SharePoint, and then click SharePoint 2013 Central
Administration.
14. In the list of service applications, click Managed Metadata Service Application.
15. In the Taxonomy Term Store list, expand the Corporate Structure group.
Results: A SharePoint hosted app that can create a new group and a new empty term set in a term store.
MCT USE ONLY. STUDENT USE PROHIBITED
L2-10 Developing Microsoft SharePoint Server 2013 Advanced Solutions
3. In the How do you want to open this type of file (.sln)? dialog box, click Visual Studio 2012.
7. Press Enter.
9. Press Enter.
context.load(hostwebinfo);
context.executeQueryAsync(
function () {
},
function (sender, args) {
});
hostweb = context.get_site().openWebById(hostwebinfo.get_id());
3. Press Enter.
context.load(hostweb);
MCT USE ONLY. STUDENT USE PROHIBITED
L2-11
5. Press Enter.
context.executeQueryAsync(
function () {
},
function (sender, args) {
});
7. Place the cursor within the first of the two anonymous functions.
9. Press Enter.
addColumns();
11. Place the cursor within the second of the two anonymous functions.
12. Type the following code:
Results: A SharePoint app that has a reference to the host web in preparation for creating site columns in
the host web.
5. Press Enter.
7. Press Enter.
MCT USE ONLY. STUDENT USE PROHIBITED
L2-12 Developing Microsoft SharePoint Server 2013 Advanced Solutions
9. Press Enter.
context.load(noteField);
context.load(metaDataField);
context.executeQueryAsync(
function () {
},
function (sender, args) {
});
17. Place the cursor within the first of the two anonymous functions.
$("#status-message").text("Columns added.");
connectFieldToTermSet();
21. Place the cursor within the second of the two anonymous functions.
5. Press Enter.
7. Press Enter.
9. Press Enter.
context.load(metaDataTaxonomyField);
context.executeQueryAsync(
function () {
},
function (sender, args) {
});
13. Place the cursor within the first of the two anonymous functions.
metaDataTaxonomyField.set_sspId(sspID);
metaDataTaxonomyField.set_termSetId(corporateTermSetGUID);
metaDataTaxonomyField.update();
context.executeQueryAsync(
function () {
},
function (sender, args) {
});
21. Place the cursor within the first of the two anonymous functions.
MCT USE ONLY. STUDENT USE PROHIBITED
L2-14 Developing Microsoft SharePoint Server 2013 Advanced Solutions
23. Place the cursor within the second of the two anonymous functions.
3. In the Windows Security dialog box, in the User name box, type Administrator.
7. Locate the Custom Columns category and note the columns listed.
11. In the Password box, type Pa$$w0rd, and then click OK.
12. On the Do you trust Corporate Structure App? page, click Trust It.
13. In the Windows Security dialog box, in the User name box, type Administrator.
14. In the Password box, type Pa$$w0rd, and then click OK.
15. On the Page Title page, click Create Corporate Site Columns.
16. When the operations are complete, switch to the other instance of Internet Explorer.
18. Locate the Custom Columns category and note the presence of the Corporate Unit site column.
19. Click Corporate Unit.
20. Locate the Term Set Settings section, expand Managed Metadata Service Application Proxy, and
then expand Corporate Structure.
21. Note that the column is bound to the Contoso term set.
Results: A SharePoint-hosted app that can create site columns for metadata.
MCT USE ONLY. STUDENT USE PROHIBITED
L3-1
2. If you are not already logged on, log on to the LONDON machine as CONTOSO\Administrator with
password Pa$$w0rd.
3. On the Start screen, type Visual Studio, and then click Visual Studio 2012.
9. In the New app for SharePoint dialog box, in the What SharePoint site do you want to use for
debugging your app? box, type http://dev.contoso.com.
10. In the How do you want to host your app for SharePoint? list, click SharePoint-hosted and then
click Finish.
11. In the Default.aspx file, locate and delete the following code:
<div>
<p id="message">
<!-- The following content will be replaced with the user name when you
run the app - see App.js -->
initializing...
</p>
</div>
13. In Solution Explorer, expand the Scripts folder and then double-click the App.js file.
23. On the Permissions tab, click the Scope column of the first row, and then click Search.
26. Click the Permission column of the second row, and then click Read.
29. On the SearchApp page, in the search text box, type Contoso, and then click Go. You should see
results presented in the app web page. This may take one to two minutes.
Results: A new SharePoint App that uses Search REST API calls.
4. In the Create Custom Action for Menu Item dialog box, under Where do you want to expose the
custom action?, confirm that Host Web is selected.
5. In the Where is the custom action scoped to? list, ensure List Template is selected.
6. In the Which particular item is the custom action scoped to? list, click Document Library, and
then click Next.
7. In the What is the text on the menu item? box, type Search.
8. In the Where does the custom action navigate to? list, confirm that
SearchApp\Pages\Default.aspx is selected, and then click Finish.
9. In the open Elements.xml file, in the UrlAction element, change the value of the Url attribute to the
following:
~appWebUrl/Pages/Default.aspx?{StandardTokens}
&HostUrl={HostUrl}&Source={Source}
&ListURLDir={ListUrlDir}
&ListID={ListId}&ItemURL={ItemUrl}&ItemID={ItemId}
clientContext.executeQueryAsync(onListLoadSucceeded,
onRequestFailed);
});
function onListLoadSucceeded() {
title = currentItem.get_fieldValues().Title;
getSearchResults(title);
}
function onRequestFailed(sender, args) {
alert('Error:' + args.get_message());
}
18. You will test the menu item custom action in the next task.
2. On the Contoso Development Site page, in the Quick Launch menu, click Documents.
3. On the Documents page, on the Northwind Traders Contract row, click the ellipsis.
4. In the Northwind Traders Contract.docx dialog box, click the ellipses, and then click Search. You
will be redirected to the App web page and a search is performed based on the Title of the
document.
Note: At this point, the app is only designed to run only when a user clicks the custom action menu
item labeled Search. If you try to debug the app directly, you will see a JavaScript error because there is
no list item associated with the app. You must deploy the app and launch it from the Edit Control Block
on a document.
MCT USE ONLY. STUDENT USE PROHIBITED
L3-4 Developing Microsoft SharePoint Server 2013 Advanced Solutions
3. On the Windows Start page, type SharePoint, and then click SharePoint Designer 2013.
5. In the Open Site dialog box, in the Site name box, type http://search.contoso.com, and then click
Open.
6. In the Windows Security dialog box, in the User name box, type Administrator.
9. Click _catalogs, click masterpage, click Display Templates, and then click Search.
18. In the address bar, type http://search.contoso.com, and then press Enter.
25. On the ribbon, on the FILES tab, click Edit Properties. Note the Title is what you typed in the file
from above.
26. Under Target Control Type (Search), select all the check boxes, and then click Save.
27. Click Settings, and then click Site Settings.
MCT USE ONLY. STUDENT USE PROHIBITED
L4-2 Developing Microsoft SharePoint Server 2013 Advanced Solutions
29. On the Manage Result Types page, click New Result Type.
30. On the Add Result Type page, in the Give it a name box, type Tasks.
31. Click Show more conditions to expand the advanced conditions area.
32. In the Which custom properties should match? list, click ContentType.
34. In the What should these result look like? list, click Task Item, and then click Save.
37. SharePoint will display five results. Notice that there is no visual difference between the new display
template and the standard (out-of-the-box) display template.
Note: You will customize the Item Task display template in the next exercise.
Results: After completing this lab, you should have created a new result type and a new display template.
_#=ctx.RenderBody(ctx)=#_
<h3>
<img src="/_layouts/images/icon_tasklist.gif" style="padding-right:5px;border:0px"/>
Title: <a href='_#=ctx.CurrentItem.Path=#_'>_#=ctx.CurrentItem.Title=#_</a><br />
Assigned To: _#=ctx.CurrentItem.AssignedTo=#_<br />
</h3>
Note: You may notice that SharePoint Designer displays some schema errors in the HTML
file. You can safely ignore these errors.
8. On the Search page, in the text box, type Project, and then press Enter. Notice that the results use
your new display template.
MCT USE ONLY. STUDENT USE PROHIBITED
L4-3
Results: After completing this exercise, you should have customized an item display template.
4. Click _catalogs, click masterpage, click Display Templates, and then click Search.
15. Click _catalogs, click masterpage, click Display Templates, and then click Search.
<br/>
Modified: _#=ctx.CurrentItem.LastModifiedTime =#_
24. Move the mouse over one of the results. Notice that the hover panel appears, showing the Modify
date.
25. Close Internet Explorer, and then close SharePoint Designer 2013.
Results: After completing this exercise, you should have created a hover panel display template for your
custom Task result type.
MCT USE ONLY. STUDENT USE PROHIBITED
L4-5
2. If you are not already logged on, log on to the LONDON machine as CONTOSO\Administrator with
password Pa$$w0rd.
5. On the Quick Access Toolbar, click New folder, type EntityExtractor, and then press Enter.
6. Right-click the EntityExtractor folder, point to Share with, and then click Specific people.
7. In the File Sharing dialog box, in the text box, type SPFarm, click Add, and then click Share.
10. Right-click in the empty folder, point to New, and then click Text Document.
15. On the Windows Start page, type SharePoint, and then click SharePoint 2013 Management Shell.
16. At the command prompt, type the following code, and then press Enter:
$searchApp = Get-SPEnterpriseSearchServiceApplication
17. At the command prompt, type the following code, and then press Enter:
5. In the Managed property box, type Title, and then press Enter.
7. In the Custom entity extraction section, select the Word Extraction - Custom1 check box, and
then click OK.
8. In the Managed property box, type Description, and then press Enter.
10. In the Custom entity extraction section, select the Word Extraction - Custom1 check box, and
then click OK.
14. Wait for the crawl to complete. Click Refresh until the Status reads Idle.
3. On the Search page, in the text box, type mp3 player, and then press Enter, several results appear.
5. In the Navigation Zone section, in the Refinement section, click the Refinement Web Part Menu
drop-down arrow, and then click Edit Web Part.
6. In the Refinement section, click the Choose Refiners button.
7. In the Refinement configuration for ‘Refinement’ dialog box, in the Available refiners box, click
WordCustomRefiner1, and then click Add>.
8. In the Display name box, type Memory, and then click OK.
12. On the Search page, in the text box, type mp3 player, and then press Enter. Several results appear.
Notice the new memory refiner on the left.
13. Click 8GB. Results appear that have 8GB in the title or description.
Results: After completing this exercise, you should have created, deployed, and tested a custom entity
extractor.
MCT USE ONLY. STUDENT USE PROHIBITED
L5-1
3. In the New Project dialog box, in the hierarchy of templates, expand Visual C#, expand
Office/SharePoint, and then click SharePoint Solutions.
7. In the Project Location dialog box, browse to E:\Labfiles\Starter, and then click Select Folder.
9. In the SharePoint Customization Wizard dialog box, in the What site do you want to use for
debugging box, type http://dev.contoso.com, and then click Validate.
10. In the Microsoft Visual Studio dialog box, click OK.
12. In Solution Explorer, right-click ContosoDocumentIDProvider, point to Add, and then click Class.
13. In the Add New Item - ContosoDocumentIDProvider dialog box, in the Name box, type
DocumentIDProvider, and then click Add.
14. In Solution Explorer, right-click References, and then click Add Reference.
15. In the Reference Manager - ContosoDocumentIDProvider dialog box, under Assemblies, click
Extensions.
16. In the list of extensions, click Microsoft.Office.DocumentManagement, and then select the check
box that appears.
17. In the list of extensions, click Microsoft.Office.Policy, select the check box that appears, and then
click OK.
18. In the DocumentIDProvider.cs code window, locate the following line of code:
using System.Threading.Tasks;
19. Immediately after this located code, type the following code:
using System.Data;
using Microsoft.SharePoint;
using Microsoft.Office.DocumentManagement;
namespace ContosoDocumentIDProvider
MCT USE ONLY. STUDENT USE PROHIBITED
L5-2 Developing Microsoft SharePoint Server 2013 Advanced Solutions
namespace Contoso.ContentManagement
class DocumentIDProvider
3. Press Enter.
if (listItem == null)
{
throw new ArgumentNullException("listItem");
}
7. Press Enter.
8. Type the following code:
9. Press Enter.
5. Press Enter.
7. In Solution Explorer, right-click ContosoDocumentIDProvider, point to Add, and then click Existing
Item.
if (itemUrls.Count == 0)
{
return null;
}
else
{
return itemUrls.ToArray();
}
5. Place the cursor within the DocumentIDProvider class, but outside any method.
Results: A Microsoft Visual Studio® project with a custom document ID provider class coded and
completed.
5. In the Description box, type This feature enables the Contoso Document ID Provider.
7. In Solution Explorer, right-click ContosoDocIDFeature, and then click Add Event Receiver.
8. In the ContosoDocIDFeature.EventReceiver.cs code window, delete all the comments within the
ContosoDocIDFeatureEventReceiver class.
using Microsoft.SharePoint;
2. Immediately after the located code, insert the following line of code:
using Microsoft.Office.DocumentManagement;
base.FeatureActivated(properties);
7. Press Enter.
base.FeatureDeactivating(properties);
5. Press Enter.
DocumentId.SetDefaultProvider(site);
3. In the Windows Security dialog box, in the User name box, type Administrator.
Note: Notice that you can add your own prefix for document IDs.
10. In Visual Studio, on the DEBUG menu, click Start Without Debugging. Wait for the deployment to
complete before you continue.
11. In the first instance of Internet Explorer (which is displaying the Document ID Settings), refresh the
page.
Note: The page shows a message informing you that a custom document ID provider has
been configured. Notice that you cannot edit the prefix for document IDs.
MCT USE ONLY. STUDENT USE PROHIBITED
L5-6 Developing Microsoft SharePoint Server 2013 Advanced Solutions
15. In the Choose File to Upload dialog box, browse to E:\Labfiles\Test Documents, click Test
Document.docx, and then click Open.
16. In the Add a document dialog box, click OK.
19. In the list of Columns, select the check box to the left of Document ID (linked to document), and
then click OK.
7. Click Create.
8. On the Edit Policy page, in the Name box, type Contoso Audit Policy.
9. In the Administrative Description box, type This policy ensures auditing for reading and editing
items.
10. In the Policy Statement box, type A policy is applied to this document that audits access.
12. Select the Opening or downloading documents, viewing items in lists, or viewing item
properties check box.
13. Select the Editing items check box, and then click OK.
16. In the Do you want to open or save Contoso Audit Policy.xml from dev.contoso.com? message
box, in the Save list, click Save as.
17. In the Save As dialog box, browse to the root of the C: drive.
18. Click New folder, type Policies, and then press Enter.
MCT USE ONLY. STUDENT USE PROHIBITED
L5-7
20. In the The Contoso Audit Policy.xml download has completed message box, click Open folder.
22. Click the Settings icon, and then click Site settings.
23. Under Site Collection Administration, click Content Type Policy Templates.
6. In the Description box, type Sets up auditing for documents in Contoso sites.
8. In Solution Explorer, right-click ContosoAuditingFeature, and then click Add Event Receiver.
9. In the ContosoAuditingFeature.EventReceiver.cs code window, delete all the comments within the
ContosoDocIDFeatureEventReceiver class.
10. On the FILE menu, click Save All.
using Microsoft.SharePoint;
using System.Xml;
using Microsoft.Office.RecordsManagement.InformationPolicy;
using System.IO;
base.FeatureActivated(properties);
7. Press Enter.
9. Press Enter.
policyXmlDoc.WriteTo(xmlTextWriter);
PolicyCollection.Add(site, policyXml);
24. Switch to File Explorer and verify that the contents of the C:\Policies folder is displayed.
26. In the How do you want to open this type of file (.xml)? dialog box, click Microsoft Visual Studio
2012.
27. In the Contoso Audit Policy.xml code window, in the <p: Policy> element, select the value of the
id element.
"];
Policy.CreatePolicy(docContentType, newPolicy);
base.FeatureDeactivating(properties);
5. Press Enter.
6. Type the following code:
7. Press Enter.
Policy.DeletePolicy(docContentType);
9. Press Enter.
11. In the Contoso Audit Policy.xml code window, in the <p: Policy> element, select the value of the
id element.
PolicyCollection.Delete(site, "
");
2. In the Windows Security dialog box, in the User name box, type Administrator.
Note: Notice that the Contoso Audit Policy you deleted has been recreated by the
feature receiver.
Note: Notice that the information management policy for the Document content type is
taken from Contoso Audit Policy.
Results: A SharePoint solution that imports and applies an information management policy when it is
activated.
MCT USE ONLY. STUDENT USE PROHIBITED
L6-1
2. If you are not already logged on, log on to the LONDON machine as CONTOSO\Administrator with
password Pa$$w0rd.
3. On the Windows Start page, type Visual Studio, and then click Visual Studio 2012.
6. In Solution Explorer, right-click Contoso.Website.Layouts, point to Add, and then click SharePoint
Mapped Folder.
7. In the Add SharePoint Mapped Folder dialog box, expand TEMPLATE, click
CONTROLTEMPLATES, and then click OK.
8. In Solution Explorer, right-click the CONTROLTEMPLATES folder, point to Add, and then click New
Item.
9. In the Add New Item - Contoso.Website.Layouts dialog box, in the Office/SharePoint group, click
User Control (Farm Solution only).
10. In the Name box, type Contoso.ProductCodeTemplate.ascx, and then click Add.
<SharePoint:RenderingTemplate ID="ContosoProductCodeRenderingTemplate"
runat="server">
<Template>
<asp:TextBox ID="ProductCodeTextBox" runat="server" />
<asp:RegularExpressionValidator ID="ProductCodeValidator" runat="server"
ControlToValidate="ProductCodeTextBox"
ErrorMessage="Please enter a valid product code in the format @@@-####."
ValidationExpression="^[A-Z]{3}[0-9]{4}$" />
</Template>
</SharePoint:RenderingTemplate>
<SharePoint:RenderingTemplate ID="ContosoProductCodeDisplayRenderingTemplate"
runat="server">
<Template>
<asp:HyperLink ID="ProductCodeHyperLink" runat="server" />
</Template>
</SharePoint:RenderingTemplate>
Note: If you prefer, you can copy this markup from the text file at
E:\Starter\Snippets\RenderingTemplate.txt.
MCT USE ONLY. STUDENT USE PROHIBITED
L6-2 Developing Microsoft SharePoint 2013 Advanced Solutions
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
class ProductCodeField
{
}
7. Place the cursor in the class body, and then add the following code:
}
set
{
this.EnsureChildControls();
ProductCodeTextBox.Text = (string)this.ItemFieldValue;
}
}
Note: If you prefer, you can copy this code from the text file at
E:\Starter\Snippets\ProductFieldCode.txt.
Results: After completing this exercise, you should have created a User Control containing rendering
templates, and a custom field control.
3. In the code editor, add a content placeholder by appending the following code:
2. In Internet Explorer, in the address bar, type http://www.contoso.com, and then press Enter.
7. On the Create Page page, in the Title box, type My Product Article.
8. In the Page Layout list, click (Product Article Page) Product Article, and then click Create.
11. In the Product Code box, type ABC123J, and then press Tab.
Note: A message should appear next to the Product Code edit box requesting that you enter a valid
product code. This validates that our RegEx validation for product code is working properly.
12. In the Product Code box, type ABC1234, and then press Tab.
Note: The Add the Part gallery should open, allowing you to browse web parts to add to the page.
This validates that our Web Part Zone control is configured correctly.
17. Position the cursor on the ABC1234 text. At the bottom of the screen, notice that the URL of the
hyperlink is set to http://www.contoso.com/products?ProductCode=ABC1234.
Note: The previous step verifies our custom field control is properly rendering the display template
that formats the product code as a hyperlink.
Results: After completing this lab, you will have learned how to build and deploy page layouts that
include page field controls and web parts.
MCT USE ONLY. STUDENT USE PROHIBITED
L7-1
4. In Internet Explorer, in the address bar, type http://intranet.contoso.com, and then press Enter.
5. On the Home page, review the navigation at the top of the page.
6. Click the Settings icon, and then click Site settings.
7. Under Look and Feel, click Navigation, and notice how the navigation is set to structural for both
the global and the current navigation areas.
9. On the Windows Start page, type SharePoint, and then click SharePoint 2013 Central
Administration.
10. Under Application Management, click Manage service applications.
12. On the Term Store Management Tool page, in the TAXONOMY TERM STORE section, notice that
there is no term group called Navigation.
13. On the Windows Start page, type Visual Studio, and then click Visual Studio 2012.
18. In the Select the files to reference dialog box, browse to C:\Program Files\Common
Files\microsoft shared\Web Server Extensions\15\ISAPI, select the
Microsoft.SharePoint.Taxonomy.dll, Microsoft.SharePoint.dll, and
Microsoft.SharePoint.Publishing.dll assemblies, and then click Add.
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Navigation;
using Microsoft.SharePoint.Publishing;
using Microsoft.SharePoint.Publishing.Navigation;
using Microsoft.SharePoint.Taxonomy;
23. Below the located code, add the following code to define the CreateGroup method:
Note: If you prefer, you can copy the CreateGroup method from the text file at
E:\Labfiles\Starter\Snippets\CreateGroup.txt.
Note: If you prefer, you can copy the CreateNavigationTermSet method from the text file
at E:\Labfiles\Starter\Snippets\CreateNavigationTermSet.txt.
28. When the program has finished running and the console window has closed, switch to SharePoint
2013 Central Administration.
29. On the Term Store Management Tool page, click Refresh, notice the new Navigation term group
appears.
termSet.SetCustomProperty("_Sys_Nav_IsNavigationTermSet", "True");
termSet.TermStore.CommitAll();
}
}
termSet.TermStore.CommitAll();
}
catch (Exception ex) { }
}
Note: If you prefer, you can copy the CreateNavigationTermSet method from the text file
at E:\Labfiles\Starter\Snippets\CreateNavigationTerms.txt.
7. When the program has finished running and the console window has closed, switch to SharePoint
2013 Central Administration.
9. Expand Navigation, expand Intranet, and notice the terms in your term set.
10. Click the Intranet term set, and on the INTENDED USE tab notice the Use this Term Set for Site
Navigation check box is selected.
11. Click the Finance term, and on the NAVIGATION tab notice the Simple Link or Header option is
selected.
12. Click the Home term, and on the NAVIGATION tab notice that the Term-Driven Page with
Friendly URL option is selected.
13. On the TERM-DRIVEN PAGES tab, notice that the Target Page Settings has been configured to
/Pages/Home.aspx.
t = termSet.CreateTerm("Finance", 1033);
t.SetLocalCustomProperty("_Sys_Nav_SimpleLinkUrl",
http://intranet.contoso.com/finance");
try
{
termSet.TermStore.CommitAll();
}
catch (Exception ex) { }
}
{
target.ReuseTermWithPinning(t);
}
}
Note: If you prefer, you can copy the PinTermSet method from the text file at
E:\Labfiles\Starter\Snippets\PinTermSet.txt.
CreateNavigationTermSet(group, "Team");
TermSet t_termSet = group.TermSets["Team"];
PinTermSet(s_termSet, t_termSet);
termStore.CommitAll();
7. When the program has finished running and the console window has closed, switch to SharePoint
2013 Central Administration.
9. Expand Navigation, and notice a new Team term set has been created.
10. Expand Team, and notice the same terms exist in the new term set as in the Intranet term set.
Note: If you prefer, you can copy the SetManagedNavigation method from the text file at
E:\Labfiles\Starter\Snippets\SetManagedNavigation.txt.
Note: If you prefer, you can copy the Main method from the text file at
E:\Labfiles\Starter\Snippets\Main.txt.
7. When the program has finished running and the console window has closed, switch to Internet
Explorer.
8. In Internet Explorer, click New Tab, in the address bar, type http://intranet.contoso.com, and then
press Enter. Notice that the managed navigation items are displayed. If the navigation items are not
visible, click Refresh.
9. Click the HR node, and notice that you are directed to the http://intranet.contoso.com/hr URL.
10. Click New Tab, in the address bar, type http://team.contoso.com, and then press Enter. Notice in
the global navigation area that the pinned terms being used are similar to your intranet publishing
site.
Results: A new navigation term set used by a site collection and shared by a team site.
MCT USE ONLY. STUDENT USE PROHIBITED
L7-7
2. In Internet Explorer, in the address bar, type http://intranet.contoso.com, and then press Enter.
2. Under Web Designer Galleries, click Master pages and page layouts.
3. On the ribbon, on the FILES tab, click Upload Document.
7. In the Master Page gallery - WindowsPhone.master dialog box, in the Content Type list, click ASP
NET Master Page.
8. In the Compatible UI Version(s) section, select the 15 check box, and then click Save.
12. On the Windows Start page, type SharePoint, and then click SharePoint Designer 2013.
13. In SharePoint Designer, click Open Site.
14. In the Open Site dialog box, in the Site name box, type http://intranet.contoso.com, and then
click Open.
15. In the Windows Security dialog box, in the User name box, type Administrator.
16. In the Password box, type Pa$$w0rd, and then click OK.
20. In the WindowsPhone.master file, locate and delete the div element with an id value of siteIcon. Be
sure to delete the opening tag, the closing tag, and everything in between.
23. Click the Settings icon, and then click Site settings.
24. Under Look and Feel, click Master page.
25. In the Windows Phone list, click WindowsPhone, and then click OK.
2. In F12 Developer Tools, on the Tools menu, point to Change user agent string, and then click
Custom.
3. In the Custom User Agent Strings dialog box, in the Friendly Name box, type Windows Phone.
4. In the User Agent String box, type Windows Phone, and then click Add.
6. Reload the page, and notice that the site icon is no longer displayed.
Results: After completing this exercise, you should have configured a device channel for Windows Phone
devices.
2. In Internet Explorer, in the address bar, type http://intranet.contoso.com, and then press Enter.
4. Under Web Designer Galleries, click Master pages and page layouts.
7. In the Choose File to Upload dialog box, browse to E:\Labfiles\Starter, click custom.master, and
then click Open.
9. In the Master Page gallery - custom.master dialog box, in the Content Type list, click ASP NET
Master Page.
10. In the Compatible UI Version(s) section, select the 15 check box, and then click Save.
15. In the middle pane, click custom.master. If the custom.master file is not visible, click Refresh.
18. On a new line below the located code, add the following code:
Note: You can copy the Register directive from the text file at
E:\Labfiles\Starter\Snippets\PublishingWebControlsTagPrefix.txt.
20. On a new line immediately below the located code, add the following code:
Note: If you prefer, you can copy the DeviceChannelPanel element from the text file at
E:\Labfiles\Starter\Snippets\DeviceChannelPanel.txt.
27. In the All Channels list, click custom, and then click OK.
2. Press F12.
3. In F12 Developer Tools, on the Tools menu, point to Change user agent string, and then click
Windows Phone.
MCT USE ONLY. STUDENT USE PROHIBITED
L7-10 Developing Microsoft SharePoint 2013 Advanced Solutions
4. Reload the page, and notice that the page now includes a welcome message for Windows Phone
users.
Results: After completing this exercise, you should have configured a master page to use device channel
panels to display content to users of specific devices.
MCT USE ONLY. STUDENT USE PROHIBITED
L8-1
3. On the Windows Start screen, type Visual Studio, and then click Visual Studio 2012.
6. In Solution Explorer, right-click the Features folder, and then click Add Feature.
using System.Text;
using Microsoft.SharePoint.Taxonomy;
using Microsoft.SharePoint.Publishing.Navigation;
13. Select the following code, and then click the Uncomment the selected lines button:
Best Practice: When calling the SPSite.RootWeb property, it is a best practice to utilize a
using statement to ensure the object instance is properly disposed of when complete.
For the remainder of this Lab, code should be appended within the using statement curly braces.
16. Click on the blank line between the two curly brackets.
MCT USE ONLY. STUDENT USE PROHIBITED
L8-2 Developing Microsoft SharePoint 2013 Advanced Solutions
18. In the Insert File dialog box, in the file type dropdown list, click All Files (*.*).
20. Review the code you just added. The code performs the following tasks:
b. It configures the robots.txt file to exclude various file paths from search crawling.
6. In Solution Explorer, right-click the Props feature, and then click Add Event Receiver.
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Taxonomy;
using Microsoft.SharePoint.Publishing.Navigation;
8. Select the following code, and then click the Uncomment the selected lines button:
11. Click on the blank line between the two curly brackets.
13. In the Insert File dialog box, in the file type dropdown list, click All Files (*.*).
15. Review the code you just added. The code performs the following tasks:
5. On the Site Collection Features page, on the Search Engine Sitemap feature, click Activate.
6. On the Contoso.Website.SEO - Props feature, click Activate
10. In the Verify ownership of this site with search engines section, verify that the meta tag with the
name msvalidate.01 has been added.
11. In the Consolidate link popularity with canonical URLs section, verify that the Filter link
parameters box contains category, and then click OK.
12. Under Site Collection Administration, click Search Engine Sitemap Settings.
13. On the Search Engine Sitemap page, verify that the text box contains Disallow: /legal/, and then
click OK.
14. In the address bar, type http://www.contoso.com, and then press Enter.
15. Click the Settings icon, and then click Edit Page.
16. On the Contoso Pharmaceuticals page, on the PAGE menu, click Edit Properties, and then click
Edit SEO Properties.
17. Verify that the SEO properties have been updated and are not blank, and then click Cancel.
18. On the PAGE menu, click Check In, and then click Discard Check Out.
Results: After completing this lab, the Internet-facing site collection at www.contoso.com configuration
for search engine optimizations should be complete.
MCT USE ONLY. STUDENT USE PROHIBITED
L8-4 Developing Microsoft SharePoint 2013 Advanced Solutions
4. In Solution Explorer, right-click the Features folder, and then click Add Feature.
using Microsoft.SharePoint.Administration;
11. Select the following code, and then click the Uncomment the selected lines button:
12. In the FeatureActivated method, add a new line between the curly brackets, and then on the
EDIT menu, click Insert File as Text.
13. In the Insert File dialog box, in the file type dropdown list, click All Files (*.*).
a. It modifies the web.config file for the web application to enable the BLOB cache.
6. In Solution Explorer, right-click the OutputCache feature, and then click Add Event Receiver.
MCT USE ONLY. STUDENT USE PROHIBITED
L8-5
using Microsoft.SharePoint.Publishing;
8. Select the following code, and then click the Uncomment the selected lines button:
9. In the FeatureActivated method, add a new line between the curly brackets, and then on the EDIT
menu, click Insert File as Text.
10. In the Insert File dialog box, in the file type dropdown list, click All Files (*.*).
12. Review the code you just added. The code performs the following tasks:
b. It enables and configures the page output cache settings for the site collection.
6. In Solution Explorer, right-click the ImageRenditions feature, and then click Add Event Receiver.
using Microsoft.SharePoint.Publishing;
using System.Linq;
using System.Linq.Expressions;
8. Select the following code, and then click the Uncomment the selected lines button:
9. In the FeatureActivated method, add a new line between the curly brackets, and then on the EDIT
menu, click Insert File as Text.
10. In the Insert File dialog box, in the file type dropdown list, click All Files (*.*).
12. Review the code you just added. The code performs the following tasks:
2. On the Central Administration web site, under Application Management, click Manage web
applications.
3. On the Web Applications Management page, click Host Named Site Collection (HNSC) Host
Web Application, and then on the ribbon, click Manage Features.
4. In the Manage Web Application Features dialog box, ensure that the Contoso.Website.Perf –
BLOB Cache feature is Active. If it is not Active, click Activate.
9. Right-click web.config, point to Open with, and then click Microsoft Visual Studio 2012.
10. In Visual Studio, on the EDIT menu, point to Find and Replace, and then click Quick Find.
11. In the Quick Find box, type BlobCache, and press Enter.
12. Validate that the <BlobCache> element has been updated and that the Enabled attribute has been
set to true.
13. Close Visual Studio 2012, and then close File Explorer.
15. In Internet Explorer, in the address bar, type http://www.contoso.com, and then press Enter.
17. Click the Settings icon, and then click Site settings.
18. Under Site Collection Administration, click Site collection output cache.
19. On the Output Cache Settings page, verify the Enable output cache check box is selected.
21. Verify the Authenticated Cache Profile is set to Disabled, and then click Cancel.
23. On the Image Renditions page, verify that a Masthead rendition has been created.
24. Close Internet Explorer.
Results: After completing this lab, the Internet-facing site collection at www.contoso.com configuration
will be configured for performance optimizations.
MCT USE ONLY. STUDENT USE PROHIBITED
L9-1
4. In the Login Properties - CONTOSO\Administrator dialog box, under Select a page, click User
Mapping.
5. Under Users mapped to this login, in the Map column, confirm that the ContosoRetailDW check
box is selected.
6. Under Database role membership for: ContosoRetailDW, confirm that db_datareader is selected.
Note: If ContosoRetailDW and db_datareader are not selected, select them now.
8. On the Start screen, type SharePoint, and then click SharePoint 2013 Central Administration.
11. On the ribbon, in the Manage Target Applications group, click New.
12. On the Create New Secure Store Target Application page, in the Target Application ID box, type
ContosoDWGeographyApp.
13. In the Display Name box, type Contoso Retail Geography Data Warehouse.
16. Leave the Field Name and Field Type unchanged, and then click Next.
18. In the Members box, type Everyone, and then click OK.
Note: You have created a group target application that maps all users to a single set of
credentials. You will now set the credentials that the target application will use to connect to the
external database.
19. In the list of target applications, select the ContosoDWGeographyApp check box.
MCT USE ONLY. STUDENT USE PROHIBITED
L9-2 Developing Microsoft SharePoint Server 2013 Advanced Solutions
21. In the Set Credentials for Secure Store Target Application (Group) dialog box, in the Windows
User Name box, type CONTOSO\Administrator.
22. In the Windows Password, and Confirm Windows Password boxes, type Pa$$w0rd, and then click
OK.
3. In the Open Site dialog box, in the Site name box, type http://sharepoint.contoso.com, and then
click Open.
4. If you are prompted for credentials, log in as CONTOSO\Administrator with password Pa$$w0rd.
Note: SharePoint Designer may take some time to open the site.
5. When SharePoint Designer has finished loading the site, in the Navigation pane, click External
Content Types.
6. On the ribbon, in the New group, click External Content Type.
7. In the External Content Type Information pane, in the Name row, click New external content
type.
9. In the External System row, click Click here to discover external data sources.
12. In the SQL Server Connection dialog box, in the Database Server box, type LONDON.
16. In the Secure Store Application ID box, type ContosoDWGeographyApp, and then click OK.
18. On the Data Source Explorer tab, expand ContosoRetailDWConnection, and then expand Tables.
21. In the All operations dialog box, on the Operation Properties page, click Next.
22. On the Parameters Configuration page, in the Data Source Elements list, clear the ETLLoadID,
LoadDate, and UpdateDate check boxes.
23. Click GeographyKey, and confirm that Map to Identifier is selected.
24. Click ContinentName, and then select the Show In Picker check box.
MCT USE ONLY. STUDENT USE PROHIBITED
L9-3
25. Click CityName, and then select the Show In Picker check box.
26. Click StateProvinceName, and then select the Show In Picker check box.
27. Click RegionCountryName, select the Show In Picker check box, and then click Next.
Note: Having created an external content type, you will now create an external list to display data
from the external content type
29. On the ribbon, in the Lists & Forms group, click Create Lists & Form.
31. In the Create List and Form for Geography dialog box, in the List Name box, type Regions, and
then click OK.
33. Locate the External Lists pane, and observe that it now includes a list named Regions.
35. On the Start screen, type SharePoint, and then click SharePoint 2013 Central Administration.
36. Under Application Management, click Manage service applications.
37. In the list of service applications, on the Business Data Connectivity Service Application row, click
Contoso Business Data Connectivity Service Application.
38. On the ribbon, in the Permissions group, click Set Metadata Store Permissions.
39. In the Set Metadata Store Permissions dialog box, type Domain Admins, and then click Add.
40. Under Permissions for CONTOSO\domain admins, select all the check boxes.
41. Select the Propagate permissions to all BDC Models, External Systems and External Content
Types in the BDC Metadata Store check box, and then click OK.
42. In the list of external content types, select the Geography check box.
43. On the ribbon, in the Permissions group, click Set Object Permissions.
44. In the Set Object Permissions dialog box, type Everyone, and then click Add.
45. Under Permissions for Everyone, select the Execute, and Selectable In Clients check boxes, and
then click OK.
46. In the Address bar, type http://sharepoint.contoso.com, and then press Enter.
47. On the Contoso SharePoint Site page, on the Quick Launch menu, click Regions.
Verify that the Regions list retrieves and displays a set of data from the external database.
3. In the Navigation pane, click External Content Types, and then click Geography.
6. In the Read List dialog box, on the Operation Properties page, click Next.
MCT USE ONLY. STUDENT USE PROHIBITED
L9-4 Developing Microsoft SharePoint Server 2013 Advanced Solutions
8. In the Properties pane, in the Data Source Element list, click RegionCountryName.
10. In the Filter Configuration dialog box, in the New Filter box, type By Country.
11. Confirm that the Filter Type list is set to Comparison, and the Operator list is set to Equals.
13. Select the Use to create match list in external item picker check box, and then click OK.
14. On the Filter Parameters Configuration page, in the Default Value list, type United States, and
then click Finish.
18. In the Address bar, type http://sharepoint.contoso.com, and then press Enter.
19. On the Quick Launch menu, under Lists, click Regions. You should now be able to see a list of
regions in the United States.
20. On the LIST menu, in the Manage Views section, click Modify View.
21. On the Edit View page, in the Data Source Filters section, in the Filter Value box, type China, and
then click OK.
Observe that the Regions list now displays a list of States/Provinces in China.
3. In the Open Site dialog box, in the Site name box, type http://sharepoint.contoso.com, and then
click Open.
6. On the New external content type tab, in the External Content Type Information pane, to the
right of Name, click New external content type.
8. To the right of External System, click Click here to discover external data sources and define
operations.
9. On the Data Source Explorer tab, expand ContosoRetailDWConnection, and then expand Tables.
10. In the Microsoft SharePoint Designer dialog box, click OK.
11. On the Data Source Explorer tab, right-click DimCustomer, and then click New Read Item
Operation.
12. In the Read Item dialog box, on the Operations Properties page, in the Operation Name box, type
ReadCustomer.
13. In the Operation Display Name box, type Read Single Customer, and then click Next.
MCT USE ONLY. STUDENT USE PROHIBITED
L9-5
14. On the Input Parameters Configuration page, click CustomerKey, confirm that the Map to
Identifier check box is selected, and then click Next.
15. On the Return Parameter Configuration page, clear all check boxes except:
a. CustomerKey
b. GeographyKey
c. Title
d. FirstName
e. LastName
f. EmailAddress
16. Click CustomerKey, confirm that the Map to Identifier check box is selected, and then click Finish.
17. On the Data Source Explorer tab, right-click DimCustomer, and then click New Read List
Operation.
18. In the Read List dialog box, on the Operations Properties page, in the Operation Name box, type
ReadCustomerList.
19. In the Operation Display Name box, type Read Customer List, and then click Next.
20. On the Filter Parameters Configuration page, click Add Filter Parameter.
21. In the Properties pane, to the right of Filter, click Click to Add.
22. In the Filter Configuration dialog box, in the New Filter box, type Results Limit.
23. In the Filter Type drop-down list box, click Limit, and then click OK.
24. On the Filter Parameters Configuration page, in the Default Value list, type 100, and then click
Next.
25. On the Return Parameter Configuration page, clear all check boxes except:
a. CustomerKey
b. GeographyKey
c. Title
d. FirstName
e. LastName
f. EmailAddress
26. Click CustomerKey, and confirm that the Map to Identifier check box is selected.
27. Click FirstName, and then select the Show In Picker check box.
28. Click LastName, select the Show In Picker check box, and then click Finish.
31. In the Create List and Form for Customer dialog box, in the List Name box, type Customers, and
then click OK.
32. On the ribbon, in the Views section, click Summary View.
36. In Internet Explorer, in the Address bar, type http://sharepoint.contoso.com,and then press Enter.
37. On the Quick Launch menu, click Customers, and verify that the list displays customer data.
3. In the Open Site dialog box, in the Site name box, type http://sharepoint.contoso.com, and then
click Open.
4. In the Navigation pane, click External Content Types, and then click Customer.
10. In the Association Display Name box, type Customer Geography Navigation, and then in the
Related External Content Type pane, click Browse.
11. In the External Content Type Selection dialog box, click Geography, and then click OK.
12. On the Association Properties page, in the Field list, ensure that GeographyKey is selected, and
then click Next.
13. On the Input Parameters Configuration page, in the Data Source Elements list, click
GeographyKey.
14. In the Properties pane, select the Map to Identifier check box, and then click Next.
16. On the Return Parameter Configuration page, clear all the check boxes except:
a. CustomerKey
b. GeographyKey
c. Title
d. FirstName
e. LastName
f. EmailAddress
22. In Internet Explorer, in the Address bar, type http://sharepoint.contoso.com, and then press Enter.
25. On the ribbon, on the FILES tab, in the New group, click the New Document drop-down arrow, and
then click Web Part Page.
26. On the New Web Part Page page, in the Name box, type CustomersByCountry, and then click
Create.
27. On the new page, in the Left Column section, click Add a Web Part.
29. In the Parts list, click Business Data List, and then click Add.
30. In the Left Column section, in the Business Data List section, click Open the tool pane.
31. In the Business Data List tool pane, to the right of the Type box, click the Select External Content
Type icon.
32. In the External Content Type Picker, click Geography, and then click OK.
Note: It may take some time to populate the External Content Type Picker dialog box.
34. In the Geography List web part, in the text box for the By Country filter, type Australia, and then
click Retrieve Data.
35. On the new page, in the Middle Column section, click Add a Web Part.
37. In the Parts list, click Business Data Related List, and then click Add.
38. In the Middle Column section, in the Business Data Related List web part, click Open the tool
pane.
39. In the Business Data Related List tool pane, to the right of the Type box, click the Select External
Content Type icon.
40. In the External Content Type Picker dialog box, click Customer, and then click OK.
41. In the Business Data Related List tool pane, notice the Relationship dropdown list showing the
value Default (Customer Geography Navigation) association.
42. In the Tool pane, click Apply and wait for the page to refresh.
43. In the Customer List web part, move the mouse just above the Edit View link until a black drop-
down arrow appears.
44. Click the Customer List Web Part Menu drop-down arrow, point to Connections, point to Get
Related Item From, and then click Geography List.
46. In the Geography List, click the double-arrow icon next to GeographyKey 425. Notice that the
Customer List web part updates to show a list of customers for that region.
Results: After this exercise, you should have created two external content types named Geography and
Customer, exposed their data by using external lists and business data web parts.
3. In the How do you want to open this type of file (.sln)? dialog box, click Visual Studio 2012.
5. Review the InitializeService method. Notice that this method exposes the DimProducts,
DimProductCategories and DimProductSubcategories entities. These map to the DimProduct,
DimProductCategory and DimProductSubcategory database tables.
6. On the DEBUG menu, click Start Without Debugging. Leave the service running because it is
required in the following tasks.
7. In the New app for SharePoint dialog box, in the What SharePoint site do you want to use for
debugging your app, type http://dev.contoso.com/.
8. In the How do you want to host your app for SharePoint list, click SharePoint-hosted, and then
click Finish.
9. In Solution Explorer, right-click the ContosoOData project, point to Add, and then click Content
Types for an External Data Source.
10. In the SharePoint Customization Wizard, in the What OData service URL do you want to use to
create the external data source box, type
http://localhost:12345/ContosoODataWebService.svc/.
11. In the What do you want to name your new data source box, type ContosoODataSource, and
then click Next.
12. On the Select the Data Entities page, select the DimProducts and DimProductSubcatergories
check boxes.
13. Ensure that the Create list instances for the selected data entities (except Service Operations)
check box is selected, and then click Finish.
MCT USE ONLY. STUDENT USE PROHIBITED
L9-9
15. In Solution Explorer, right click DimProducts.ect, and then click Open With.
16. In the Open With - DimProducts.ect dialog box, click XML (Text) Editor, and then click OK.
19. In the Search term box, type <Association. In the code, note that the highlighted Association
element contains SourceEntity and DestinationEntity elements that map the DimProducts entity
to the DimProductsSubcategories entity.
4. If SharePoint displays an error message, close Internet Explorer, and then in Visual Studio, on the
DEBUG menu, click Start Debugging.
5. In Internet Explorer, in the DimProducts list, in the ProductKey column, click 1.
7. In the ProductDescription box, type New description, and then click Save.
9. On the Start screen, type SQL, and then click SQL Server Management Studio.
11. In Object Explorer, expand Databases, expand ContosoRetailDW, and then expand Tables.
12. Right-click dbo.DimProduct, and then click Select Top 1000 Rows.
13. Verify that the ProductDescription for row 1 has been updated to New description.
Results: After this exercise, you should have created two app-scoped external content types named
Product and Category by using an OData connection.
MCT USE ONLY. STUDENT USE PROHIBITED
MCT USE ONLY. STUDENT USE PROHIBITED
L10-1
2. If you are not already logged on, log on to the LONDON machine as CONTOSO\Administrator with
password Pa$$w0rd.
3. On the Start page, type Visual Studio, and then click Visual Studio 2012.
4. On the FILE menu, point to New, and then click Project.
5. In the New Project dialog box, under Templates, expand Visual C#, and then click
Office/SharePoint.
6. In the list of templates, click SharePoint 2013 - Empty Project.
9. In the SharePoint Customization Wizard dialog box, in the What site do you want to use for
debugging box, type http://dev.contoso.com.
12. In the Add New Item - NorthwindModel dialog box, in the Office/SharePoint category, click
Business Data Connectivity Model.
13. In the Name box, type NorthwindModel, and then click Add.
5. In Solution Explorer, under NorthwindModel, right-click Entity1.cs, and then click Rename.
9. In the Product.cs file, in the Product class, replace the existing code, with the following code:
3. In Properties, in the Name box, type ProductId, and then press Enter.
4. In the Type Name list, click Int32.
5. In BDC Explorer, under ReadItem, expand returnParamater, and then click Entity1.
8. In BDC Explorer, under returnParamater, expand Product, and then click Identifier1.
9. In Properties, in the Name box, type ProductId, and then press Enter.
13. In Properties, in the Name box, type Name, and then press Enter.
14. In BDC Explorer, under returnParameter, right-click Product, and then click Add Type Descriptor.
15. In Properties, in the Name box, type Description, and then press Enter.
o RetailPrice
o QuantityPerUnit
o ProductManager
o Manufacturer
o CostBasis
17. In BDC Explorer, expand ReadList, expand returnParamater, and then click Entity1List.
19. In the Name box, type Products, and then press Enter.
20. In BDC Explorer, expand Products, and then click Entity1.
MCT USE ONLY. STUDENT USE PROHIBITED
L10-3
21. In Properties, in the Name box, type Product, and then press Enter.
23. In Solution Explorer, right-click NorthwindModel.bdcm, and then click Open With.
27. In the NorthwindModel.bdcm file, select the following code, and then press CTRL+C:
28. Select the following lines of code, and then press CTRL+V:
29. In the Methods element, before the closing tag, press Enter.
33. Review the method definitions you have just added to the model.
7. In the Select the files to reference dialog box, browse to C:\Program Files\Common
Files\Microsoft Shared\Web Server Extensions\15\ISAPI, click Microsoft.BusinessData.dll, and
then click Add.
8. Click Assemblies, select the System.Web check box, and then click OK.
9. In Solution Explorer, double-click ProductService.cs, and after the existing using statements, press
Enter.
11. In the Insert File dialog box, browse to E:\Labfiles\Starter, and in the file extension list, click Text
Files (*.txt).
15. In the ProductServices.cs, file, at the end of the ProductService class, before the closing brace, press
Enter.
16. On the EDIT menu, click Insert File As Text.
17. In the Insert File dialog box, browse to E:\Labfiles\Starter, and in the file extension list, click Text
Files (*.txt).
18. Click EntityMethods.txt, and then click Open.
19. Review the code you have just added to the code file.
2. At the beginning of the ProductService class, after the opening brace, press Enter.
3. Add the following class variables and properties to implement the IContextProperty interface:
4. In the ProductService class, after the last of the property declarations, press Enter.
8. On the Windows Start page, type SharePoint, and then click SharePoint 2013 Central
Administration.
11. On the ribbon, in the Manage Target Applications section, click New.
12. On the Create New Secure Store Target Application page, in the Target Application ID box, type
Northwind.
16. On the Create New Secure Store Target Application page, change the Field Name to User Name
and Password by removing the Windows text.
17. Change the Field Type to User Name and Password, and then click Next.
18. On the Create New Secure Store Target Application page, in the Target Application
Administrators box, type CONTOSO\administrator, and then click Check Names.
19. In the Members box, type CONTOSO\domain users, click Check Names, and then click OK.
23. In the Password and Confirm Password boxed, type Pa$$w0rd, and then click OK.
24. Switch to Visual Studio.
25. In the NorthwindModel.bdcm file, modify the LobSystemInstance xml node by adding the AppId
property, as shown in bold:
<LobSystemInstances>
<LobSystemInstance Name="NorthwindModel">
<Properties>
<Property Name="AppId" Type="System.String">Northwind</Property>
</Properties>
</LobSystemInstance>
</LobSystemInstances>
<Properties>
<Property Name="AppId" Type="System.String">Northwind</Property>
<Method Name="ReadItem">
MCT USE ONLY. STUDENT USE PROHIBITED
L10-6 Developing Microsoft SharePoint Server 2013 Advanced Solutions
<Properties>
<Property Name="RootFinder" Type="System.String">Empty</Property>
</Properties>
8. In Solution Explorer, right-click the NorthwindModel project, and then click Deploy.
9. When the solution has been deployed successfully, switch to SharePoint Central Administration.
10. On the Quick launch menu, under Central Administration, click System Settings.
11. Under Farm Management, click Manage farm features.
12. On the Manage Farm Features page, confirm that the NorthwindModel Feature1 is activated.
17. On the Quick Launch menu, under Central Administration, click Application Management.
18. On the Application Management page, under Service Applications, click Manage service
applications.
20. Select the Product check box, and then on the ribbon, click Set Object Permissions.
21. In the Set Object Permissions dialog box, type CONTOSO\domain users, and then click Add.
22. In the Permissions for CONTOSO\domain users section, select all the check boxes, and then click
OK.
MCT USE ONLY. STUDENT USE PROHIBITED
L10-7
Note: If you discover an error after deploying the search connector, you must retract the
solution by using Visual Studio (to retract the solution, right-click the project and then click
Retract), and then restart IIS before you can re-deploy the solution. If you do not restart IIS after
the retraction, SharePoint will use the previous version of the assembly and you will get
unexpected results.
Task 2: Test the .NET Connectivity Solution by Using a BCS Web Part
1. Open a new browser tab, and in the address bar, type http://team.contoso.com, and then press
Enter.
3. In the Add a page dialog box, in the New page name box, type Product, and then click Create.
8. Next to the Type property, click the Select External Content Type icon.
9. In the External Content Type Picker dialog box, click NorthwindModel, and then click OK.
10. In the Business Data List web part properties, click OK.
4. In the Adding External List dialog box, in the Name box, type Product.
5. Next to External Content Type, click the Select External Content Type icon.
6. In the External Content Type Picker dialog box, click NorthwindModel, and then click OK.
8. On the Site Contents page, on the Quick Launch menu, click Product. You should see the data
displayed in the external list app.
10. On the Product – New Item page, in the Name box type Test.
14. In the Manufacturer box, type Contoso, and then click Save.
15. At the bottom of the page, in the paging controls, click the right arrow. Repeat this step until you
reach the last page.
2. On the Quick Launch menu, under Central Administration, click Application Management.
5. Select the Product check box, and then on the ribbon, click Configure.
6. In the Configure External Content Type Profile Page Host dialog box, in the text box, type
http://team.contoso.com, and then click OK.
7. On the Quick Launch menu, under Central Administration, click Application Management.
10. On the Quick Launch menu, under Crawling, click Content Sources.
11. On the Manage Content Sources page, click New Content Source.
12. On the Add Content Source page, in the Name box, type Northwind.
13. In the Content Source Type section, click Line of Business Data.
14. In the External Data Source section, click Crawl selected external data source.
15. Select the NorthwindModel check box, and then click OK.
16. On the Manage Content Sources page, click the Northwind drop-down arrow, and then click Start
Full Crawl.
19. You should see the Northwind content source has indexed several items, but several have warnings.
These warnings are expected.
20. Open a new browser tab. In the Address bar, type http://search.contoso.com, and then press Enter.
21. On the Search page, in the text box, type Chef, and then press Enter. You should get back two items.
3. In the New Project dialog box, under Templates, expand Visual C#, expand Office/SharePoint, and
then click Apps.
7. In the New app for SharePoint dialog box, in the What SharePoint site do you want to use for
debugging your app, type http://dev.contoso.com/.
8. In the How do you want to host your app for SharePoint list, click SharePoint-hosted, and then
click Finish.
9. In Solution Explorer, right-click the AssetApp project, point to Add, and then click Content Types
for an External Data Source.
10. In the SharePoint Customization Wizard, in the What OData service URL do you want to use to
create the external data source box, type
http://localhost:12345/ContosoODataWebService.svc/.
11. In the What do you want to name your new data source box, type ContosoODataSource, and
then click Next.
MCT USE ONLY. STUDENT USE PROHIBITED
L11-2 Developing Microsoft SharePoint Server 2013 Advanced Solutions
12. On the Select the Data Entities page, select the DimProducts, and DimProductSubcategories
check boxes.
13. Confirm that the Create list instances for the selected data entities (except Service Operations)
check box is selected, and then click Finish.
2. Locate the div element near the bottom of the page. Delete this div element and all its contents.
4. On a new line immediately below the code you just added, type the following:
8. In the Insert File dialog box, in the file type list, click All Files (*.*).
10. Review the code you just added. The onGetProducts function retrieves data from the DimProducts
external list, which you configured in the previous task. The returned data is stored in a variable
named odataResult.
11. Click anywhere on the line that shows the following code, and then press F9 to add a breakpoint:
13. When the app has finished loading, in Internet Explorer, click Get Products.
14. When the debugger reaches the breakpoint, in Visual Studio, press F10.
15. Hover over the text odataResult, and then on the context menu, expand odataResult.
16. Verify that the odataResult variable contains multiple sets of data, and then on the DEBUG menu,
click Stop Debugging.
17. Press Ctrl+Shift+F9 to delete all breakpoints.
2. Locate the onReturnData function, and delete all the code within the function (delete everything
within the curly brackets).
4. In the Insert File dialog box, in the file type list, click All Files (*.*).
6. Review the code you just added. The onGetProducts function renders the data from the external list
as a table.
7. On the DEBUG menu, click Start Debugging.
8. When the page loads, click Get Products. Verify that the app displays a table containing product
data.
Results: After this exercise, you should have retrieved a list of products that are older than three years.
3. On a new line immediately above the input element, add the following code:
<select id="lstClass">
<option value="'Economy'">Economy</option>
<option value="'Regular'">Regular</option>
<option value="'Deluxe'">Deluxe</option>
</select>
7. Edit the line of code you just located to resemble the following:
5. Notice that the page only displays items with a Class value of Economy.
6. In the drop-down list, click Regular, and then click Get Products.
MCT USE ONLY. STUDENT USE PROHIBITED
L11-4 Developing Microsoft SharePoint Server 2013 Advanced Solutions
7. Notice that the page displays only items with a Class value of Regular.
8. In the drop-down list, click Deluxe, and then click Get Products.
9. Notice that the page displays only items with a Class value of Deluxe.
Results: After this exercise, you should have filtered the data retrieved from the OData by class name.
MCT USE ONLY. STUDENT USE PROHIBITED
L12-1
2. In Visual Studio, on the FILE menu, point to Open, and then click Project/Solution.
<div id="search">
2. On a new line below the located code, add the following code:
<p>
<label>Account Name</label><input type="text" id="accountName" />
</p>
<p>
<label>Name</label><input type="text" id="name" />
</p>
<p>
<label> Department </label><input type="text" id="department" />
</p>
<p>
<button type="button" id="submitSearch">Search</button>
</p>
<div id="results">
4. On a new line below the located code, add the following code:
<p>
<a href="#" onclick="Contoso.UserProfileApp.showSearch()">New Search</a>
</p>
<div id="users">
</div>
6. In the App.css file, review the markup. Notice that the markup defines the layout for the elements
you have added in this task.
MCT USE ONLY. STUDENT USE PROHIBITED
L12-2 Developing Microsoft SharePoint Server 2013 Advanced Solutions
3. On a new line below the located code, add the following code:
6. Place the cursor on a new line after the line you located in the previous step.
8. In the Insert File dialog box, browse to E:\Labfiles\Snippets, in the file type list, click All Files (*.*),
click searchUsersFunction.txt, and then click Open.
function showSearch() {
$("#search").show();
$("#results").hide();
}
return {
10. On a new line below the located code, add the following code:
searchUsers: searchUsers,
$(document).ready(function() {
12. On a new line below the located code, add the following code:
$('#submitSearch').click(Contoso.UserProfileApp.searchUsers);
2. In Internet Explorer, on the Do you trust ContosoUserProfileApp page, click Trust It.
3. On the User Profile Search page, in the Account Name box, type Administrator, and then click
Search.
4. Verify that a single user is returned with the display name Administrator.
13. In the Department box, type Marketing, and then click Search.
14. Verify that a single user is returned with the display name Denise Smith.
Results: After completing this exercise, you should have added search functionality to an app.
3. On a new line below the located code, add the following code:
<div id="users">
</div>
5. On a new line below the located code, add the following code:
<div id="profile">
</div>
8. Place the cursor on a new line after the line you located in the previous step.
10. In the Insert File dialog box, browse to E:\Labfiles\Snippets, in the file type list, click All Files (*.*),
click displayProfileFunction.txt, and then click Open.
searchUsers: searchUsers,
MCT USE ONLY. STUDENT USE PROHIBITED
L12-4 Developing Microsoft SharePoint Server 2013 Advanced Solutions
12. On a new line below the located code, add the following code:
displayProfile: displayProfile,
$("#users").html("");
14. On a new line below the located code, add the following code:
$("#profile").html("");
$("#users").append("<div>" +
"<a href='#'
onclick='Contoso.UserProfileApp.displayProfile(this)' data-username='" +
this.AccountName + "'>" + this.PreferredName + "</a></div>");
5. Verify that the app displays the profile information for Denise Smith.
Results: After completing this exercise, you should have modified an app to retrieve a user profile.
MCT USE ONLY. STUDENT USE PROHIBITED
L12-5
3. On the Manage Service Applications page, click the User Profile Service Application row (do not
click the Contoso User Profiles text).
5. In the Administrators for Contoso User Profiles dialog box, in the text box, type Domain Admins,
and then click Add.
6. Under Permissions for CONTOSO\domain admins, select the Manage Profiles check box, and
then click OK.
2. In Visual Studio, on the FILE menu, point to Open, and then click Project/Solution.
3. In the Open Project dialog box, browse to E:\Labfiles\Starter\CMPWP, click
ContosoManagePropertiesWebPart.sln, and then click Open.
5. Review the ContosoManagePropertiesWebPart.ascx file. Notice that the file defines a text box, two
buttons and a table.
6. In Solution Explorer, right-click References, and then click Add Reference.
using Microsoft.Office.Server.UserProfiles;
12. Place the cursor on a new line after the code you just located.
14. In the Insert File dialog box, browse to E:\Labfiles\Snippets, in the file types list, click All Files (*.*),
click LoadPropertiesMethod.txt, and then click Open.
16. On a new line below the located code, add the following code:
LoadProperties();
propertiesTable.Rows.Add(row);
}
}
18. On a new line below the located code, add the following code:
3. In Internet Explorer, on the Contoso Development Site page, on the PAGE menu, click Edit.
4. In the edit view, click in the box on the line above the Get started with Apps for Office and
SharePoint text.
5. On the INSERT menu, click Web Part.
6. In the Categories list, click Custom, in the Parts list, click ContosoManagePropertiesWebPart, and
then click Add.
Results: After completing this exercise, you should have added code to display user profile properties on
a web part.
2. Place the cursor on a new line after the code you just located.
3. On the EDIT menu, click Insert File As Text.
4. In the Insert File dialog box, browse to E:\Labfiles\Snippets, in the file types list, click All Files (*.*),
click addPropertyMethod.txt, and then click Open.
2. Place the cursor on a new line after the code you just located.
3. On the EDIT menu, click Insert File As Text.
4. In the Insert File dialog box, browse to E:\Labfiles\Snippets, in the file types list, click All Files (*.*),
click deletePropertyMethod.txt, and then click Open.
2. Place the cursor on a new line after the code you just located.
4. In the Insert File dialog box, browse to E:\Labfiles\Snippets, in the file types list, click All Files (*.*),
click privacyOptions_SelectedIndexChangedMethod.txt, and then click Open
MCT USE ONLY. STUDENT USE PROHIBITED
L12-8 Developing Microsoft SharePoint Server 2013 Advanced Solutions
2. In Internet Explorer, on the Contoso Development Site page, in the text box, type New Property,
and then click Add Property. After you click Add Property, the page may take some time to update.
Wait for the page to update before you continue. Do not click Add Property twice, or the code may
throw an exception.
3. In the NewProperty row, in the Privacy list, click Private, and then click Save Changes. When the
page reloads, verify that the default privacy for the NewProperty is now Private.
4. In the NewProperty row, click Delete. When the page reloads, verify that the NewProperty row has
been removed.
Results: After completing this exercise, you should have updated a web part to include functionality to
manage user profile properties.
MCT USE ONLY. STUDENT USE PROHIBITED
L13-1
4. In Visual Studio, on the FILE menu, point to Open, and then click Project/Solution.
8. Click the empty Scope field, and then in the list, click Tenant.
Note: The Tenant permission simplifies the debugging process. In a production app you should use
the most restrictive permissions requirements that are necessary for your app.
9. Click the empty Permission field next to the Scope you have just set, and then from the list, click
Write.
10. Click in the empty Scope field, and then in the list, click User Profiles (Social).
11. Click in the empty Permission field next to the Scope you have just set, and then in the list, click
Read.
2. In the code editor, locate the comment // TODO: Add code to load the site's newsfeed.
3. On a new line after the comment you have just located, type the following code:
var siteFeed;
$.ajax({
url: Utilities.appWebUrl + "/_api/social.feed/actor(item=@v)/feed?@v='" +
Utilities.hostWebUrl + "/newsfeed.aspx'",
headers: {
'accept': 'application/json;odata=verbose'
},
success: function (data) {
siteFeed = getSiteFeedSuccess(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error: " + xhr.status + " " + thrownError + "\nResponseText: " +
xhr.responseText);
},
});
return siteFeed;
4. Locate the comment // Add code to process the newsfeed after the feed has been retrieved.
MCT USE ONLY. STUDENT USE PROHIBITED
L13-2 Developing Microsoft SharePoint Server 2013 Advanced Solutions
5. On a new line after the comment you have just located, type the following code:
feedPosts = data.d.SocialFeed.Threads.results.reverse();
Contoso.NewsfeedApp.feedPosts = feedPosts;
Display.updateDisplay();
6. Locate the comment // TODO: Add code to update the newsfeed when the app launches.
7. On a new line after the comment you have just located, type the following code:
Contoso.NewsfeedApp.updateFeed();
2. In Internet Explorer, on the Do you trust ContosoFeedApp page, click Trust It.
5. In the Parts list, click ContosoFeedAppPart Title, and then click Add.
7. Verify that a newsfeed is displayed and includes the message Welcome to the project site for
project 2822.
Results: After completing this exercise, you should have modified an app part to display a newsfeed from
a project site.
2. Locate the comment <!-- TODO: Add textarea and button. -->.
3. On a new line after the comment you have just located, type the following markup:
5. In the code editor, locate the following comment // TODO: Add code to add a click event handler
to the post button.
6. On a new line after the comment you have just located, type the following code:
$('#PostStatus').click(Contoso.NewsfeedApp.post);
MCT USE ONLY. STUDENT USE PROHIBITED
L13-3
2. Locate the following comment // TODO: Add code to send the new post to SharePoint.
3. On a new line after the comment you have just located, type the following code:
4. On a new line after the code you have just typed, type the following code:
$.ajax({
url: Utilities.appWebUrl + "/_api/social.feed/actor(item=@v)/feed/post?@v='" +
Utilities.hostWebUrl + "/newsfeed.aspx'",
type: 'POST',
data: JSON.stringify({
'restCreationData': {
'__metadata': {
'type': 'SP.Social.SocialRestPostCreationData'
},
'ID': null,
'creationData': {
'__metadata': {
'type': 'SP.Social.SocialPostCreationData'
},
'ContentItems': {
'results': tags
},
'ContentText': userContent,
'UpdateStatusText': false
}
}
}),
headers: {
'accept': 'application/json;odata=verbose',
'content-type': 'application/json;odata=verbose',
'X-RequestDigest': Utilities.formDigest
},
success: sendPostSuccess,
error: function () {
alert("Error: " + xhr.status + " " + thrownError + "\nResponseText: " +
xhr.responseText);
}
MCT USE ONLY. STUDENT USE PROHIBITED
L13-4 Developing Microsoft SharePoint Server 2013 Advanced Solutions
});
$("#StatusTextArea").val("");
5. Locate the following comment // TODO: Add code to update the feed after a post is successfully
added.
6. On a new line after the comment you have just located, type the following code:
Feed.updateFeed();
2. In Internet Explorer, in the ContosoFeedAppPart Title text box, type Sent from the app, and then
click Post.
3. Verify that the feed is updated with a post containing Sent from the app #P2822.
4. On the Quick Launch menu, click Newsfeed.
5. Verify that the first post in the feed contains the text Sent from the app #P2822.
Results: After completing this exercise, you should have added controls and code to an app part to
support posting a message to a newsfeed.
3. Click the empty Permission row, in the list, click QueryAsUserIgnoreAppPrincipal, and then click
Save.
// Add code to process the newsfeed after the feed has been retrieved.
feedPosts = data.d.SocialFeed.Threads.results.reverse();
6. On a new line after the lines of code you have just located, type the following code:
sortList.add("LastModifiedTime",
Microsoft.SharePoint.Client.Search.Query.SortDirection.Ascending);
keywordQuery.set_enableSorting(true);
var searchExecutor = new
Microsoft.SharePoint.Client.Search.Query.SearchExecutor(Utilities.clientContext);
var results = searchExecutor.executeQuery(keywordQuery);
Utilities.clientContext.executeQueryAsync(function () {
var resultRows = results.m_value.ResultTables[0].ResultRows;
Contoso.NewsfeedApp.searchResults = resultRows;
Display.updateDisplay();
8. On a new line after the line of code you have just located, type the following code:
},
function () {
alert("Search failed.");
});
3. Locate the following comment // TODO: Add code to retrieve the actor for the specified account.
4. On a new line after the comment you have just located, type the following code:
2. In Internet Explorer, on the Do you trust ContosoFeedApp page, click Trust It.
5. In the Parts list, click ContosoFeedAppPart Title, and then click Add.
7. Verify that the feed on the page now includes a message from Pat Coleman asking for help on a case
study she is producing. This post is from Pat’s My Site newsfeed.
8. Close all open windows.
Results: After completing this exercise, you should have modified the app part to display posts retrieved
by using the search service.
MCT USE ONLY. STUDENT USE PROHIBITED
L14-1
5. When the how do you want to open this type of file (.sln)? dialog appears click Visual Studio
2012.
6. In Solution Explorer, in the MileageRecorderRemoteWeb project, expand the Controllers project,
and then double-click HomeController.cs.
8. Immediately after the located code, insert the following lines of code:
9. Place the cursor within the Diagnostics method you just created, and then type the following code:
return View();
4. Press Enter.
"settingsLinks": [
{
}
]
6. Place the cursor within the settingsLinks property object you just created, and then type the
following code:
7. Press Enter.
"displayName": "Diagnostics"
5. On the Contoso Mileage Recorder page, click the Settings icon, and then click Diagnostics.
Note: Be careful to double-click the Web.config file in the root of the project, not the
Web.config file in the Views folder.
</system.web>
3. Immediately before the located code, insert the following lines of code:
<trace enabled="false"
localOnly="false"
mostRecent="true"
pageOutput="false"
requestLimit="100"
traceMode="SortByTime"
writeToDiagnosticsTrace="true" />
3. Immediately after the located code, insert the following line of code:
4. Press Enter.
TraceSection traceSection =
(TraceSection)currentConfig.GetSection("system.web/trace");
6. Press Enter.
ViewBag.TracingStatus = traceSection.Enabled;
8. In Solution Explorer, expand Views, expand Home, and then double-click Diagnostics.cshtml.
MCT USE ONLY. STUDENT USE PROHIBITED
L14-4 Developing Microsoft SharePoint Server 2013 Advanced Solutions
@if (ViewBag.TracingStatus)
{
}
else
{
}
10. Place the cursor within the if code block you just created, and then type the following code:
11. Place the cursor within the else code block you just created, and then type the following code:
2. Place the cursor after the end of the Diagnostics action but within the HomeController class, and
then type the following code:
3. Place the cursor within the ToggleTracing action you just created, and then type the following code:
4. Press Enter.
TraceSection traceSection =
(TraceSection)currentConfig.GetSection("system.web/trace");
6. Press Enter.
traceSection.Enabled = switchOn;
8. Press Enter.
currentConfig.Save();
ViewBag.TracingStatus = switchOn;
return View("Diagnostics");
3. Immediately after the located code, insert the following lines of code:
<p>
@Html.ActionLink("Switch Off Tracing", "ToggleTracing", new { controller = "Home",
switchOn = false, SPHostUrl = Request.QueryString["SPHostUrl"], SPAppWebUrl =
Request.QueryString["SPAppWebUrl"] });
</p>
4. Press Enter.
7. Immediately after the located code, insert the following lines of code:
<p>
@Html.ActionLink("Switch On Tracing", "ToggleTracing", new { controller = "Home",
switchOn = true, SPHostUrl = Request.QueryString["SPHostUrl"], SPAppWebUrl =
Request.QueryString["SPAppWebUrl"] });
</p>
2. If SharePoint displays the Do you trust Mileage Recorder? page, on the Do you trust the Mileage
Recorder? page, click Trust It.
3. On the Contoso Mileage Recorder page, click the Settings icon, and then click Diagnostics.
6. In the Engine size box, type 1600, and then click Create.
3. On the Application Trace page, locate the tracing entry that records a GET request for the
Home/Diagnostics page, and then click View Details.
7. Locate the tracing entry that records a POST request for the MileageClaim/Create address, and then
click View Details.
Results: A SharePoint auto-hosted app in which users can enable tracing and view tracing logs to supply
information about bugs and other issues.