.xxi ⊲ Part i using sharePoint technologies and exPloiting functionality chaPter 1 Leveraging the SharePoint Object Model.. ConTenTs Creating Page Layouts Using SharePoint Designer 201
Trang 3Professional
sharePoint® 2010 field guide
introduction .xxi
⊲ Part i using sharePoint technologies and exPloiting functionality chaPter 1 Leveraging the SharePoint Object Model 3
chaPter 2 Creating Visual Web Parts 35
chaPter 3 Customizing Search 55
chaPter 4 Leveraging the SharePoint Lists Web Service 73
chaPter 5 Custom Field Types, Content Types, and List Definitions 93
chaPter 6 Workflow 131
chaPter 7 Administrating SharePoint 2010 with PowerShell 175
⊲ Part ii sharePoint solutions chaPter 8 UI Design and Branding 211
chaPter 9 Building a Site Provisioning System 233
chaPter 10 Building Scalable Applications in SharePoint 297
chaPter 11 Building a Custom Global Navigation Solution 343
aPPendix a URL Shortcuts 399
aPPendix B CSS Quick Reference 401
aPPendix c Hiding and Customizing Page Breadcrumbs 405
aPPendix d PowerShell Quick Reference 407
glossary 409
index 411
Trang 5Professional
Trang 7Professional
Steve Mann Colin Murphy Pablo Gazmuri Chris Caravajal Christina Wheeler
Trang 8Indianapolis, IN 46256
www.wiley.com
Copyright © 2012 by John Wiley & Sons, Inc., Indianapolis, Indiana
Published simultaneously in Canada
be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions.
Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect
to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without tion warranties of fitness for a particular purpose No warranty may be created or extended by sales or promotional materials The advice and strategies contained herein may not be suitable for every situation This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services If professional assistance is required, the services of a competent professional person should be sought Neither the publisher nor the author shall be liable for damages arising herefrom The fact that an organization or Web site is referred to in this work as a citation and/or a poten- tial source of further information does not mean that the author or the publisher endorses the information the organization or Web site may provide or recommendations it may make Further, readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work was written and when it is read.
limita-For general information on our other products and services please contact our Customer Care Department within the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Wiley publishes in a variety of print and electronic formats and by print-on-demand Some material included with standard print versions of this book may not be included in e-books or in print-on-demand If this book refers to media such as a CD or DVD that is not included in the version you purchased, you may download this material at http://booksupport.wiley.com For more information about Wiley products, visit www.wiley.com.
Library of Congress Control Number: 2011942765
Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Wrox Programmer to Programmer, and related trade dress are
trademarks or registered trademarks of John Wiley & Sons, Inc and/or its affiliates, in the United States and other countries, and may not be used without written permission SharePoint is a registered trademark of Microsoft Corporation All other trademarks are the property of their respective owners John Wiley & Sons, Inc., is not associated with any product or vendor mentioned in this book.
Trang 9aBout the authors
steve Mann was born and raised in Philadelphia, Pennsylvania, where he still resides today He is
an Enterprise Applications Engineer for Morgan Lewis and has more than 17 years of professional experience Steve was previously a Principal Architect for RDA Corporation, where he worked for over thirteen years Steve graduated from Drexel University in 1993 For the past eight years, he has focused primarily on collaboration and business intelligence solutions using Microsoft technologies Steve managed the internal BI Practice Group at RDA for several years He was also heavily involved within RDA’s Collaboration/Search Practice Group Steve has authored and coauthored several books related to the subject of SharePoint Server 2010 Steve’s blog can be found at: www.SteveTheManMann com Steve enjoys vacationing with his family along the east coast, including locations such as Orlando, Florida; Williamsburg, Virginia; Ocean City and Sea Isle City, New Jersey; and New York City They usually hits three or four locations each year Follow Steve on Twitter @stevethemanmann!
colin MurPhy lives in Atlanta, Georgia, where he works as a Principal Architect for RDA
Corporation, a Microsoft Gold Partner He has spent the last fifteen years developing Web sites and Windows applications using a variety of languages including C++, PowerBuilder, Java, PHP, and Python, but has primarily been a NET/C# developer for the last ten years Colin has been developing enterprise solutions built on SharePoint since SharePoint 2007 was in beta Colin holds a number of technical certifications including Microsoft Certified Professional, Microsoft Certified Application Developer, Microsoft Certified Solutions Developer, and is also a Microsoft Certified Technical Specialist for SharePoint He has been recognized as a K2 Insider and is the coauthor of the book
Professional K2 blackpearl by Wiley
PaBlo gazMuri is a Principal Architect with RDA Corporation, an IT Consulting firm He has led SharePoint efforts for a number of Fortune 500 companies where he conducts planning, mentoring, training, and coding activities With fifteen years of development experience, Pablo is a web, collabo-ration, and search expert who has built numerous corporate intranets, extranets, ecommerce sites, and custom applications over the course of his career Pablo has recently built custom SharePoint applications enabling project management, document generation, SharePoint site provisioning, gover-nance enforcement, and more You can find him on Twitter as @PGazmuri, or contact him through RDA at http://www.rdacorp.com
chris caravajal has been working exclusively with SharePoint technologies since 2007 As a sultant, he works with organizations on planning and architecting SharePoint solutions that vary in both size and complexity Primarily an “out-of-the-box” specialist, Chris’s main focus is getting the most out of SharePoint with the native features and tools He also has experience building InfoPath forms and SharePoint Designer workflow solutions Chris is a MCTS and is a contributing author to the top-selling SharePoint technical publication, “Professional SharePoint 2010 Administration.”
Trang 10con-educational institutions, financial institutions, and telecommunications As a trainer, Christina brings her real-world experience to the classroom She enjoys contributing articles to technical Web sites and often speaks at SharePoint community events and conferences You can follow her on Twitter
as @cwheeler76
aBout the technical editor
reza alirezaei MVP, MCP, MCPD, MCITP & MCTS for SharePoint 2010, is a SharePoint tion architect focused on designing custom applications with SharePoint, Office, and Microsoft Business Intelligence technologies Reza is the founder and president of Development Horizon, where
solu-he has solu-helped many clients architect and build large-scale, mission-critical SharePoint applications
He also speaks in many local and international conferences Reza achieved the status of Microsoft Most Valuable Professional (MVP) for SharePoint in 2006, which he still is today He has also co-authored several books, papers, and articles Reza can be reached at reza@devhorizon.com
Trang 11Mary Beth Wakefield
freelancer editorial Manager
Trang 13thanks to christina Wheeler for taking over one of the chapters in this book I am so glad she joined the group of authors Also, thanks to Chris Caravajal from SharePoint 911 for stepping in and taking a chapter as well Thanks to all my SharePoint expert friends and Twitter followers You inspire
me to keep going and doing more with technology Special thanks to Paul Reese, our acquisitions editor, and the entire Wrox project team for helping us create an excellent SharePoint 2010 resource
Trang 15summary 54
contents
Conventions xxii
errata xxiii
p2p.wrox.com xxiii
Part i: using sharePoint technologies and exPloiting f
summary 33
summary 54
summary 71
Trang 16Defining Site Collection Search Scopes and Scope Display Groups 60
summary 71
summary 92
Trang 17Building a Restricted Social Security Number Field Type 99
summary 129
Trang 18Part ii: sharePoint solutions
Themes 211
Trang 19ConTenTs
Creating Page Layouts Using SharePoint Designer 2010 226
Deploy Custom Page Layouts Through Visual Studio 2010 227
Registering Custom Application Pages from Receivers 231
Registering Custom Application Pages from Windows PowerShell 232
summary 232
Buildout 243
summary 295
chaPter 10: Building scalaBle aPPlications in sharePoint 297
Trang 21ConTenTs
Trang 23this Book Was Written to Provide a wide coverage of complex solutions to common needs and desires from SharePoint 2010 implementations along with great reference material for digging in and learning the new platform; an excellent guide and handbook for people in the field There are plenty of books to ramp up and learn how to do things with SharePoint; however, this book focuses
on the main areas of customization and provides more intricate details as well as specific full-scale solutions that people need to implement It is not a beginner how-to but a second or third book to further deepen one’s understanding and knowledge in SharePoint 2010 It is meant to be a guide for those in the field that suddenly find themselves needing to create custom SharePoint solutions
Who this Book is for
This book is for SharePoint or NET Developers who now need to implement solutions in SharePoint
2010 These are developers that may have been exposed to some SharePoint development but haven’t spent extensive time customizing solutions Those that consider themselves more than beginner but not quite intermediate or advanced can benefit greatly from this book If you need to become an expert in SharePoint 2010 solutions, this book takes you down that road
What this Book covers
This book covers the main aspects of customizing SharePoint from branding and creating web parts,
to exploiting the SharePoint API and building workflows PowerShell administration is discussed and explained The Search features of SharePoint are demonstrated and customized Full-scale solutions are dissected to present best practices and understanding of SharePoint development way beyond out-of-the-box
hoW this Book is structured
There are two parts to this book The first part starts out with the building blocks of SharePoint knowledge and customization The second part gets deeper and more complex while building out applications and custom solutions
What you need to use this Book
In order to benefit the most from this book, readers need to have a SharePoint 2010 development ronment along with Visual Studio 2010 Professional Edition (or higher) Usually a virtual-machine-based environment is more available than physical servers SharePoint 2010 requires 64-bit hardware with at least 8GB of memory and the Windows 2008 R2 operating system
Trang 24➤ We present code in two different ways:
We use a monofont type with no highlighting for most code examples.
We use bold to emphasize code that is particularly important in the present
context or to show changes from a previous code snippet.
Listings include the filename in the title If it is just a code snippet, you’ll find the filename in a code note such as this:
Code snippet filename
Because many books have similar titles, you may find it easiest to search by
ISBN; this book’s ISBN is 978-0-470-10505-4.
Once you download the code, just decompress it with your favorite compression tool Alternately, you can go to the main Wrox code download page at www.wrox.com/dynamic/books/download aspx to see the code available for this book and all other Wrox books
Trang 25introduction
errata
We make every effort to ensure that there are no errors in the text or in the code However, no one
is perfect, and mistakes do occur If you find an error in one of our books, like a spelling mistake
or faulty piece of code, we would be very grateful for your feedback By sending in errata, you may save another reader hours of frustration, and at the same time, you will be helping us provide even higher-quality information
To find the errata page for this book, go to www.wrox.com and locate the title using the Search box
or one of the title lists Then, on the book details page, click the Book Errata link On this page, you can view all errata that has been submitted for this book and posted by Wrox editors A complete book list, including links to each book’s errata, is also available at www.wrox.com/misc-pages/ booklist.shtml
If you don’t spot “your” error on the Book Errata page, go to www.wrox.com/contact/techsupport shtml and complete the form there to send us the error you have found We’ll check the information and, if appropriate, post a message to the book’s errata page and fix the problem in subsequent editions
of the book
P2P Wrox coM
For author and peer discussion, join the P2P forums at http://p2p.wrox.com The forums are a Web-based system for you to post messages relating to Wrox books and related technologies and inter-act with other readers and technology users The forums offer a subscription feature to email you top-ics of interest of your choosing when new posts are made to the forums Wrox authors, editors, other industry experts, and your fellow readers are present on these forums
At http://p2p.wrox.com, you will find a number of different forums that will help you, not only
as you read this book, but also as you develop your own applications To join the forums, just follow these steps:
1 Go to p2p.wrox.com and click the Register link
2 Read the terms of use and click Agree
3 Complete the required information to join, as well as any optional information you wish to provide, and click Submit
4 You will receive an email with information describing how to verify your account and complete the joining process
You can read messages in the forums without joining P2P, but in order to post
your own messages, you must join.
Trang 26Once you join, you can post new messages and respond to messages other users post You can read messages at any time on the Web If you would like to have new messages from a particular forum emailed to you, click the Subscribe to this Forum icon by the forum name in the forum listing For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to questions about how the forum software works, as well as many common questions specific to P2P and Wrox books To read the FAQs, click the FAQ link on any P2P page
Trang 27Part I
using sharePoint technologies and exploiting functionality
⊲ chaPter 1: Leveraging the SharePoint Object Model
⊲ chaPter 2: Creating Visual Web Parts
⊲ chaPter 3: Customizing Search
⊲ chaPter 4: Leveraging the SharePoint Lists Web Service
⊲ chaPter 5: Custom Field Types, Content Types, and List Definitions
⊲ chaPter 6: Workflow
⊲ chaPter 7: Administrating SharePoint 2010 with PowerShell
Trang 29leveraging the sharePoint
object Model
SharePoint provides a rich and complex object model for working with SharePoint data Although it is challenging to master the details of the SharePoint object model, an even greater challenge that many developers face is taking their knowledge of the object model and using it
to craft a solution that delivers on a set of requirements By its nature, SharePoint solutions are often made up of loosely coupled components that combine to deliver a full set of functional-ity, and it is sometime difficult to figure out how to translate knowledge of the object model into the set of loosely coupled components in SharePoint Ask three SharePoint developers how
to solve a particular, nontrivial problem, and you will likely receive three unique solutions that might all be equally valid
This chapter attempts to first cover, in broad strokes, the various customization mechanisms that SharePoint exposes to developers and then provides a number of sample problems and describes how they can be solved the “SharePoint Way.” The chapter provides some basic code snippets illustrating how you can implement various features, but because this chapter is more about how components can be plugged together and combined into solutions, the coverage is not exhaustive
custoMizing sharePoint
SharePoint is a powerful platform that offers many points of extension and customization You can’t cover everything that SharePoint encompasses within a single chapter, but this chapter high-lights some of the most common bits of functionality that you are likely to need to implement in your role as a SharePoint developer
1
Trang 30ui components
Master Pages and Themes
Master Pages and Themes are the primary mechanism in SharePoint to modify the look and feel of SharePoint Master Pages can best be thought of as controlling the “edges” of a SharePoint page Everything from the breadcrumb and up and from the quick launch and left is determined by the Out of the Box (OOTB), v4.master Master Page This could be extended to control items to the right and below the primary content area of SharePoint pages as well One common change typically implemented by deploying a custom Master Page is the addition of a standard footer to the bottom
of pages in SharePoint
Themes determine the color palette utilized by SharePoint You can build themes using the Theme Designer available from Site Settings or also by using PowerPoint 2010 themes In addition to devel-oping a custom theme, you likely also need a custom CSS file to provide the granular control most branding efforts require
Chapter 8, “UI Design and Branding,” provides a good overview of Master Pages,
themes, and what goes into branding a solution.
Custom Web Parts
Web parts are the primary UI building block within SharePoint They are modular elements that you can place on almost any page within SharePoint SharePoint ships with a large number of web parts, but it will often be necessary to write your own
Within SharePoint 2010, there are two types of web parts: visual web parts and traditional web parts Back in the days of SharePoint 2007, there was only a single type of web part, the traditional web part Unlike most other visual controls within Visual Studio, web parts did not have any sort of WYSIWYG designer, and developers had to build the UI via code SharePoint 2010 introduces the ability to build visual web parts that enable the developer to use a WYSIWYG designer to build the UI
Following is code for a traditional, “Hello World!” web part:
Trang 31Customizing sharePoint ❘ 5
{
protected override void CreateChildControls()
{
Label label = new Label();
label.Text = “Hello World!”;
figure 1-1: A Visual Web Part design canvas
When placed on a SharePoint page, the two web parts appear to be nearly identical, as shown in Figure 1-2
Trang 32figure 1-2: Web parts
You probably wonder why traditional web parts continue to exist within SharePoint 2010 because Visual Web Parts provide a better design experience The answer is twofold The first is to maintain backward compatibility and to allow solutions that can be deployed to both 2007 and 2010 envi-ronments The second is that because of the way Visual Web Parts deploy, they are not supported within Sandboxed Solutions There are some alternative implementations of Visual Web Parts, such
as those found within Microsoft’s Visual Studio 2010 SharePoint Power Tools, which do work for sandboxed solutions
Web parts are primarily applicable when you need to implement functionality that requires a UI, is meant to be end-user configurable, and is meant for the site owners or designers to place on pages of their choosing This may not always be the case however
Chapter 2, “Creating Visual Web Parts,” delves into Visual Web Parts in much
greater depth.
Custom application Pages
The other primary UI building block within SharePoint is the custom application page These are standard ASPX pages that are deployed beneath the _layouts directory within your SharePoint environment
Trang 33Customizing sharePoint ❘ 7
Unlike web parts, custom application pages are standalone pages of self-contained functionality Users cannot edit the contents of the page or add custom web parts If you don’t want the user to determine the placement of the control, or you need to link to the page from another solution ele-ment (for example, a custom action, web part, and so on), application pages are generally the right solution to the problem
A common use for custom application pages is for settings pages, which is probably the scenario in which you see them most used within the OOTB SharePoint screens For example, go to the site settings section of any site in SharePoint, and every one of the settings links take you to an application page.Creating a custom application page is as simple as selecting Add➤➪➤New Item within your project, and selecting the Application Page type This creates an ASPX page beneath the Layouts directory
of your project, as shown in Figure 1-3
figure 1-3: Application page in Visual Studio
As you can see in the screenshot, application pages are just like any traditional ASPX page ten in NET with a few references added to SharePoint assemblies Just like the other pages within SharePoint, application pages make use of a Master Page, and content placeholder regions are
writ-exposed for you to add content to Figure 1-4 shows a sample application page
Application pages are deployed to the Layouts directory and, as such, are not deployed as part of a feature This means that application pages are accessible from within any site within your farm just
by appending \_layouts\<path to page> and SharePoint does not secure them assuming the user has access to the site, so you need to check user access within your own code
Trang 34figure 1-4: Application page in SharePoint
Custom lists
SharePoint Lists provide a flexible and extensible way for users to store data within SharePoint and
is frequently be used by developers as a location to store information as well In many instances, these types of “configuration” lists are hidden from the user, and all interactions with the list data occurs through UI elements such as web parts and application pages, but there are cases, particu-larly when the user must maintain lists of data that you want to expose the list directly to the user
In those cases, it may be sufficient to simply link them directly to the list and use the default list UI
to allow the users to manage the list items In more complicated scenarios (consider an example in which you have complex multicolumn validation requirements or in which you have multilevel drop-downs) the OOTB UI provided by lists is insufficient
Custom List Forms
List forms refer to the add, edit, and display forms accessible from SharePoint when a user adds a new list item or clicks on an existing list item and chooses to view or edit it Typical scenarios in which you might need to customize these would be if you need to add complex validation logic that spans across multiple columns in the list or in which selections made to one column affect those available
in another However, list forms are only one way in which you can enter list data within a list Users interacting with a list through the datasheet view, through the office information panel, or through Access cannot enjoy the same experience, so you need to account for these usage scenarios
Trang 35Customizing sharePoint ❘ 9
Chapter 5, “Custom Field Types, Content Types and List Definitions,” covers lists and list forms in great detail and illustrates how to create custom list forms, so they will not be covered further here, but 2010 provides a number of mechanisms for customizing these forms: You can use SharePoint Designer, InfoPath, and Visual Studio to create more robust list forms
Custom Field Types
Field types are the basic building blocks of lists and content types Whenever you add a new column
to a SharePoint list, you select from a variety of predefined column types such as Currency, Number, and Choice By selecting these types, you can decide what types of data can be entered and how that data displays and can be manipulated Figure 1-5 shows a standard column creation dialog
figure 1-5: Creating a column in SharePoint
Creating custom field types adds to the list of standard types of new columns and enables you to dictate how information displays and interacts within the standard SharePoint list UI They are most appropriate when you need to implement rules about the types of data fields can contain or the formatting of the display of your data (masking a Social Security number, for example)
Chapter 5 discusses creating custom field types in greater detail.
Trang 36Delegate Controls
SharePoint supports delegate controls, which might best be described as functionality ers Developers can register their own implementation of the functionality that overrides the OOTB implementation You can embed many delegate controls within the default Master Page and include things such as the search box
placehold-As example of how to embed a delegate control in a Master Page is shown in the following code snippet:
<SharePoint:DelegateControl ControlId=”SmallSearchInputBox”
AllowMultipleControls=”false”/>
This snippet basically tells SharePoint that the developer wants to embed a control called
SmallSearchInputBox into this location, but the developer requires no knowledge of the mentation of the control
imple-Delegate controls can also have a default implementation specified directly within the body as well Following is an example in the TopNavigationDataSource delegate control from the v4.master:
Delegate controls are most useful when you need to replace a bit of OOTB functionality that exists within multiple locations in SharePoint such as the search box, navigation providers, and so on Unfortunately, not every control in the OOTB Master Pages uses delegate controls, so their use is limited to specific controls
Trang 37nonvisual components
Visual components are only half of the story with most SharePoint customizations Equally necessary
is the ability to implement nonvisual functionality, such as executing code at periodic intervals (a timer job) or executing code after an item is added to a list (event handlers or workflow)
Trang 38Because there is considerable functionality overlap, determining when to write a list workflow sus writing an event handler is confusing Workflows provide some advantages during the creation process because codeless workflows can be authored via SharePoint Designer, and workflow actions exist so that developers don’t need to write custom code But assuming you need to write code with either implementation, event handlers are best used for short-running, atomic processes that do not require user involvement and are tied to the specific list in question Event handlers are also the only option if you want to intercept an action before it happens If the requirement being met involves long-running processes that involve waiting for multiple inputs from users or which are triggered from multiple locations, a workflow is more likely to be the correct solution.
ver-SharePoint 2010 also introduces a new type of workflow called a site workflow Site workflows are tied to sites rather than individual lists and can be only manually triggered (or via code) Site work-flows are primarily useful when the workflow in question is not tied to actions around a particular item in a list Imagine a scenario in which you need to find a single item in a list based on some characteristic and then email the creator of that item In that case, because you want the workflow
to find the item, a site workflow is appropriate If instead you want to email the creator of an item every time it updates, a list workflow is appropriate
Chapter 6 covers workflow in greater detail.
Chapter 11 contains an example of a timer job used to process links contained within a list to retrieve access information to secure the items
feature receivers
Feature receivers are just an alternative form of an event receiver tied to SharePoint Features rather than SharePoint Lists Feature receivers enable the developer to run arbitrary code whenever a fea-ture is installed or removed from a farm/web application/site collection/web, whenever a feature is activated or deactivated, or when a feature is upgraded
One common use for feature receivers is to register timer jobs deployed by a feature Following is an example of what code to add for a timer job whenever the feature activates:
public override void FeatureActivated(
SPFeatureReceiverProperties properties)
{
SPSite site = (SPSite)properties.Feature.Parent;
CustomTimerJob smbJob = new CustomTimerJob(“My Job Name”, site);
Trang 39SharePoint provides two mechanisms to support external access The first, which existed in SharePoint
2007 and continues to exist in 2010, are web services The second is Client Object Model, which is new to SharePoint 2010, which you can access from NET, Silverlight, or JavaScript
The main advantage to using the Client Object Model over the web services is that rather than having
to learn a completely new way to access SharePoint content, developers can reuse much of their edge of the server-side object model There definitely are some differences, but in general, the Client Object Model provides a much more familiar framework
knowl-sharePoint Web services
SharePoint provides a rich set of web services (both ASMX and WCF/RESTful) to enable external applications to interact with SharePoint Although not everything is exposed via web services, a great deal of functionality is For those writing code in NET, Silverlight, or Javascript, the Client Object Model introduced in 2010 will likely be the preferred mechanism for interacting with SharePoint, but for developers writing in other languages, web services continue to be the primary mechanism used
to interact with SharePoint
The list of web services SharePoint provides follows:
Trang 40Client object Model
The Client Object Model is a set of APIs that enable you to design custom applications that access SharePoint content It includes libraries for client applications based on the NET Framework This new API is targeted for building things such as console, Windows Forms, and WPF applications The Client Object Model also includes a library for Silverlight and JavaScript client applications The Silverlight library is composed of a subset of the object model These interfaces include the Managed NET Client Object model, Silverlight Client Object, ECMAScript (JavaScript, Jscript) Client Object Model, and LINQ to SharePoint
The NET Client Object Model for SharePoint 2010 is one of the newest APIs for working with SharePoint content The Client Object Model API enables you to build custom applications in any of