Microsoft SharePoint 2010 Development Cookbook Over 45 recipes to take you from beginner to professional in SharePoint Development
Ed Musters
BIRMINGHAM - MUMBAI
Microsoft SharePoint 2010 Development Cookbook Copyright © 2011 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: December 2011
Production Reference: 2161211
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-84968-150-6 www.packtpub.com
Cover Image by Sandeep Babu (
[email protected])
Credits Author Ed Musters Reviewers Thomas Ledan Sothilingam Jeyashanker Acquisition Editor
Copy Editor Leonard D'Silva Project Coordinator Michelle Quadros Proofreader Stephen Silk
Dilip Venkatesh Development Editor Susmita Panda Technical Editors Sakina Kaydawala Mehreen Shaikh Ankita Shashi
Indexers Hemangini Bari Tejal Daruwale Production Coordinator Prachali Bhiwandkar Cover Work Prachali Bhiwandkar
About the Author Ed Musters is a SharePoint MVP and a SharePoint Architect for Infusion. He has been an instructor for the exclusive Critical Path SharePoint courses for many years. Ed is an author of two books on SharePoint 2010 development. He has been a featured speaker at many international conferences, SharePoint Saturdays, and user groups. Ed enjoys sharing his real-world expertise with the readers! He has earlier worked on the Expert SharePoint 2010 Practices book, (ISBN: 1430238704). I would like to thank Ted and Andrew of Critical Path Training for starting me on my SharePoint journey, the folks at Telerik for their fantastic support for my community work, and finally, my loving wife Gala for her unwavering support for this project.
About the Reviewers Thomas Ledan has worked for 10 years in application and website development with Microsoft technologies and more particularly in SharePoint.
Initially, he was a web developer, and then became a technical leader for SharePoint from 2006 to 2010 and managed a development team of four. He is now a senior consultant at SoftFluent, an innovative company founded in 2005 by Microsoft veterans. I would like to thank Ed for providing this nice cookbook and I hope it will be a great help for all the readers. Above all, I would like to thank my wife Zuzana for supporting me and taking care of our children while I was concentrating on Ed's work.
Sothilingam Jeyashanker is a Senior SharePoint Developer/Administrator at DHI Water
& Environment (S) Pte. Ltd. He has many years of hands-on experience in SharePoint projects in various industries, both in the private and government sectors. He began his career with 'dBase III +' and 'Pascal' and he is currently engaged full time with 'SharePoint 2010.' Previously, he has worked for several Microsoft gold partner companies and obtained his M.E. degree in Computer Science and Engineering from Anna University, in Chennai, India. I take this opportunity to thank three people—first, my friend Loga, who is the reason for me entering the world of software; second, the Government of Singapore for the opportunities that they provided me to grow professionally in this high- tech nation; and third, DHI Water & Environment (S) Pte. Ltd., for giving me the opportunity to work with cutting edge technologies and giving me the chance to explore new possibilities.
www.PacktPub.com Support files, eBooks, discount offers and more
You might want to visit www.PacktPub.com for support files and downloads related to your book. Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at service@ packtpub.com for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
http://PacktLib.PacktPub.com Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books.
Why Subscribe? ff
Fully searchable across every book published by Packt
ff
Copy and paste, print and bookmark content
ff
On demand and accessible via web browser
Free Access for Packt account holders If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.
Instant Updates on New Packt Books Get notified! Find out when new books are published by following @PacktEnterprise on Twitter, or the Packt Enterprise Facebook page.
Table of Contents Preface Chapter 1: Setting Up a Development Environment Introduction Selecting your virtual environment Installing and configuring Windows Server 2008 R2 Installing and configuring SQL Server 2008 R2 Installing and configuring SharePoint Server 2010 Installing Microsoft Office 2010 Professional Installing Visio Premium 2010 Installing SharePoint Designer 2010 Installing Visual Studio 2010 Installing recommended developer tools Setting up your first web application
1 7
7 9 10 15 20 27 29 30 30 32 33
Chapter 2: SharePoint Development with Visual Studio
43
Chapter 3: Web Part Development
77
Introduction Exploring Content Types and Site Columns Features and Solutions Creating new Site Columns Packaging SharePoint Solutions Creating new Content Types Creating document libraries with Content Types Feature Receivers List Event Receivers Feature Staplers
Introduction Exploring Web Parts in SharePoint 2010 Creating and deploying Web Parts with Visual Studio 2010
43 44 47 49 57 61 65 68 70 74 77 78 81
Table of Contents
Creating Visual Web Parts Creating custom Web Part properties Creating Editor Parts for custom Web Part properties Creating Connected Web Parts
87 91 97 104
Chapter 4: Development with SharePoint Designer 2010
117
Chapter 5: Using the ClientOM and REST
145
Chapter 6: External Data
171
Chapter 7: SharePoint Workflows
209
Introduction Exploring SharePoint Designer 2010 Working with the XSLT List View Web Part Creating List Forms with SharePoint Designer Creating List Forms with InfoPath Enabling Inline Edit mode
Introduction Retrieving data using LINQ to SharePoint Retrieving SharePoint data using the list data service Working with the .NET Client Object Model Working with the Silverlight Client Object Model Introduction Getting your data ready for the chapter Using the Data Form Web Part with SQL Server Using the Data Form Web Part with WCF data External Content Types and Lists Using Business Data Web Parts Introduction Using out-of-the-box workflows Copying and extending out-of-the-box workflows with SharePoint Designer 2010 Using Visio 2010 to create workflows Using SharePoint Designer 2010 to implement Visio 2010 workflows Developing workflows in Visual Studio 2010
117 118 122 132 135 142 145 146 151 155 161
171 172 181 188 194 203 209 210 217 224 226 231
Chapter 8: Web Content Management
239
Index
259
Introduction Creating Publishing Pages Modifying navigation settings Creating and Using Page Layouts SharePoint 2010 Branding
ii
239 240 247 248 254
Preface There is a heavy demand in the marketplace for SharePoint developers that you could take advantage of—if only you had the opportunity to acquire the relevant skills! However, SharePoint 2010 is a big, old, product with a steep learning curve—so where do you begin? This book has been designed to take the experienced ASP.NET developer from beginner to professional SharePoint developer in the shortest amount of time. You will be productive on your very first SharePoint development assignment with the knowledge and skills that you learn here. You will have distilled the essence of the author's many years of training, and leading development teams in SharePoint. This book uncovers the most common "pattern" of SharePoint development tasks encountered in the real world and puts the topics into a logical order with detailed step-by-step recipes for you to follow. The practical examples that are given build-up and flow throughout the chapters. By the end of this book, you will be able to apply the concepts to the challenges ahead of you!
What this book covers Chapter 1, Setting up a Development Environment: In this chapter, you will build a fully functional SharePoint 2010 server and an integrated SharePoint development environment in a virtualized setting. Chapter 2, SharePoint Development with Visual Studio: This chapter will introduce SharePoint 2010 development with Visual Studio—packaging with features and deploying with solutions. It will introduce the definition of "schema" SharePoint style—site columns, content types, and list definitions—as applied to a document library. The SharePoint equivalent of a database "trigger" will be introduced—the list event receiver. Chapter 3, Web Part Development: This chapter will cover web control development with SharePoint, including user controls and Web Parts. More advanced web part development will be covered including Web Part properties, Editor Parts, and connected Web Parts.
Preface Chapter 4, Development with SharePoint Designer 2010: This chapter introduces SharePoint Designer 2010 as an important tool for the developer. You will apply this tool in this chapter to work with lists. You will learn about the very important XSLT List View Web Part, and about creating list forms with both ASPX and InfoPath. Chapter 5, Using the Client OM and REST: This chapter will introduce the retrieval of SharePoint data via Language Integrated Query (LINQ) and via the List Data Service (REST). The resulting data query will then be demonstrated in a Web Part, and via the Client Object Model in both a Windows and Silverlight application. Chapter 6, External Data: This chapter shows you how to connect to data that is "outside" of SharePoint, either in databases or via web services. Surprisingly powerful out-of-the-box capabilities will allow you to do most of this with "no code"—with Business Data Web Parts, with SharePoint Designer 2010, and with External Content Types and Lists. You will also learn to wrap existing data in SQL Server with a custom developed WCF Data Service that is then consumed in SharePoint 2010. Chapter 7, SharePoint Workflows: This chapter covers using an out-of-the-box approval workflow and then extending that with SharePoint Designer 2010. Along the way, we are introduced to the workflow form types—Association, Initiation, and Task Edit. Then we learn the tools for developing new workflows—Visio 2010, SharePoint Designer 2010, and Visual Studio 2010. Chapter 8, Web Content Management: This chapter provides a "non-developer" overview of the "other important side" of SharePoint. It also covers the concepts of publishing pages, page layouts, and master pages that are used within the Web Content Management capabilities of SharePoint to deliver public-facing websites.
What you need for this book In order to run the examples in the book, the following software will be required: ff
Microsoft Server software Windows Server 2008 R2 SQL Server 2008 R2 Enterprise SharePoint Server 2010 Enterprise
ff
Microsoft Office Software: Microsoft Office 2010 Professional Visio Premium 2010 SharePoint Designer 2010
ff
Development Tools: Visual Studio 2010 Professional or Ultimate Imtech Get SPMetal Definition Extension3
2
Preface
Note that the links given will lead you to downloadable trial software that will, by definition, have an expiry date. Feel free to replace this with your own licensed software, such as an MSDN subscription. #
Software Name
URL
1
Windows Server 2008 R2
http://www.microsoft.com/download/en/ details.aspx?displaylang=en&id=11093
2
SQL Server 2008 R2 Enterprise
http://msdn.microsoft.com/en-us/evalcenter/ ff459612
3
SharePoint 2010 Enterprise
http://technet.microsoft.com/en-us/ evalcenter/ee388573
4
Microsoft Office 2010 Professional
http://technet.microsoft.com/en-us/ evalcenter/ee390818
5
Visio Premium 2010
http://technet.microsoft.com/en-us/ evalcenter/ee390821
6
SharePoint Designer 2010
http://www.microsoft.com/download/en/ details.aspx?id=16573
7
Visual Studio 2010 Ultimate Trial
http://www.microsoft.com/download/en/ details.aspx?id=12187
8
SP Metal Extension
http://visualstudiogallery.msdn.microsoft. com/c523e7ba-ba9d-45c4-98ea-b02b19f81640/
Who this book is for This book is written for the ASP.NET developer who wants to become a professional SharePoint 2010 developer as quickly as possible, by learning the most important practical aspects of development that will be used in the real world.
Conventions In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning. Code words in text are shown as follows: "With CreateChildControls, you can literally create a control such as a Label or TextBox and add it to the controls collection."
3
Preface A block of code is set as follows: protected override void CreateChildControls() { Label myLabel1 = new Label(); myLabel1.Text = "SharePoint 2010 Cookbook Chapter 3 - This Web Part uses CreateChildControls"; this.Controls.Add (myLabel1); }
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold: <properties> <property name="Title" type="string">Web Part Using Render Contents <property name="Description" type="string">This Web Part demos overriding Render Contents.
Any command-line input or output is written as follows: # cp /usr/src/asterisk-addons/configs/cdr_mysql.conf.sample /etc/asterisk/cdr_mysql.conf
New terms and important words are shown in bold. Words that you see on the screen, in menus, or dialog boxes for example, appear in the text like this: "clicking the Next button moves you to the next screen". Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Reader feedback Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.
4
Preface
To send us general feedback, simply send an e-mail to
[email protected], and mention the book title via the subject of your message. If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or e-mail
[email protected]. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.
Customer support Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
Downloading the example code You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.
Errata Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.
Piracy Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy. Please contact us at
[email protected] with a link to the suspected pirated material. We appreciate your help in protecting our authors, and our ability to bring you valuable content.
Questions You can contact us at
[email protected] if you are having a problem with any aspect of the book, and we will do our best to address it. 5
1
Setting Up a Development Environment In this chapter, we will cover: ff
Selecting your virtual environment
ff
Installing and configuring Windows Server 2008 R2
ff
Installing and configuring SQL Server 2008 R2
ff
Installing and configuring SharePoint Server 2010
ff
Installing Microsoft Office 2010 Professional
ff
Installing Visio Premium 2010
ff
Installing SharePoint Designer 2010
ff
Installing recommended developer tools
ff
Setting up your first web application
Introduction Before one can consider himself/herself a true SharePoint 2010 developer, you must be capable of creating your very own development environment. Rather like the Jedi requirement of crafting your very first light saber; ok, it's not really that mystical, or that difficult to do, but I assure you that you will find the experience highly gratifying.
Setting Up a Development Environment This chapter will take you through all the recipes that you require to build your very own development environment. This will be done in a step-by-step manner, via the suggested best practice of using a Windows Server 2008 R2 server as the base operating system running on a virtual machine. This chapter will result in a standalone self-contained environment that will serve you very well as you learn SharePoint development, while teaching you the key ingredients that are required for you to be successful.
This chapter is not meant to be followed as a guide for building any type of production server - for example, it does not follow best practices for database naming or service accounts; having SQL and/or Active Directory on the same box; PowerShell automation, and so on. It may not be sufficient as a development standard in your organization, so please consult with your IT department before doing real SharePoint development for your clients. What if you have the Windows 7 64-bit version? Can you install and run SharePoint Server 2010 and all other required software and tools? Absolutely you can! Please use your favorite search engine to seek out the instructions to do so. However, I don't recommend it in practice, unless you have no other choice. SharePoint is a server-based piece of software, and installing this on your desktop will inflict a heavy price on performance due to the many services (such as Search) that SharePoint will want to run frequently! There are scripts out there that help shut down and start up these SharePoint services to help you out. However, I personally like the convenience of isolating SharePoint 2010 and related development activities to a virtual machine. You can completely shut this down and put it away for when you need it—by literally putting it on an external drive. Also, I find myself developing solutions for many different clients and projects, and in fact, I have set up a virtual machine for each project, so that, in future, I can pick up the project for that client from exactly where I left it, by simply firing up the corresponding virtual environment. We will be covering selection of a virtual environment in the next section. However, I thought I would mention that if you have a Windows Server 2008 R2 operating system on hand capable of running Hyper V, then you have the option of bypassing a full build, and downloading the Information Worker virtual machine, fully configured with SharePoint 2010, Visual Studio, and even FAST Search. Use your favorite search engine to find information worker vm download. Follow the instructions to download, set up, and activate this virtual machine on a trial basis (180 day maximum life span).
8
Chapter 1
Presuming you are still reading, you have decided that building your own virtual environment is the way to go. So let's get to it! I urge you to be patient during this task — this chapter will take a couple of days for you to complete, as you download many GBs of software and wait patiently through sometimes long installation processes. For the software that you will require throughout this chapter, you have two main choices: 1. Preferred: If you or the company that you work for has, access to a Microsoft Developer Network (MSDN) subscription, then you can download the required software that provides you with the corresponding activation keys. The main advantage of this approach is that your virtual environment will be permanent and licensed, thus you don't have to worry about the software expiring. 2. Alternative: Every single software product mentioned in this chapter is available for download on a trial basis from the Microsoft site. The main disadvantage of this approach is that each and every piece of software has a different trial use period. Many have the ability to extend the trial period, but eventually the environment will be rendered effectively inoperable and you will have to build the environment again from scratch. Also, note that the environment is not a properly licensed version, and is therefore only for trial, exploration, and evaluation uses.
Selecting your virtual environment Prisoners serving life sentences (in Canada) have what is known as a faint hope clause where you have a glimmer of a chance of getting parole after 15 years. However, those waiting for Microsoft to provide us a version of Virtual PC that can run Virtual Hard Drives (VHDs) hosting 64-bit operating systems (such as Windows Server 2008 R2), have no such hope of ever seeing that piece of software. But miracles do happen, and I hope that the release of a 64-bit capable Virtual PC renders this section of the chapter obsolete. If this has in fact happened, go with it and proceed to the following section.
Getting ready Head into your computer's BIOS settings and enable the virtualization setting. The exact setting you are looking for varies widely, so please consult with your manufacturer's documentation. This setting seems universally defaulted to off, so I am very sure you will need to perform this action.
9
Setting Up a Development Environment
How to do it... Since you are still reading, however, it is safe to say that a miracle has not yet happened. Your first task is to select a suitable virtualization technology that can support a 64-bit guest operating system. The recipe here is to consider the choices in this order, with the outcome of your virtual environment being selected: 1. Microsoft Virtualization: Hyper-V certainly has the ability to create and run Virtual Hard Disks (VHDs) with 64-bit operating systems. It's free—that is, you can install the Hyper-V role, but it requires the base operating system to be Windows Server 2008 R2. It can be brutal to get it running properly on something like a laptop (for example, because of driver issues). It won't be a good idea to get Windows 2008 Server running on a laptop, primarily because of driver issues. I recommend that if your laptop is running Windows 7, look at creating a dual boot, and a boot to VHD where this other boot option / partition is Windows Server 2008 R2. The main disadvantage is coming up with an (preferably licensed) installation of Windows Server 2008 R2 as the main computer operating system (or as a dual boot option). Or perhaps your company runs Hyper-V on their server farm and would be willing to host your development environment for you? Either way, if you have managed to get access to a Hyper-V server, you are good to go! 2. VMware Workstation: Go to http://www.vmware.com and download my absolute favorite virtualization technology—VMware Workstation—fully featured, powerful, and can run on Windows 7. I have used it for years and love it. You must of course pay for a license, but please believe me, it is a worthwhile investment. You can sign up for a 30 day trial to explore the benefits. Note that you only need one copy of VMware Workstation to create a virtual machine. Once you have created it, you can run it anywhere using the freely available VMware Player. 3. Oracle Virtual Box: Go to http://www.virtualbox.org/ and download this free software that will run on Windows 7 and create and host 64-bit guest operating systems. The reason that this is at the bottom of the list is that I personally do not have experience using this software. However, I have colleagues who have used it and have had no problems with it. Give this a try and see if it works as equally well as a paid version of VMware. With your selected virtualization technology in hand, head to the next section to install and configure Windows Server 2008 R2, which is the base operating system required for an installation of SharePoint Server 2010.
Installing and configuring Windows Server 2008 R2 SharePoint 2010 requires the Windows Server 2008 R2 operating system in order to run. In this recipe, we will configure the components of Windows Server 2008 necessary in order to get ready to install SQL Server 2008 and SharePoint 2010. 10
Chapter 1
Getting ready Download Windows Server 2008 R2 from your MSDN subscription, or type in windows server 2008 R2 trial download into your favorite search engine to download the 180-day trial from the Microsoft site. This book does not cover actually installing the base operating system. The specific instructions to do so will be dependent upon the virtualization software selected as per the Selecting your virtual environment recipe. Generally, it will be provided as an ISO image (the file extension will be .iso). ISO means a compressed disk image, and all virtualization software that I am aware of will let you mount (attach) an ISO image to the virtual machine as a CD Drive. This means that when you elect to create a new virtual machine, you will normally be prompted for the ISO image, and the installation of the operating system should proceed in a familiar and relatively automated fashion. So for this recipe, ready means that you have your virtualization software up and running, the Windows Server 2008 R2 base operating system is installed, and you are able to log in as the Administrator (and that you are effectively logging in for the first time).
How to do it... Log in as the Administrator. You will be prompted to change the password the first time—I suggest choosing a very commonly used Microsoft password—Password1. However, feel free to select a password of your choice, but use it consistently throughout this chapter. The Initial configuration tasks screen will come up automatically. On this screen: 1. Activate windows using your 180 day trial key or using your MSDN key. 2. Select Provide computer name and domain. Change the computer name to a simpler one of your choice. In my case, I named the machine OPENHIGHWAY. Leave the Member of option as Workgroup. The computer will require a reboot. 3. In the Update this server section, choose Download and install updates. Click on the Change settings link and select the option Never check for updates and click OK. Click the Check for updates link. The important updates will be selected. Click on Install Updates. Now is a good time for a coffee break! You will need to reboot the server when the updates complete. 4. In the Customize this server section, click on Add Features. Select the Desktop Experience, Windows, PowerShell, Integrated, Scripting, and Environment options. Choose Add Required Features when prompted to do so. Reboot the server when prompted to do so. If the Initial configuration tasks screen appears now, or in the future, you may now select the checkbox for Do not show this window at logon. We will continue configuration from the Server Manager, which should be displayed on your screen. If not, launch the Server Manager using the icon on the taskbar. 11
Setting Up a Development Environment We return to Server Manager to continue the configuration: OPTIONAL: Click on Configure Remote Desktop if you have a preference for accessing your virtual machine using Remote Desktop (RDP) instead of using the virtual machine's console software.
1. In the Security Information section, click Go to Windows Firewall. Click on the Windows Firewall Properties link. From the dialog, go to each of the tabs, namely, Domain Profile, Private Profile, and Public Profile and set the Firewall State to Off on each tab and click OK. 2. Click on the Server Manager node, and from the main screen, click on the Configure IE ESC link. Set both options to Off and click OK. 3. From the Server Manager, expand the Configuration node and then expand Local Users and Groups node, and then click on the Users folder. Right-click on the Administrator account and select Properties. Select the option for Password never expires and click OK. 4. From the Server Manager, click the Roles node. Click the Add Roles link. Now, click on the Introductory screen and select the checkbox for Active Directory Domain Services. Click Next, again click on Next, and then click Install. After completion, click the Close this wizard and launch the Active Directory Domain Services Installation Wizard (dcpromo.exe) link. Now, carry out the following steps: From the new wizard that pops up, from the welcome screen, select the checkbox Use advanced mode installation, click Next, and again click on Next on the Operating System Compatibility screen. Select the option Create a new domain in a new forest and click Next. Choose your domain (FQDN)! This is completely internal to your development server and does not have to be real. For book purposes, I am using theopenhighway.net, as shown in the following screenshot. Then click Next:
12
Chapter 1
From the Set Forest Functional Level drop-down, choose Windows Server 2008 R2 and click Next. Click Next on the Additional Domain Controller Option screen. Select Yes on the Static IP assignment screen. Click Yes on the Dns Delegation Warning screen. Click Next on the Location for Database, Log Files, and SYSVOL screen. On the Directory Services Restore Mode Administrator Password screen, enter the same password that you used for the Administrator account, in my case, Password1. Click Next. Click Next on the Summary screen. Click on the Reboot On Completion screen. Otherwise reboot the server after the installation completes. 5. You will now configure a user account that will run the application pools for the SharePoint web applications in IIS. From the Server Manager, expand the Roles node. Keep expanding the Active Directory Domain Services until you see the Users folder. Click on the Users folder. Now carry out the following: Right-click on the Users folder and select New | User
Enter SP_AppPool in the full name field and also enter SP_AppPool in the user logon field and click Next. Enter the password as Password1 (or the same as you had selected for the Administrator account). Deselect the option for User must change password at next logon and select the option for Password never expires. Click Next and then click Finish.
13
Setting Up a Development Environment 6. A loopback check is a security feature to mitigate against reflection attacks, introduced in Windows Server 2003 SP1. You will likely encounter connection issues with your local websites and it is therefore universally recommended that you disable the loopback check on a development server. This is done from the registry editor: Click the Start menu button, choose Run…, enter Regedit, and click OK to bring up the registry editor. Navigate to HKEY_LOCAL_MACHINE | SYSTEM | CurrentControlSet | Control | Lsa Right-click the Lsa node and select New | DWORD (32-bit) Value
In the place of New Value #1 type DisableLoopbackCheck.
Right-click DisableLoopbackCheck, select Modify, change the value to 1, and click OK Congratulations! You have successfully configured Windows Server 2008 R2 and are ready for our next recipe Installing and configuring SQL Server 2008 R2
There's more... The Windows Shutdown Event Tracker is simply annoying on a development machine. To turn this feature off, click the Start button, select Run…, enter gpedit.msc, and click OK. Scroll down, right-click on Display Shutdown Event Tracker, and select Edit. Select the Disabled option and click OK, as shown in the following screenshot:
14
Chapter 1
Installing and configuring SQL Server 2008 R2 SharePoint 2010 requires Microsoft SQL Server as a fundamental component of the overall SharePoint architecture. The content that you plan to manage in SharePoint, including web content and documents, literally is stored within and served from SQL Server databases. The SharePoint 2010 architecture itself relies on information stored in SQL Server databases, such as configuration and the many service applications. In this recipe, we will install and configure the components of SQL Server 2008 necessary to install SharePoint 2010.
Getting ready I do not recommend SQL Server Express for your development environment, although this is a possible, free, and valid choice for the installation of SharePoint 2010. In my personal experience, I have valued the full power and flexibility of the full version of SQL Server as well as not having to live with the constraints and limitations of SQL Express. Besides, there is another little reason too! The Enterprise edition of SQL Server is either readily available with your MSDN subscription or downloadable as a trial from the Microsoft site. Download SQL Server 2008 R2 Enterprise from your MSDN subscription, or type in sql server 2008 enterprise R2 trial download into your favorite search engine to download the 180-day trial from the Microsoft site.
15
Setting Up a Development Environment For SQL Server 2008 R2 Enterprise, if you have MSDN software, then you will be provided with an ISO image that you can attach to the virtual machine. If you download your SQL Server from the Microsoft site as a trial, extract the software (it is a self-extracting EXE) on your local machine, and then share the folder with your virtual machine. Finallly, run the Setup.exe file.
How to do it... Here is your recipe for installing SQL Server 2008 R2 Enterprise. Carry out the following steps to complete this recipe: 1. You will be presented with the SQL Server Installation Center; on the left side of the screen, select Installation, as shown in the following screenshot:
2. For the choices presented on the Installation screen, select New installation or add features to an existing installation. 3. The Setup Support Rules (shown in the following screenshot) will run to identify any possible problems that might occur when installing SQL Server. All rules should pass. Click OK to continue:
16
Chapter 1
4. You will be presented with the SQL Server 2008 R2 Setup screen. On the first screen, you can select an evaluation or use your product key (from, for example, MSDN) and then click Next. 5. Accept the terms in the license, but do not check the Send feature usage data to Microsoft checkbox, and click Next. 6. On the Setup Support Files screen, click Install. All tests will pass except for a warning that you can safely ignore (the one noting we are installing on a domain controller), and click Next, as shown in the following screenshot:
7. On the Setup Role screen, select SQL Server Feature Installation and click Next. 8. On the Feature Selection, as shown in the following screenshot, carry out the following tasks: In Instance Features, select Database Engine Services (and both SQL Server Replication and Full Text Search), Analysis Services, and Reporting Services In Shared Features, select Business Intelligence Development Studio, Management Tools Basic (and Management Tools Complete), and Microsoft Sync Framework 17
Setting Up a Development Environment Finally, click Next.
9. On the Installation Rules screen, click Next 10. On the Instance Configuration screen, click Next. 11. On the Disk Space Requirements screen, click Next 12. On the Server Configuration screen: Set the Startup Type for SQL Server Agent to be Automatic Click on the button Use the same account for all SQL Server services. Select the account NT AUTHORITY\SYSTEM and click OK. Finally, click Next. 13. On the Database Configuration Engine screen: Look for the Account Provisioning tab and click the Add Current User button under Specify SQL Server administrators. Finally, click Next
18
Chapter 1
14. On the Analysis Services Configuration screen: Look for the Account Provisioning tab and click the Add Current User button under Specify which users have administrative permissions for Analysis Services. Finally, click Next. 15. On the Reporting Services Configuration screen, select the option to Install but do not configure the report server. Now, click Next. 16. On the Error Reporting Screen, click Next. 17. On the Installation Configuration Rules screen, click Next. 18. On the Ready to Install screen, click Install. 19. Your patience will be rewarded with the Complete screen! Finally, click Close. The Complete screen is shown in the following screenshot:
20. You can close the SQL Server Installation Center.
19
Setting Up a Development Environment 21. Configure SQL Server security for the SP_AppPool account: Click Start | All Programs | SQL Server 2008 R2 | SQL Server Management Studio. On Connect to server, type a period (.) in the Server Name field and click Connect. Expand the Security node. Right-click Logins and select New Login. Use the Search function and enter SP_AppPool in the box Enter object name to select. Click the check names button and then click OK. In my case, you see the properly formatted THEOPENHIGHWAY\SP_AppPool in the login name text box. On the Server Roles tab, ensure that the dbcreator and securityadmin roles are selected (in addition to the already selected public role). Finally, click OK. Congratulations! You have successfully installed and configured SQL Server 2008 R2 Enterprise and are ready for our next recipe Installing and configuring SharePoint Server 2010.
Installing and configuring SharePoint Server 2010 We are ready to get to the main event of the chapter! In this recipe, we deal with the installation and configuration of SharePoint 2010 itself.
Getting ready Download SharePoint Server 2010 from your MSDN subscription, or type in sharepoint server 2010 trial download into your favorite search engine to download the 180-day trial from the Microsoft site. There are a few pre-requisites that need to be in place before the actual installation of SharePoint 2010. So, let us prepare a few ingredients for our recipe in advance. From Internet Explorer in the virtual machine: 1. Use your favorite search engine to find ado.net data services update for .net framework 3.5 sp1. Look for the Download Details link, which should be the first result (on the Microsoft site). This update is required in order to enable the REST–based data services that SharePoint 2010 relies upon. 2. Look for the x64 version and download it from the Microsoft site to the desktop of the virtual machine. Now, launch the installation. 20
Chapter 1
3. Click Yes when prompted with Do you want to install the following Windows software update?, which is shown in the following screenshot:
It is now time for our second coffee break. Click Close after the Installation Complete screen appears. We are nearly there! We are going to get into the SharePoint 2010 setup in order to install the required pre-requisites. If you have the MSDN software, you will be provided with an ISO image that you can attach to the virtual machine. If you downloaded it from Microsoft as a trial, download it to your virtual machine settings and sharing a folder from the host machine. Double-click the EXE file to launch the installation. Ensure your virtual machine has internet connectivity (test by using Internet Explorer to navigate to http://www.microsoft.com). Run Splash.hta. Installing the SharePoint 2010 pre-requisites: 1. Click on the Install Software Prerequisites link. Once you click on this link, you will see the following screen:
21
Setting Up a Development Environment 2. On the Microsoft SharePoint 2010 Products Preparation Tool - Welcome screen, click Next. 3. On the License Terms for Software Products screen, select the I accept the terms of the License Agreement(s) checkbox and click Next. 4. It is now time for our third coffee break. Watch for any prompts to reboot the server. 5. On the Installation Complete screen, click Finish. Now, let's get to the main recipe for which you have patiently been waiting for!
How to do it... Here is your recipe to install SharePoint 2010: 1. From the virtual machine CD Drive, run Splash.hta 2. Click on the Install SharePoint Server link. 3. On the Enter your product key screen, enter either your MSDN software key or your trial license key. 4. On the Read the Microsoft Software License Terms screen, select the checkbox I accept the terms of this agreement and click on Continue. 5. On the Choose a file location screen, click Install Now. The Installation Progress screen will show the proceeding of the installation. 6. Fourth coffee break? You might want to consider switching to decaf. 7. Note! This is a good time to actually take a snapshot of your virtual machine (or back it up), as this can be a good a starting point if in the future you have to set up another separate development machine. 8. When you see the Run Configuration Wizard, leave the checkbox Run the SharePoint Products Configuration Wizard selected and click Close. 9. On the SharePoint Products Configuration Wizard or the Welcome screen, click Next. 10. Click Yes to the warning regarding services that may need to be restarted. 11. On the Connect to a Server Farm screen, choose the option to Create a new server farm and click Next. 12. On the Specify Configuration Database Settings screen, specify your machine name in the Database Server text field. Use the SP_AppPool account, which was previously set up, and specify your password in the Password field of the Database Access Account section and click Next.
22
Chapter 1
13. On the Specify Farm Security Settings screen, choose a passphrase of Password1 (or the same as you have used for the Administrator account) and click Next. 14. On the Configure SharePoint Central Admin Web Application Page, select the checkbox Specify port number and enter the value 9999 (or a different port number of your preference). Leave the default authentication provider as NTLM and click Next. 15. On the Completing the SharePoint Products Configuration Wizard, click Next. 16. You are probably sick of coffee by now. Please take the time to check your e-mail, voice messages, Facebook, Twitter, and Linked In. 17. On the Configuration Successful screen, click Finish. Configure SharePoint 2010 via the Initial Farm Configuration Wizard: 1. Internet Explorer will open and navigate to the adminconfigintro.aspx page in Central Administration or the Initial Farm Configuration Wizard 2. On the Help make SharePoint better screen, select the option No, I don't wish to participate and click OK. 23
Setting Up a Development Environment 3. On the How do you want to configure your SharePoint farm? screen, click on Start the Wizard. 4. On the next screen in the Service Account, select Use existing managed account and ensure that the SP_AppPool account is selected. In the Services section, de-select Access Services and Word Automation Services and click Next 5. You are almost there! Reward yourself with a quick online match in your favorite game on your favorite console while you wait for the configuration to complete. 6. The wizard will have created a web application using the machine name, in my case, http://openhighway. You now get to create your very first Site Collection. Choose a title based on your company name (in my case, The Open Highway), choose the Team Site template and click OK, as shown in the following screenshot:
7. Your hard and patient work is rewarded with the This completes the Farm Configuration Wizard screen!
24
Chapter 1
8. Click on the Site URL to open and test that your new Team Site (and therefore SharePoint 2010) is operating correctly. DO NOT DESPAIR OR PANIC if you receive a rather nasty looking Error screen!
9. Many times in a development machine, depending on the resources assigned to it and the power of the desktop/laptop you are running with - navigation to the URL will simply TIME OUT. Breathe deeply. Refresh the browser. See! There is your Team Site. Congratulations! Bookmark this URL in your Internet Explorer favorites. The following screenshot shows my Team Site:
25
Setting Up a Development Environment Congratulations! You have successfully installed and configured SharePoint Server 2010 and are ready for our next step – to install Microsoft Office and your development tools.
There's more... From the home page of your Team Site, click on the Site Actions menu and select More Options. If you are prompted with the following screen with the Install Microsoft Silverlight link, then click on the link and take the opportunity now to install it! The user interface of SharePoint 2010 relies on Silverlight in many cases:
26
Chapter 1
When the Silverlight install downloads, click Run on the security warning on the Install Silverlight dialog and then click Install Now, as shown in the following screenshot:
Installing Microsoft Office 2010 Professional SharePoint 2010 is tightly integrated with, and was specifically designed to exploit, Microsoft Office 2010. So Office 2010 is a key tool for you to leverage in your SharePoint 2010 solutions, such as Word, Excel, and so on. Together with Visio and SharePoint Designer, these applications will be an important part of your development toolkit.
Getting ready Download Microsoft Office 2010 Professional Plus from your MSDN subscription, or type in Microsoft office 2010 professional plus trial download into your favorite search engine to download the 60-day trial from the Microsoft site. Wherever the software comes from, it will be presented as an EXE file. Make the file available to your virtual machine, for example, by going to your virtual machine settings and sharing a folder from the host machine. Or you could choose to download the software directly to your VM environment. Double-click the EXE file to launch the installation.
How to do it... Here is the recipe to install Microsoft Office Professional Plus 2010: 1. On the first screen, enter your product key (either MSDN or trial key). 2. Accept the terms of the license agreement and click Continue. 3. On the Choose the installation you want screen, click Customize.
27
Setting Up a Development Environment 4. (Recommended) On the next screen, Installation Options tab, mark Microsoft Access, Microsoft OneNote, Microsoft Outlook, and Microsoft Publisher as Not Available / not installed (red mark). You can always install these later if you wish to experiment with these applications with SharePoint. Finally, click Install Now.
5. Click Close when the installation completes. 6. We want to take a moment to initialize Office. From the Windows Start menu, launch Microsoft Word. 7. On the Help protect and improve Microsoft Office screen, select the option Don't make changes and click OK. 8. Take the opportunity to activate Office if this has not been (automatically) done already. 9. On the File tab in the ribbon, select Options. On the Word Options screen, select Trust Center on the left-hand side. Click the Trust Center Settings button. On the Trust Center screen, select Protected View on the left-hand side, as shown in the following screenshot. Deselect the first three checkboxes and click OK twice:
28
Chapter 1
10. Close Microsoft Word. Congratulations! You have installed Microsoft Office Professional Plus 2010.
Installing Visio Premium 2010 Here we will install Visio 2010, and later in this book, we will exploit the key new capability to design SharePoint workflows.
Getting ready Download Visio Premium 2010 from your MSDN subscription, or type in visio premium 2010 trial download into your favorite search engine to download the trial from the Microsoft site. If you have the MSDN software, you will be provided with an ISO image that you can attach to the virtual machine as a CD Drive. In this case, run SETUP.EXE. If you downloaded from Microsoft as a trial, make the file available to your virtual machine, for example, by going to your virtual machine settings, and sharing a folder from the host machine. In this case, run VisioSingleImage.exe.
How to do it... Here is the simple recipe to install Visio 2010: 1. On the first screen, enter your product key (either MSDN or the trial key) for Visio Premium Note that the edition is important, as Premium is the version that contains the SharePoint Workflow template. 29
Setting Up a Development Environment 2. Accept the terms of the license agreement and click Continue. 3. On the Choose the installation you want screen, click Install Now. 4. Click Close when the installation completes. Congratulations! You have installed Visio Premium 2010.
Installing SharePoint Designer 2010 In this recipe, we will install SharePoint Designer 2010. This is a powerful tool to create no-code solutions for SharePoint, but it is also a critical tool for the developer to exploit all of SharePoint's out-of-the-box capabilities before turning to code solutions in Visual Studio.
Getting ready SharePoint Designer 2010 is a FREE tool you can download from the Microsoft site and install without the need for a license key. Type sharepoint designer 2010 download into your favorite search engine to download the software. Make the file available to your virtual machine, for example, by going to your virtual machine settings, and sharing a folder from the host machine. Otherwise, you could choose to download the software directly to your virtual machine environment. Double-click the EXE file to launch the installation.
How to do it... Here is the simple recipe to install SharePoint Designer 2010: 1. Accept the terms of the license agreement and click Continue. 2. On the Choose the installation you want screen, click Install Now. 3. Click Close when the installation completes. Congratulations! You have installed SharePoint Designer 2010.
Installing Visual Studio 2010 Visual Studio 2010 is, believe it or not, the very first version of Visual Studio to incorporate a complete set of SharePoint 2010 development tools—ones that we of the SharePoint development world have been longing for for many years. You might overhear our excitement by murmuring "Wow!" We can press F5 and then we can even debug our software! For those ASP. NET developers who might be new to SharePoint development in 2010, you might say "Yeah, so what?" Of course you can! To which we might reply "But you don't understand!!!". Anyway, I digress, this could be the subject of another whole chapter about what we used to have to deal with, which would add absolutely no value whatsoever to your task at hand today. Suffice to say, Visual Studio is your primary SharePoint customization platform that you will discover as we go through the book. For now, let us get this tool installed into your virtual environment. 30
Chapter 1
Getting ready Download Visual Studio 2010 from your MSDN subscription—get the Ultimate version if you have it, download the Professional version, or type Microsoft visual studio 2010 ultimate trial into your favorite search engine to download the 30-day trial from the Microsoft site. Note that there is an option on the start page of Visual Studio to register the software and extend this trial for a further 60 days.
Either way, you will be provided with an ISO image that you can attach to the virtual machine as a CD Drive. Run Autorun.EXE.
How to do it... Here is the recipe for installing Visual Studio 2010: 1. On the Microsoft Visual Studio 2010 Setup screen, click on Install Microsoft Visual Studio 2010 2. Under the Help Improve Setup section, de-select Yes, send information about my setup experiences to Microsoft Corporation. 3. Click the Next button when it is available. 4. Click I have read and accept the license terms and click Next. 5. Under Select features to install, select the Custom option and click Next. 6. Deselect options for Visual Basic, Visual C++, Visual F#, Dofuscator, and SQL Server 2008 Express. Finally, click Install. 7. It's probably been long enough now, so have another coffee break and enjoy! 8. Click Finish when the installation completes and restart the server when prompted. 9. When rebooted, you can exit the wizard. Congratulations! You have successfully installed Visual Studio 2010.
How it works... You may now realize the point which we are at. I will put forward to you that by my experience, the most effective development platform for the SharePoint 2010 developer is a standalone virtual machine, where Visual Studio is installed within a full server-based installation of SharePoint 2010. Only time will tell whether you agree with me!
31
Setting Up a Development Environment
There's more... Start up Visual Studio 2010 and select your preferred environment settings (I choose the settings for Visual C# developer). Note the startup screen has the option of Extending Visual Studio (for an additional 60 days), in case you are using a trial version.
Installing recommended developer tools While Visual Studio 2010 certainly contains an excellent set of tools for the SharePoint 2010 developer, both Microsoft and the community at large are constantly providing you with further excellent sample code, utilities, and productivity aids. In this section, I recommend three key tools that you should have, and will direct you to a location where you can find more! 32
Chapter 1
How to do it... Here is the recipe for installing key SharePoint developer tools: 1. Mandatory for all SharePoint developers is the SharePoint 2010 SDK that includes many code samples and documentation. Use your favorite search engine to find Microsoft SharePoint 2010 SDK. 2. Highly recommended is the SharePoint Guidance available at http://www.microsoft.com/spg, with additional information available at http://spg.codeplex.com. 3. Highly recommended is the Community Kit for SharePoint. It is a set of best practices, templates, Web Parts, tools, and source code that enables practically anyone to create a community website based on SharePoint technology for practically any group of people with a common interest. It is available from http://cks.codeplex.com. 4. Highly recommended is the SharePoint Manager 2010 tool. It is a SharePoint object model explorer that enables you to browse every site on the local farm and view / change every property. It is from http://spm.codeplex.com. 5. Suggested are the Visual Studio 2010 SharePoint Power Tools, especially if you plan to develop Sandboxed Solutions. Use your favorite search engine to find Visual Studio 2010 SharePoint Power Tools. You have successfully installed the key tools every SharePoint developer should have at hand.
There's more... There are far too many excellent tools contributed by the community to be mentioned here, and more being created all the time. Some will be useful to accelerate some very specific development task. The primary source is CodePlex at http://www.codeplex.com. Search the site for SharePoint 2010, or more generally, SharePoint (as some tools support both the current and older versions of SharePoint).
Setting up your first web application You are ready to start developing on SharePoint 2010! Well almost. I am going to strongly recommend a development approach for you. I ask for a moment of patience as I explain. A specific SharePoint site (say, a Team Site) lives within a Site Collection. The site collection in turn lives within a Web Application (in IIS) and that web application will have an associated content database (literally, a SQL Server database that has been created to hold the content within the site collections of that web application). You may also know this as the SharePoint containment hierarchy.
33
Setting Up a Development Environment My advice then revolves around creating an entirely new web application for the project you want to work on. Let's say that project is a new collaboration Intranet for the company The Open Highway. I want to host that on the URL http://intranet.theopenhighway.net. So I'd like to create that very web application locally, including mimicking the URL I ultimately want to use. That way, when I actually want to deploy my application, I'll be quite certain that it should operate perfectly well in the target environment. But why do I say your first web application? Did SharePoint not create for itself the first content database, web application, and site collection with a Team Site at its root? Why, yes it did, located at a URL that is your machine name. In my case, that would have been http://OPENHIGHWAY. And the clarification is that SharePoint created that. The key word here is your first web application. Here are the advantages of creating a new web application for each client / project you want to work on, in addition to the deployment advantage already mentioned: ff
You are programming and testing against the real URL, which the application will run against
ff
Via a change to the Hosts file (you will see this shortly), you can switch on the fly between your local environment and a deployed environment (testing, production)
ff
Each web application has its own content database, which means your project / client is isolated from others and that implies easy backup and easy movement between environments
ff
Leave the original machine name web application intact so that if anything goes wrong you can rely on a pristine and reliable website to benchmark against
Please follow the best practice of creating a new and separate web application for your next project to see if you agree with this approach and benefits.
Getting ready You must first create a Hosts entry for the URL that you wish to use. Use Windows Explorer to navigate to the directory C:\Windows\System32\drivers\ and so on. Right-click on the Hosts file and select Open. On the Open With dialog, select Notepad and click OK. Copy and paste the three lines referring to the local intranet. Remove the hash marks (#) from lines two and three and then replace the local host with your URL. The result will look as follows:
34
Chapter 1
Close the notepad and save the changes.
How to do it... Here is the recipe to create a new web application: 1. Launch SharePoint Central Administration and click on Application Management. From this screen, click on Manage Web Applications and the following screen will be displayed:
35
Setting Up a Development Environment 2. In the ribbon, click on the New button. Fill in the screen similarly to the following screenshot. Choose your own name for the web application. Change the port to 80, and enter the URL that you created as the Host Header:
3. Scroll down the window. Leave the Security Configuration and Public URL sections at their defaults. As shown in the following screenshot, in the Application Pool section, select the Use existing application pool and select the one that begins with SharePoint – 80. In the Database Name and Authentication sections, change that unusably ugly GUID at the end of the database name to something meaningful. In my case, the database name is WSS_Content_TheOpenHighway:
36
Chapter 1
4. Scroll down to the bottom of the window. Leave all the remaining settings at their default and click OK. Please wait while your changes are processed. Truer words have never been spoken. Please wait patiently until you see the Application Created screen. Click on the Create Site Collection link, as shown in the following screenshot:
37
Setting Up a Development Environment Type in a Title for your website (in my case, The Open Highway Intranet) and leave the template selection at the default of Team Site, as shown in the following screenshot:
1. Scroll to the bottom of the window, enter the Administrator account as the Primary Site Administrator, and press OK, as shown in the following screenshot:
38
Chapter 1
2. You will be rewarded with the Top Level Site Successfully Created screen, as shown in the following screenshot:
3. Click on the URL link to launch your new Team Site! Don't forget! If you get the dreaded Error screen, it is just a time out. Refresh the browser and you will see your site. You will be prompted to log in. We will fix this in a moment. In the meantime, enter the Administrator and the password you chose (in my case, Password1). There are a couple of small helpful clean up notes, but otherwise you are ready to code! See you in Chapter 2, SharePoint Development with Visual Studio
39
Setting Up a Development Environment
There's more... With your Team Site open, add the URL to your favorites. Using the Tools menu drop-down, select Internet Options. Click on the Security tab and click on the Local Intranet icon, as shown in the following screenshot:
40
Chapter 1
Click on Sites and then Advanced. Enter *.theopenhighway.net in the Add this website to the zone: text box (actually, your URL) and click the Add button, as shown in the following screenshot. Then click Close and click OK thrice:
The advantage? With your URL in the Local intranet zone, Windows Authentication is now integrated. No more prompts to login!
41
2
SharePoint Development with Visual Studio In this chapter, we will cover: ff
Exploring Content Types and Site Columns
ff
Features and Solutions
ff
Creating new Site Columns
ff
Packaging SharePoint solutions
ff
Creating new Content Types
ff
Creating document libraries with Content Types
ff
Feature receivers
ff
List event receivers
ff
Feature staplers
Introduction A critical component of SharePoint is lists – the place we store data in SharePoint. The familiar document library is a special type of list that is designed to hold (primarily) Microsoft Office document types that people collaborate on, check out / check in, edit, version, and approve. There are many other "out-of-the-box" SharePoint lists you can create such as Announcements, Contacts, Events (calendar), Tasks, and more! Lists are where we store our data in SharePoint.
SharePoint Development with Visual Studio You should strive to use the out-of-the-box lists wherever possible. Next you should look to leverage an out-of-the-box list by "inheriting" from it and then customizing your own columns. If you wish, you may also create your own custom list from scratch. A list is composed of columns – collectively they form the schema for the list. In SharePoint terms, the schema is called a Content Type, and the individual columns within the schema are called Site Columns. For example, the Contacts Content Type has columns such as First Name, Last Name, and E-mail. Finally, an instance of a contacts list will use/attach the contacts list content type. If you have relational database expertise (such as with Microsoft SQL Server), the concepts introduced here will be familiar to you. Site Columns are equivalent to data types. The Data Definition Language (a script) will contain the definition / schema for a table. Running the script will create a physical table instance as determined by the schema. Why does this chapter on SharePoint development begin with a lecture on Site Columns, Content Types, and Lists? The proper creation, deployment, and management of SharePoint lists and schema is an important focus of the professional SharePoint developer. I cannot think of a better example to introduce all of the basics in such a way that you will be returning to this chapter again and again for guidance! We will be using the awesome Visual Studio 2010 SharePoint tools to create a custom document library for Proposals. The "Proposal" will be implemented with a Content Type (and Site Columns), and inherit from the out-of-the-box "document", and attached to the document library. We will also be exploring the practical use of more advanced techniques: Feature Receivers, Event Receivers, and Feature Staplers. This forms one of the most common "professional" patterns for a SharePoint developer! 1. Create Site Columns 2. Create Content Types 3. Create SharePoint list and attach Content Types 4. Provision with Feature Receivers and Feature Staplers 5. Control list events with Item Event Receivers This chapter will walk through the components of this pattern.
Exploring Content Types and Site Columns First let us look "behind the scenes" on a Contact List to discover how Microsoft put this list together with Site Columns and Content Types.
44
Chapter 2
Getting ready First, we need to create a site collection for this chapter: 1. Go to Central Administration and click on the link for Create Site Collections. 2. Ensure the correct web application is selected. Enter Chapter 2 for the title and Chapter2 in the textbox for the URL. 3. Leave the Template Selection defaulted to Team Site, and enter administrator for the Primary Site Collection Administrator. 4. Leave all other options at their default values. Scroll to the bottom and click on Ok. 5. When the screen Top Level Site Successfully Created appears, click on the link provided. Bookmark the site to your favorites. IMPORTANT NOTE: I will refer to this site as the Chapter 2 URL in this chapter, for later purposes of creating Visual Studio 2010 projects. For example, in my case, this URL is: http:// intranet.theopenhighway.net/sites/Chapter2.
6. From the home page of the Chapter 2 site, use the Site Actions menu and select More Options. Choose the type Contacts, enter name as MyContacts and click on Create. 7. After the creation of the MyContacts list, you should automatically be navigated to the new list. From the ribbon, choose the Items tab from List Tools. Select the New Item drop-down. Specifically, note that you are creating a "new contact". I added last name "Munster", first name "Eddy" (yes, from the 60's television show). Click on the Save button:
45
SharePoint Development with Visual Studio
How to do it... Now we are going to use the Contacts list as an example for demonstrating all the SharePoint components Microsoft used in putting this type of list together. First we look behind the scenes of the MyContacts list: 1. Navigate to the MyContacts list by clicking the link in Quick Launch (left-hand navigation). 2. In the ribbon, you will see List Tools. Click on the List tab. Click on List Settings in the ribbon. 3. Let us enable a "behind the scenes" view! Click on Advanced Settings. Click on Yes to Allow management of content types. Scroll down and click on OK to save this setting:
4. If you scroll down, you will now see a Content Types section has become visible. Note that the Content Type – Contact is assigned to the list:
5. If you scroll down further, you will see the Columns such as the First Name and the Last Name. These site columns are part of the Contact content type. 6. The columns in the MyContacts list were created as a result of the schema defined in the Contact Content Type. All Content Types can be found in a special list type called the Content Type Gallery. 7. From the Site Actions menu, choose Site Settings. Note the Galleries section:
46
Chapter 2
8. Click on Site content types and note the rather extensive selection available. The key options are there under Document Content Types and List Content Types. You will see Contact under the List section:
9. Click on Contact and it will take you to the details screen. Note all of the Site Columns that make up the Contact Content Type. 10. From the Site Actions menu, choose Site Settings. From the Galleries section, click on Site Columns. A very long list appears but I would encourage you to review and become familiar with it – you should always consider using an existing Site Column instead of "duplicating" something very similar for your own use. If we wish to follow "best practice" when creating our own Proposals document library, then it should be similarly backed by a Proposal Content Type that contains some out-of-the-box Site Columns and custom Site Columns.
There's more... As an exercise, repeat this recipe again, but this time try using the Shared Documents library in the Chapter 2 site.
Features and Solutions If you have professionally developed any type of application, then you must have had the requirement to "deploy" it. For example, if you are developing a Windows (desktop) application, you may have been asked to create a setup.exe for it – which in Visual Studio is a deployment project. If you are a web application developer, you can similarly add a "web setup project" and/or deploy your files in a CAB file (a special type of ZIP/compressed) file. Or perhaps you have experience with using MSI (windows installer) files. Regardless, when it is time to hand off your application to others you must "package" it for deployment. 47
SharePoint Development with Visual Studio SharePoint at its heart is an ASP.NET web application, so SharePoint understands special installer files called Solutions (creative name, right?). SharePoint solution files have the extension .wsp and are simply in CAB (compressed) format. The great news is that Visual Studio 2010 will automatically "package" your SharePoint customizations in WSP format – ready for you to deploy it to the world (of SharePoint)! In this case, the document library we ultimately create will be packaged as a WSP that you would ultimately deliver to a SharePoint Administrator for installation/deployment to the Test or Production SharePoint Farm. Packaged within the SharePoint Solution (WSP) file are one or more "Features" (again, a 9.5 on the name creativity scale). Each Feature, in turn, contains one or more SharePoint Project Items. I will explain the term "Feature" in more detail in one moment, but your goal throughout the remainder of this chapter will be to: 1. Create a Feature containing one SharePoint Project Item for Site Columns and another for Content Type. 2. Create a Feature containing one SharePoint Project Item for a List Definition (document library) and another for a List Event Receiver. 3. Package these two Features into a SharePoint Solution file. We will be proceeding to create the example, but at various points in the chapter, you will see the There's more section that will take you behind the scenes on what is happening with our Features and Solution. Here, we will explore how Microsoft implemented the Contacts Content Type and list schema.
How to do it... To explore Features from the SharePoint site perspective, go to the Chapter 2 site: 1. From the Site Actions menu, select Site Settings. 2. Notice under Site Collection Administration section, there is a Site Collections Feature link. 3. Underneath the Site Actions section, click on the Manage Site Features link. 4. Here, you can see that Microsoft itself has created a number of Features for SharePoint. The Activate and Deactivate buttons are simply a means of being able to turn the features on or off. Team Collaboration Lists is a feature that enables your ability to create all of the out-of-the-box lists, including a Contact list:
5. Go ahead and click on the Deactivate button for the Team Collaboration Lists feature. You may accept the warning that will pop up! Nothing "bad" will happen. 48
Chapter 2
6. Now go to Site Actions | More Options. You will find all of the out-of-the-box lists gone – you cannot select them to create them. Announcements, Contacts, Document Library, and so on. 7. Go back to Site Actions | Site Settings. Go to Manage Site Features and Activate the Team Collaboration Lists feature again. Verify using Site Actions | More Options that the list choices have returned. To explore Features from the physical implementation perspective, we need to examine the SharePoint installation folder. This is also referred to as the SharePoint Root folder. Open windows explorer and navigate to: C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14
And then: 1. Go to the Template sub-folder. Then underneath to the Features folder. From one perspective, SharePoint is a composition of a long list of Features – customizations and extensions that Microsoft has created for the product. 2. Find the TeamCollab folder and navigate to it. Inside you will find a Feature. xml folder. One of the purposes of this file is to describe the feature with a title, description, and icon. In this case, it displays the title Team Collaboration Lists and description Provides team collaboration capabilities…". 3. Navigate back up to the Features folder. Towards the top, go to the ContactsList sub-folder. Explore and you will find a feature.xml file, a schema.xml file that defines the schema for contact list (basically, it attaches the Contact Content Type), and a contacts.xml file that is responsible for providing a "list definition" – which we chose when we created an instance of the Contacts lists – MyContacts. We have explored Features from these two perspectives because, as a SharePoint developer, it will be your role to create new Features that get deployed to the SharePoint servers and will appear in the Feature list alongside the Microsoft provided ones! In our case, building up a SharePoint Solution as described in the introduction to this section.
Creating new Site Columns Before we can create Content Types, we need to define all of the individual Site Columns that will appear (ultimately) in our SharePoint lists. First, please look at the rather extensive set of Site Columns you get "out-of-the-box" and please feel free to reuse them instead of duplicating something similar.
49
SharePoint Development with Visual Studio The Site Columns available will depend first on the version of SharePoint you have available – Foundation, Standard, or Enterprise. Secondly, on which features (Standard, Enterprise, and Publishing) are enabled at the Site Collection and Site level.
In our case, we will be defining a document library to hold our proposals. We are going to define the following additional Site Columns that we require: ff
Proposal Amount: Number
ff
Proposal Client: Single line of text
ff
Proposal Type: Choice field For simplicity of the example, the client is a single line of text. This could have been another long list (the client list) and we could then define a "lookup" to be able to choose the client (for example, from a drop-down menu) for the proposal.
Getting ready We will create the Visual Studio project that we will be working with in this chapter: 1. Open Visual Studio 2010. From the File menu, select New | Project. 2. From the Installed Templates, navigate to the SharePoint 2010 section and select Empty SharePoint Project. In my case, I have named my project SP2010ProposalLibrary.
50
Chapter 2
Take a moment to look at the available Visual Studio SharePoint 2010 templates available to us. We will be taking advantage of some of these in the future chapters, such as the Visual Web Part in the next chapter:
3. On the SharePoint Customization Wizard screen, type in the "Chapter 2 URL" in the box What local site do you want to use for debugging?. Please select Deploy as a FARM solution and click on Finish. 4. In the Solution Explorer, right-click on the project and select Add | New Item.
51
SharePoint Development with Visual Studio 5. From the Installed Templates for SharePoint 2010, select Empty Element. Provide a name such as ProposalSiteColumns. Take a moment to view all of the available project items. There is not one specifically for Site Columns, but shortly we will be taking advantage of the items for Content Type and for List Definition. Click on Add:
6. You will see that a Feature was added called Feature1! We will review this in more detail later. For now, right-click on the node that says Feature1 and select Rename. Change the name to ProposalLibrary.
52
Chapter 2
Double-click on the Proposal Library Feature to see the Designer. Change the Title to something more meaningful – such as Proposal Library – as well as the Description. Change the Scope from Web (meaning a Site Feature) to Site (meaning a Site Collection Feature). As a best practice, I always recommend deploying Site Columns and Content Types to the Site Collection Feature level:
OPTIONAL: It is professional to add an icon (image) to your Feature. If you wish, choose any image – formats can be PNG, JPG, or ICO. Target an image size around 32 x 32, although this is not strict for dimension. Typically, you may choose a company logo or such.
To add the image to your Feature: 1. Right-click on your project and choose Add | SharePoint Images mapped folder. 2. Click on the SP2010ProposalLibrary folder that was created. Right-click on the folder and select Add | Existing Item. Navigate to the location for your image. 3. Double-click on the ProposalLibrary Feature to expose the properties window. Locate the Image URL property and type in the path and image relative to the images folder. In my case, it is SP2010ProposalLibrary/OpenHighwayLogo.png.
53
SharePoint Development with Visual Studio Your Solution Explorer should now look similar to the following:
Get ready to generate GUIDs! You will need to generate a lot of GUIDs as a SharePoint developer, as every unique thing you define will require a GUID. For example, Each Site Column, each Content Type, each Feature, each SharePoint Solution require unique GUIDs. GUIDGEN.exe installs with Visual Studio 1. From Visual Studio 2010, you can select the GUIDGEN tools from the Tools menu. 2. If it does not appear there, go to the Windows Start menu and type in GUID and choose GUID Generator. The following screen will appear. You can generate a New GUID (shows in the Result section) and use Copy to copy the value to the clipboard, which you can then Paste into Visual Studio. Select the Registry Format. Go ahead and "copy" a GUID now.
54
Chapter 2
How to do it... Ok, this is not the most exciting development you will do in your lifetime, as you will simply be hand typing some XML: 1. Open up the Elements XML file underneath ProposalSiteColumns. Enter the following XML. You can type in these very GUIDs, or you can generate your own in place of the ones provided: <Elements xmlns="http://schemas.microsoft.com/sharepoint/"> Internal External 55
SharePoint Development with Visual Studio 2. Right-click the SP2010ProposalLibrary project and select Deploy Solution. Wait until you see the Deploy Succeeded message in the bottom left-hand corner of Visual Studio. Let us go and verify that our Feature had been deployed and our Site Columns are defined. 1. Navigate to the Chapter 2 site. Select Site Actions | Site Settings. 2. Click on Site Collection Features that appears under the Site Collection Administration section. Notice that the Proposal Library is there and is activated:
3. Select Site Actions | Site Settings. Select the Site columns link in the Galleries section. Scroll down and you will see our three custom Site Columns in the Packt Publishing section:
Congratulations! You have created your first real Feature with Visual Studio 2010 SharePoint 2010 developer tools; created some Site Columns, deployed them to the sample site, and activated the Feature.
There's more... Here is some further information and explanation regarding Site Columns and the meaning of the Elements.xml file:
More Site Column types While these are not all the possible types of columns you can create as Site Columns, here are some of the most common ones: ff
Single line of text: Type="Text"
ff
Multiple lines of text: Type="Note"
ff
Choice: Type="Choice"
ff
Number: Type="Integer"
56
Chapter 2 ff
Currency: Type="Currency"
ff
Date and time: Type="DateTime"
ff
Yes/No: Type="Boolean"
What is Elements.xml? Elements.xml is a file that contains "provisioning instructions". In this case, instructions for creating several "Field" elements, also known as Site Columns. As we examine more SharePoint items, you will see different types of instructions. There can be one or more Elements.xml files in the SharePoint Solution file, and each of these instruction files will be referenced in the feature.xml file.
Note that Elements.xml is the default and the usual name for the file that contains provisioning instructions. However, the name can be one of your choice, and possibly more helpful such as ProposalSiteColumns.xml.
Packaging SharePoint Solutions Regardless of the type of Visual Studio Solution you develop – a regular web application or even a Windows application – eventually you will need to "package" it for the purpose of deploying it to another server or client computer. Such packaging is varied and may be a Cabinet (.CAB) file, a Microsoft Installer (.MSI) file, or a setup.exe (your classic setup wizard). The packaging format for SharePoint is a SharePoint Solution, having a file extension of .WSP. A server administrator will be able to deploy your WSP file with a combination of PowerShell commands and/or Central Administration. Some summary points about SharePoint Solution files: ff
They are files of CAB format that are used to package physical files up for deployment to SharePoint Servers
ff
Visual Studio 2010 SharePoint 2010 tools will automatically create this file for you, that is automatically do the "packaging"
ff
You can give WSP files to Server Administrators to install / deploy your features to other SharePoint environments (for example, Test or Production)
Although the packaging happens behind the scenes in Visual Studio, I would like to take a few moments to explore what is going on in more detail, as every SharePoint developer should have a thorough understanding of this topic.
57
SharePoint Development with Visual Studio
How to do it... We are going to explore the Packaging Designer: 1. Open the SP2010ProposalLibrary Visual Studio Solution you created in the last recipe. 2. Double-click on the Package node in your Visual Studio project. You can see (literally in visual representation) that the Proposal Library Feature is contained in our package – as well as the graphics files we deployed to SharePoint's Images directory:
The Package Designer is a visual representation of a special file in the SharePoint Solution (WSP) that is the Manifest. It is almost the dictionary definition of a manifest – primarily a list of files contained in the package and their respective deployment location relative to the SharePoint Root folder. Click on the Manifest tab at the bottom of the Package Designer to see what is / will be the manifest. xml file: <Solution xmlns=http://schemas.microsoft.com/sharepoint/ SolutionId="a91e3953-b6bd-4c34-8e76-d7db418152f1" SharePointProductVersion="14.0">
58
Chapter 2
3. You can view the actual WSP file in the Bin folder of your project. In your Visual Studio Solution Explorer, click on the SP2010ProposalLibrary project. Click on the Show All Files button near the top of the Solution Explorer. 4. Expand the Bin folder, and then expand the Debug sub-folder. Right-click on the SP2010ProposalLibrary.wsp file and select Copy. Right-click on the Debug folder and select Paste. Rename Copy of SP2010ProposalLibrary.wsp to SP2010ProposalLibrary.cab. Accept the warning, as we ARE changing the file extension to CAB. Your Solution should look as follows:
5. Right-click on the SP2010ProposalLibrary.cab file and select Open. Windows Explorer will open up to go "inside" this CAB file just as with a ZIP file. We can see the files contained inside:
So there is your behind the scenes look at how the SharePoint Solution package is created and what is "inside the box". 59
SharePoint Development with Visual Studio
There's more... Here is some further explanation on what is going on behind the scenes with SharePoint Solutions and Solution deployment.
How did my Feature get deployed and activated? When you right-clicked on your Visual Studio project and selected Deploy Solution – you kicked off the Solution deployment lifecycle! Let us presume now that your Features are deployed. You make some changes and use Deploy Solution again. First, SharePoint actually "uninstalls" the Features and deletes the existing solution (WSP) file from the server. Then, it adds the new solution (WSP) file and "installs" it. Next, the Visual Studio Solution deployment is kind enough to automatically activate the Feature for us, although technically that is an extra step. Go ahead and use Deploy Solution again. Then look at your output window to see the following: ------ Deploy started: Project: SP2010ProposalLibrary, Configuration: Debug Any CPU -----Active Deployment Configuration: Default Run Pre-Deployment Command: Skipping deployment step because a pre-deployment command is not specified. Recycle IIS Application Pool: Recycling IIS application pool 'SharePoint - 80'... Retract Solution: Deactivating feature 'SP2010ProposalLibrary_ProposalLibrary' ... Retracting solution 'sp2010proposallibrary.wsp'... Deleting solution 'sp2010proposallibrary.wsp'... Add Solution: Adding solution 'SP2010ProposalLibrary.wsp'... Deploying solution 'SP2010ProposalLibrary.wsp'... Activate Features: Activating feature 'ProposalLibrary' ... Run Post-Deployment Command: Skipping deployment step because a post-deployment command is not specified. ========== Build: 1 succeeded or up-to-date, 0 failed, 0 skipped ========== ========== Deploy: 1 succeeded, 0 failed, 0 skipped ==========
Note you can, for the sake of understanding, use "install" interchangeably with "deploy" and "uninstall" with "retract". But what are "Deleting Solution" and "Adding Solution" actually doing? It is quite literally copying the physical WSP file into the "SharePoint configuration database". Then from here is it deployed/installed to (all) the SharePoint web servers in the farm. 60
Chapter 2
Can I see my Solutions in Central Administration? You can physically see all of the WSP files on the server and the current status of solution deployment from Central Administration. In Central Administration, go to System Settings | Farm Management | Manage Farm Solutions. Click on the SP2010ProposalLibrary.wsp file in the list. You will see the following information:
Creating new Content Types Now we are ready to create the schema for our Proposal Library – through a Content Type that will inherit from Document and extend it with our custom Proposal site columns. The Content Type can also have associated a Microsoft Word template file, so that as you create a "New Proposal", Microsoft Word will come up and launch with a Proposal document template, instead of simply a blank document.
Getting ready Launch Microsoft Word and create a simple document to serve as your Proposal template. Save the file as ProposalTemplate.dotx.
How to do it... Open the SP2010ProposalLibrary Visual Studio Solution you created in the Creating new Site Columns recipe. We must first actually take a copy of our ProposalTemplate.dotx file and copy it into the file system of the content database. A file copy operation in SharePoint is accomplished via the "Module" provisioning instruction. You will see an example of this instruction as follows: 1. Right-click on the SP2010ProposalLibrary and select Add | New Item. 2. Select Module from the presented list, provide a name such as ProposalTemplate and click on the Add button. 61
SharePoint Development with Visual Studio 3. Right-click on the ProposalTemplate item in the project and select Add | Existing Item. Navigate to the location of the ProposalTemplate.dotx file and click on Add. 4. In the ProposalTemplate section, you will see a sample.txt has been generated. Right-click on sample.txt and delete this file. Edit the Elements.xml in the ProposalTemplate section. Change the URL attribute to _cts/Proposal/ProposalTemplate.dotx. The URL is the destination folder in the content database. Templates for Content Types (by best practice) go to a hidden _cts folder, and then to a sub folder that is the same name as the Content Type (which you will see shortly when we define the Content Type). Your Elements. xml file should now look as follows: <Elements xmlns="http://schemas.microsoft.com/sharepoint/"> <Module Name="ProposalTemplate">
Next we will implement a Proposal Content Type that features the Site Columns created in the last recipe, and attaches the Word Proposal template: 1. Right-click on the SP2010ProposalLibrary and select Add | New Item. 2. Select Content Type from the presented list, provide a name such as Proposal and click on the Add button. 3. A dialog will come up. Choose Document from the drop-down in response to the question What base content type should this content type inherit from?, and click on the Finish button. 4. In the Elements.xml file that opens, change the Name attribute to Proposal and the Group to Packt Publishing Content Types. Change the Description attribute to something such as Create a new proposal from a template. 5. Add three FieldRef entries, ensuring you use the EXACT same GUIDs that were generated in the Site Columns recipe. 6. Above the FieldRefs section, add a Folder node with the TargetName set to _cts/Proposal. 7. Underneath the FieldRefs section, add a DocumentTemplate node with the TargetName set to _cts/Proposal/ProposalTemplate.dotx. Add the XMLDocuments node exactly as shown in the following example.This node will add standard New, Edit, and Display forms to the document library.
62
Chapter 2
Your Content Type XML file should now look as follows: <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
4. Right-click the SP2010ProposalLibrary project and select Deploy Solution. Wait until you see the Deploy Succeeded message in the bottom left-hand corner of Visual Studio. A Feature Stapler took longer to explain than to actually do! The above line of code takes the GUIDs for our Features (which you can look up in the properties of each feature to verify), and "attaches" them to the team site definition. The code name for the team site is "STS#0", and the code name for a blank site is "STS#1". The short form "STS" comes from the "acronym" that is the directory name for the site definition. If you wish to view it, go to the SharePoint root folder, and then the subfolder TEMPLATE/SiteTemplates.
75
SharePoint Development with Visual Studio To test our Feature Stapler, we will create another site collection for this chapter: 1. Go to Central Administration and click on the link Create Site Collections. 2. Ensure the correct web application is selected. Enter Chapter 2 New for the title and Chapter2New in the textbox for the URL. 3. Leave the Template Selection defaulted to Team Site, and enter administrator for the Primary Site Collection Administrator. 4. Leave all other options at their default values. Scroll to the bottom and click on Ok. 5. When the screen Top Level Site Successfully Created appears, click on the link provided. 6. Note that the Libraries section now has a Proposals library! Feature Staplers are an excellent means of "adding" to an out-of-the-box site template and making it "your own". As you can staple any Feature, literally the possible uses for this simple technique are endless.
76
3
Web Part Development In this chapter, we will cover: ff
Exploring Web Parts in SharePoint 2010
ff
Creating and deploying Web Parts with Visual Studio 2010
ff
Creating Visual Web Parts
ff
Creating custom Web Part properties
ff
Creating Editor Parts for custom Web Part properties
ff
Creating Connected Web Parts
Introduction The most common development task that I have encountered is the creation of Web Parts. Web Parts are widgets or gadgets or otherwise small components of user interface functionality that you can flexibly incorporate into your web pages. As of SharePoint 2007, Web Parts are not unique to SharePoint—in fact, they are directly from ASP.NET's WebControls namespace. SharePoint 2010 has numerous out-of-the-box Web Parts that you can immediately incorporate on your page. So, please first familiarize yourself with all of these Web Parts and their capabilities! I am continually surprised by the number of times I have seen new SharePoint developers create a Web Part from scratch that effectively recreates out-of-the-box Web Part functionality. This chapter will be relevant for you if you have made the decision that you must create your own Web Part using Visual Studio 2010.
Web Part Development
Exploring Web Parts in SharePoint 2010 Even for you own custom developed Web Parts, you will interact with them the same way in SharePoint 2010 in terms of placing them on your web page. This recipe will facilitate understanding of the use of an out-of-the-box Web Part called the List View Web Part.
Getting ready Carry out the following steps in order to create a site collection for this chapter: 1. Go to Central Administration and click on the link for Create Site Collections 2. Ensure that the web application you created in Chapter 1, Setting Up a Development Environment is selected. Enter Chapter 3 for the title and Chapter 3 in the text box for the URL. 3. Leave the Template Selection with its default option Team Site, and enter administrator for the Primary Site Collection Administrator. 4. Leave all the other options at their respective default settings. Scroll to the bottom and click Ok. 5. When the Top Level Site Successfully Created screen appears, click on the link provided. Bookmark the site to your favorites. Note that I will refer to this site in this chapter as the Chapter 3 URL for creating Visual Studio 2010 projects later. For example, in my case, this URL is http://intranet.theopenhighway. net/sites/Chapter3.
6. From the home page of the Chapter 3 site, use the Site Actions menu and select View All Site Content. Under the Lists sections, click on Announcements. 7. Click on the Add new announcement link. On the screen that pops up, enter Chapter 3 for the Title and Welcome to Chapter 3 on Web Parts in SharePoint 2010. Click Save and navigate back to the home page.
How to do it... Carry out the following steps in order to explore the SharePoint 2010 List View Web Part: 1. Navigate to Chapter 3 URL through Internet Explorer (or any other browser). 2. On the Page tab in the ribbon, press Edit (to get the page in edit mode).
78
Chapter 3
3. Place your cursor at the end of the first paragraph at the centre of the page. Press Enter to go to a new line. Note that the Shared Documents section that you see is a view of the Shared Documents Library. This is a Web Part called the List View Web Part. 4. In the ribbon, click on the Insert tab of the Editing Tools section. Then click on Web Part in the Web Parts section of the ribbon. Your screen should now look similar to the following screenshot:
5. What you are viewing is the gallery of available Web Parts by category. You should already be in the Lists and Libraries category with the Announcements (list view) Web Part highlighted. Click on the Add button. 6. Hover over the Announcements Web Part that is added on the title, as shown in the following screenshot. When you do, you will see a small drop-down arrow appear to the right of Announcements. Hover on the arrow itself, and it will turn light blue with a tool tip of Announcements Web Part Menu:
79
Web Part Development 7. Click on the drop-down arrow, and from the menu, select Edit Web Part:
8. On the far-right-hand side is the Editor Zone section for the Web Part. It shows all of the available properties for the Web Part and allows them to be changed. For example, expand the Appearance section, change the Title to Important Announcements, and click OK. 9. On the Page tab, click Save and Close. Your page should now look as follows:
80
Chapter 3
In this recipe, we have learned how to put our web page into edit mode, how to insert a Web Part from the Web Part gallery, and how to modify the Web Parts properties in the Editor Zone. All of this will be important as we move on to create our own Web Parts!
There's more... Please feel free to go back to the Web Part gallery and explore some other out-of-the-box Web Parts. Do not forget to edit each Web Part to see what properties are available, and experiment with those as well.
Creating and deploying Web Parts with Visual Studio 2010 The goal of this recipe is to build an understanding of how Web Parts are created using Visual Studio 2010, and exactly how they are deployed into SharePoint.
Getting ready Carry out the following steps in order to create the Visual Studio project that we will be working with in this recipe: 1. Open Visual Studio 2010. From the File menu, select New | Project. 2. From Installed Templates, navigate to the SharePoint 2010 section and select Empty SharePoint Project. In my case, I have named my project SP2010WebPart. 3. On the SharePoint Customization Wizard screen, type in the Chapter 3 URL in the What local site do you want to use for debugging? textbox. Ensure that you select the Deploy as a FARM solution and click Finish. 4. In the Solution Explorer, right-click on the project and select Add | New Item. 5. From Installed Templates for SharePoint 2010, select Web Part (do not select Visual Web Part). Provide the name WebPartUsingRenderContents and click Add. 6. Repeat the preceding step to add another Web Part. Call this one WebPartUsingChildControls.
81
Web Part Development 7. Your Solution Explorer should now look similar to the following screenshot:
How to do it... A Web Part is an ASP.NET web control that does not have any user interface. If you wish to render UI, then you must do that yourself through code! Your choices with a Web Part in SharePoint include overriding one of the two provided methods: CreateChildControls or RenderContents. With CreateChildControls, you can literally create a control such as a Label or TextBox and add it to the controls collection. With RenderContents, you can emit HTML through an HTMLTextWriter object. Note that you should never override the Web Part's Render method because it is used internally by SharePoint and overriding it will break the rendering.
Carry out the following steps in order to create code for each of the Web Part's C# files: 1. In WebPartUsingChildControls.cs, change the code that appears similar to the following block of code. Here, we have created a Label, set its Text property, and then added it to the controls collection: Downloading the example code You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub. com/support and register to have the files e-mailed directly to you. 82
Chapter 3 protected override void CreateChildControls() { Label myLabel1 = new Label(); myLabel1.Text = "SharePoint 2010 Cookbook Chapter 3 - This Web Part uses CreateChildControls"; this.Controls.Add (myLabel1); }
2. In WebPartUsingRenderContents, we simply use the provided writer to create some HTML. Change the class to use the RenderContents method as follows: [ToolboxItemAttribute(false)] public class WebPartUsingRenderContents : WebPart { protected override void RenderContents(HtmlTextWriter writer) { writer.Write("SharePoint 2010 Cookbook Chapter 3 This Web Part uses RenderContents"); } }
3. The .webpart file performs two important functions. First, it points to the .NET assembly—the code—for running the Web Part. Second, it provides a title and description for the Web Part. Change the Title and Description properties in WebPartUsingRenderContents.webpart to something more meaningful: <properties> <property name="Title" type="string">Web Part Using Render Contents <property name="Description" type="string">This Web Part demos overriding Render Contents.
4. Change the Title and Description properties in WebPartUsingChildControls.webpart to something more meaningful: <properties> <property name="Title" type="string">Web Part Using Child Controls <property name="Description" type="string">This Web Part demos overriding Create Child Controls.
83
Web Part Development 5. The contents of the Elements.xml file perform the job of placing the Web Part(s) into the Web Part gallery (which is of the list type 113) by placing the .webpart file in this list. The Web Part gallery is physically located in your site collection at _catalogs\wp (check out that fact with SharePoint Designer for extra geek points). We will check out the Web Part gallery in the user interface shortly. The only change to make at this time in both of the Elements.xml files is the Value of Group. Here, I am changing it to Open Highway, but you can pick any value that you wish:
How it works... Now it is time to see the results of our work! Press F5. Click OK if prompted to modify the web.config for debugging and carry out the following steps: 1. The Chapter 3 website will be displayed automatically. Put the home page in Edit Mode. Place the cursor above the Important Announcements Web Part. 2. In the ribbon, select the Insert tab of the Editing Tools section. Click on Web Part in the Web Parts section of the ribbon. In the Categories section, click on the group you specified above its name (in my case. Open Highway). The top part of your screen should now look as follows:
3. Note that the Web Part title and description appear as we set them earlier! 4. Click Add. On the ribbon, select Insert Web Part again. Highlight the Web Part Using Render Contents and click Add. In the ribbon, go back to the Page tab and click the Save and Close buttons. Your screen should look like the following screenshot:
84
Chapter 3
Congratulations! You have created and deployed your first Web Part in SharePoint 2010!
There's more... Here are a few behind the scenes notes regarding SharePoint Web Parts.
Where did my Web Parts go? Note that if you end your debugging session, the web parts solution will be fully retracted. You will notice the web parts "disappear" from the home page. View the output window from Visual Studio 2010 after closing the browser to see the following information: Retract Solution: Deactivating feature 'SP2010WebPart_Feature1' ... Retracting solution 'sp2010webpart.wsp'... Deleting solution 'sp2010webpart.wsp'...
This is designed in such a way that you can continue the development and debugging of your Web Part. Instead, if you wish to make the Web Parts a permanent feature of your site collection, then right-click the project in the solution explorer of Visual Studio and click Deploy.
85
Web Part Development
Web Part features are Site Collection-scoped In order to have a look at the actual feature deployed for your Web Parts, from the Chapter 3 site, access the Site Actions menu | Site Settings. Select Site collection features under the Site Collection Administration section. Scroll down to see that the SP2010WebPart feature appears and is activated, as shown in the following screenshot:
Look at the Web Part Gallery Web parts are deployed to the Web Part gallery. From the Chapter 3 site, access the Site Actions menu | Site Settings. From the Galleries section, select Web Parts. Scroll to the last page to see the Web Parts created:
Select either of the Web Parts and click on the Edit icon. You will see the properties as you set them in Visual Studio in the .webpart files. The Edit page is shown in the following screenshot:
86
Chapter 3
Creating Visual Web Parts The exact problem with a plain old Web Part is the lack of ability to visually create your user interface. It is tedious to say the least to have to create the full user interface using CreateChildControls. Enter the Visual Web Part. The Visual Web Part uses the clever technique of incorporating a User Control (ASCX) file, and then the Web Part's CreateChildControls method loads the user control within its own control collection. So, you focus on visually creating your user interface, and let this project template take care of the rest for you!
87
Web Part Development
Getting ready Carry out the following steps in order to create the Visual Studio project that we will be working with in this recipe: 1. Open Visual Studio 2010. From the File menu, select New | Project. 2. From Installed Templates, navigate to the SharePoint 2010 section and select Visual Web Part. In my case, I have named my project SP2010VisualWebPart. 3. On the SharePoint Customization Wizard screen, type the Chapter 3 URL in the What local site do you want to use for debugging? textbox. You will only be able to select the Deploy as a FARM solution and click Finish. 4. I prefer to have something better named than the default VisualWebPart1, and it is easier to simply delete it. Right-click on the VisualWebPart1 node and select Delete. 5. In the Solution Explorer, right-click on the Project and select Add | New Item. 6. From Installed Templates for SharePoint 2010, select Visual Web Part. Provide the name AmazingVisualWebPart (or a name of your choice) and click Add. 7. Your Solution Explorer should now look similar to the following screenshot:
How to do it... First, let us look at the difference in the Web Part's C# file and carry out the following steps: 1. Open AmazingVisualWebPart.cs. Notice how it refers to the related user control. It then loads the control and adds it to the Web Part control collection. Put in another way, the user control runs inside the Web Part, or the Web Part is a container for the user control: 88
Chapter 3 public class AmazingVisualWebPart : WebPart { // Visual Studio might automatically update this path when you change the Visual Web Part project item. private const string _ascxPath = @"~/_ CONTROLTEMPLATES/SP2010VisualWebPart/AmazingVisualWebPart/ AmazingVisualWebPartUserControl.ascx"; protected override void CreateChildControls() { Control control = Page.LoadControl(_ascxPath); Controls.Add(control); } }
2. Change the Title and Description properties in AmazingVisualWebPart. webpart to something more meaningful: <properties> <property name="Title" type="string">Amazing Visual Web Part <property name="Description" type="string">This Web Part has a User Control to render the UI.
3. Edit the contents of each of the two Elements.xml files. The only change to make at this time in both of the Elements.xml is the Value of Group. Here I am changing it to Open Highway, but pick any value that you wish:
4. Now, to work on the inside part, the user control. Double-click the AmazingVisualWebPart.ascx file, and put the user control in Design Mode. Pin the toolbox in place so that you can drag-and-drop controls, as shown in the following screenshot. Create your very own truly amazing Web Part:
89
Web Part Development 6. In my case, I double-clicked the button and added a line of code so that we can demonstrate performing an action: protected void btnSayHello_Click(object sender, EventArgs e) { lblSayHello.Text = "Hello " + txtName.Text + "!!!"; }
How it works... Now, it is time to see the results of our work! Press F5 and carry out the following steps: 1. The Chapter 3 website will be automatically displayed. Put the home page in Edit mode. Place the just below the welcome text. 2. In the ribbon, select the Insert tab of the Editing Tools section. Click on Web Part in the Web Parts section of the ribbon. In the Categories section that appears, click on the group you specified above (in my case, Open Highway). The top part of your screen should now look similar to the following screenshot:
3. Note that the Web Part title and description appear as we set them earlier. 4. Click Add. In the ribbon, go back to the Page tab and click on the Save and Close buttons. Your Web Part should appear on the screen as you had designed it. Note that I used the Edit Web Part menu to change the Title property of Truly Amazing Web Part:
Congratulations! You have created and deployed a Visual Web Part in SharePoint 2010. 90
Chapter 3
Creating custom Web Part properties Web Parts are not really Web Parts, in my opinion, unless they are customizable! So far, they are just convenient user interface components. It is the Properties that turn it into a true Web Part! Customizable means that the Designer can change the appearance or behavior of the Web Part through its settings. Trivially, we did this with the Title property in the first recipe of this chapter. If you have not done so already, refresh your memory by going back to the last recipe and access the Web Part menu and Edit Web Part. On the right-hand side of the Editor Zone, you will see the following three categories: Appearance, Layout, and Advanced, as shown in the following screenshot:
Our goal in this recipe will be displaying text in the Web Part in a chosen custom color. In order to do that, we need to provide a choice of colors as a property in the Editor Zone.
Getting ready We will be continuing from the previous recipe, Creating Visual Web Parts. Please open this solution in Visual Studio and carry out the following steps: 1. Right-click on References and choose Add Reference. Add the .NET reference for System.Drawing. 2. Right-click on the SP201VisualWebPart project (not the solution), and choose Add | New Folder. 3. Name the folder Enums. 4. Right-click on the Enums folder and click Add | New Item 5. From the Visual C# section, select the Code category. Choose the code file and provide the name PrettyColors. 91
Web Part Development 6. Add a public enumeration and add your favorite selection of colors (that match the named / known colors in C#. For example, Blue will work, while Chartreuse will not), that is, any valid System.Drawing.Color. Your file will look similar to the following screenshot:
How to do it... Remember that the User Control is actually hosted inside of the Web Part, or put in another way, the Web Part is a container hosting the user control. So, if we set up and then change a public property on the Web Part, the user control will not know about this, or even have access to the Web Part property. Therefore, we are first going to set up communication between the Web Part and the user control by providing a reference to the Web Part for this purpose: 1. Open the previous code for the user control
AmazingVisualWebPartUserControl.ascx.cs. Put the following code right below the declaration of the AmazingVisualWebPartUserControl class. This allows the hosting Web Part to call the user control and provide a reference: // To "communicate" with the Web Part (this control's "host") we // need to set a reference to it protected AmazingVisualWebPart webPartReference; public void SetWebPartReference(AmazingVisualWebPart hostingWebPart) { this.webPartReference = hostingWebPart; }
2. Right below the above method, we will provide a method to allow the hosting Web Part to pass in the color property. This method will take the color and set the ForeColor property of the label control: // The Web Part will pass the color property into the user control public void SetTextColor(string color) { lblSayHello.ForeColor = System.Drawing.Color. FromName(color); } 92
Chapter 3
3. Next, open the Web Part class code file—AmazingVisualWebPart.cs. Enhance the CreateChildControls method as follows, which does the job of passing the reference of the Web Part host to the user control: // We will need to "communicate" with the User Control private AmazingVisualWebPartUserControl userControlReference; protected override void CreateChildControls() { Control control = Page.LoadControl(_ascxPath); Controls.Add(control); // Give the user control a reference to this Web Part userControlReference = (AmazingVisualWebPartUserControl) control; userControlReference.SetWebPartReference(this); }
4. Now that we have our communication channel set up between the user control and the Web Part, it is time to set up the Web Part properties. Open the Web Part class code file—AmazingVisualWebPart.cs. Put the following code right below the declaration of the AmazingVisualWebPart class. You will notice that this is simply a plain old property, with get and set methods that affect a private member declaration for holding a given PrettyColors value: // Define properties for the Web Part private PrettyColors _textColor = PrettyColors.Black; public PrettyColors textColor { get { return _textColor; } set { _textColor = value; } }
5. However, this will not automatically make the property exposed to the Editor Zone. If we decorate our public property with some attributes as follows, then SharePoint will expose the property automatically for us! Modify the code in step 4 as follows, and note the addition of the attributes Category, Personalizable, WebBrowsable, WebDisplayName, and WebDescription. These will be described in more detail in the following section: // Define properties for the Web Part private PrettyColors _textColor = PrettyColors.Black; [Category(Open Highway), Personalizable(PersonalizationScope.Shared), WebBrowsable(true), WebDisplayName(Select Text Color), WebDescription(Please pick a pretty color!)] public PrettyColors textColor { get { return _textColor; } set { _textColor = value; } } 93
Web Part Development 6. There is one last little item to take care of, that is, we need to implement the OnPreRender method in AmazingVisualWebPart.cs. Add one line of code that calls the SetTextColor method of the user control we implemented previously, and passed over to the Web Part's _textColor property. Finally, here is where the Web Part and the user control talk to each another: protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); userControlReference.SetTextColor(this.textColor. ToString()); }
How it works... Now, it is time to see our work's results! Press F5 and carry out the following steps: 1. The Chapter 3 website will be automatically displayed. Note that you may see the Truly Amazing Web Part already on your page from the last recipe. This is fine! Please skip the next three steps (that is, go to step 5). 2. Put the home page in Edit mode. Place the cursor just below the welcome text. 3. In the ribbon, select the Insert tab of the Editing Tools section. Click on Web Part in the Web Parts section of the ribbon. In the categories section that appears, click on the group that you have specified (in my case, Open Highway). The top part of your screen should now look similar to the following screenshot:
4. Note that the Web Part title and description appear as we set them earlier. 5. Click Add. On the ribbon, select Insert Web Part again. Highlight the Amazing Visual Web Part and click on Add. In the ribbon, go back to the Page tab and click the Save and Close button. Your Web Part should appear on the screen as you had designed it. Note that I used the Edit Web Part menu to change the Title property to Truly Amazing Web Part, as shown in the following screenshot: 94
Chapter 3
6. Click on the drop-down arrow and select Edit Web Part from the menu:
7. In the Editor Zone of the Web Part, collapse the Appearance section. You will see a new category called (in my case) Open Highway. Expand it to see our color selection. Use the drop-down to pick your favorite color—mine is Blue. Take special note of the Select Text Color, the value you have set previously in code for the WebDisplayName attribute. Take a moment to hover over the text Select Text Color. You will note a tool tip pop-up. Please pick a pretty color, that is, the value that you set previously for the WebDescription attribute. You should see the following screenshot:
8. Press OK on the Web Part Editor dialog. On the Page tab of the ribbon, click Save and Close. Your page should now look similar to the following screenshot. Note that the Hello text is now in blue:
Congratulations on updating your Web Part project to add your first set of properties! 95
Web Part Development
There's more... Sorry for glossing over those Web Part property attributes earlier. Let me cover those in more detail here in this section: [Category("Open Highway"), Personalizable(PersonalizationScope.Shared), WebBrowsable(true), WebDisplayName("Select Text Color"), WebDescription("Please pick a pretty color!")]
And, let us recall what the Editor Zone looks like as a result of the preceding code:
The definition for the attributes is: ff
Category: A grouping for your properties in the Editor Zone area. In this example, the Category that I would like the color selection to appear in is Open Highway. If the category does not exist, it will be automatically added. You can place more than one property into the same category.
ff
WebBrowsable: True is the only option here. It indicates that you are exposing the property to the Editor Zone. Without this attribute, nothing will appear in the Editor Zone related to this property.
ff
Personalizable: By exposing the Web Part property, you are making the Web Part personalizable. You need to specify a scope for the personalization, which is either Shared or User. We have chosen Shared, which means that a designer—someone with rights to edit the page—is able to make changes to the Web Part properties. The User scope is beyond the scope of this chapter, and in fact would require its own chapter to demonstrate it properly!
ff
WebDisplayName: The text that will be displayed as the label of the property.
ff
WebDescription: If you hover over the WebDisplayName (the label), this text will pop-up as a tooltip.
96
Chapter 3
Creating Editor Parts for custom Web Part properties As you have seen, you simply need to add attributes to a Web Part property and it will automatically appear in the Editor Zone. The Editor Zone will generate a basic control appropriate for the data type of the property—a drop-down control for an enumeration or a textbox for a string. However, let us say you declared a property intended to enter an e-mail address. How can you verify that the value the person has entered is a valid e-mail address? Unfortunately you cannot, and now understand the limitations of the automatic control generation. The solution to this is Custom Editor Parts! You can provide your very own user interface for the purpose of custom property editing. In this recipe, we will create a Custom Editor Part, complete with a custom user control for the purpose of making a better color selector.
Getting ready We will be continuing from the previous recipe, Creating custom Web Part properties. Please open this solution in Visual Studio. Visual Studio SharePoint 2010 tools do not have a New Item type for an Editor Part, which is what we actually need. However, we can create a new Web Part and then hijack the item for our purposes! 1. Right-click on the SP201VisualWebPart project (not the solution) and choose Add | New Item. 2. From the SharePoint 2010 category, choose Visual Web Part. Provide a name such as AmazingVisualEditorPart and click on Add. 3. Delete the following two files from this section: Elements.xml and AmazingVisualEditorPart.webpart—these files will not be required for our Editor Part. This section of your project should now look as follows:
97
Web Part Development 4. Open the file AmazingVisualEditorPart.cs and delete the following code lines: [ToolboxItemAttribute(false)]
Change the following line: public class AmazingVisualEditorPart : WebPart
Make it: public class AmazingVisualEditorPart : EditorPart
5. An Editor Part requires two mandatory methods to be implemented that we will discuss later, namely, SyncChanges and ApplyChanges. Add the following code below CreateChildControls: public override void SyncChanges() { EnsureChildControls(); } public override bool ApplyChanges() { EnsureChildControls(); return true; }
Perform a build on the solution to make sure everything is ok so far. Great! We have now found an easy way to create a framework for our Editor Part!
How to do it... First on the agenda, we will enhance our newly created Editor Part user interface (that is, the user control). Carry out the following steps in order to accomplish this: 1. Edit the user control file AmazingVisualEditorPartUserControl.ascx. Here, you will see the control in Design mode, as shown in the following screenshot. I have added some text, but most importantly, added a radio button list control to the page, named rbPrettyColors:
98
Chapter 3
2. In the code for the user control, we will populate the radio button list with the color entries in the PrettyColors enumeration. Edit the file AmazingVisualEditorPartUserControl.ascx.cs and place the following code immediately beneath the class declaration for AmazingVisualEditorPartUserControl: // Provide a default for the selected color private string _selectedColor = PrettyColors.Black.ToString(); protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); // Build a dynamic radio button list of available colors rbPrettyColors.Items.Clear(); foreach (object prettyColor in Enum.GetValues(typeof(PrettyColors))) { string thisColor = prettyColor.ToString(); ListItem colorOption = new ListItem(thisColor, thisColor); colorOption.Attributes[style] = color: + thisColor; rbPrettyColors.Items.Add(colorOption); } // Set the selected color according to passed in value rbPrettyColors.Items.FindByValue(_selectedColor).Selected = true; }
3. As we saw in the last recipe, remember that the user control is actually hosted inside the Editor Part, or put in another way, the Editor Part is a container hosting the user control. Therefore, we are going to set up communication between the Editor Part and the user control by providing a reference to the Editor Part for this purpose. So, the same procedure is used for our Editor Part as was for our Web Part: 4. Open the code for the user control, that is the
AmazingVisualEditorPartUserControl.ascx.cs file. Put the following code declaration immediately after the declaration of the _selectedColor variable. This allows the hosting Editor Part to call the user control and provide a reference: // To communicate with the editor part (this control's host) we // need to set a reference to it protected AmazingVisualEditorPart editorPartReference; public void SetEditorPartReference(AmazingVisualEditorPart hostingEditorPart) { this.editorPartReference = hostingEditorPart; } 99
Web Part Development 5. Insert the following property declaration immediately after the declaration of the _selectedColor variable. This property will ultimately allow the hosting Editor Part to synchronize the selected color with the current value of the Web Part property: // A public property to control the selected color in the // radio button list public string selectedColor { get { _selectedColor = rbPrettyColors.SelectedValue; return _selectedColor; } set { _selectedColor = value; } }
6. Next, open the Editor Part class code file: AmazingVisualEditorPart.cs. Enhance the CreateChildControls method as follows, which does the job of passing the reference of the Editor Part host to the user control: // We will need to communicate with the User Control private AmazingVisualEditorPartUserControl userControlReference; protected override void CreateChildControls() { Control control = Page.LoadControl(_ascxPath); Controls.Add(control); // Give the user control a reference to this Web Part userControlReference = (AmazingVisualEditorPartUserControl)control; userControlReference.SetEditorPartReference(this); }
7. Next, open the Web Part class code file: AmazingVisualWebPart.cs. Comment out the attributes that previously exposed the property to the Editor Zone automatically, as these have been replaced by the custom Editor Part: // When you have a custom Editor Part, the attributes to // automatically expose the property to the Editor Zone // are no longer required. //[Category(Open Highway), // Personalizable(PersonalizationScope.Shared), // WebBrowsable(true), // WebDisplayName(Select Text Color), // WebDescription(Please pick a pretty color!)]
100
Chapter 3 public PrettyColors textColor { get { return _textColor; } set { _textColor = value; } }
8. Now that we have our communication channel set up between the user control and the Editor Part, it is time to set up a communication channel between the Web Part and the Editor Part! This is the function of two very important (and required) methods of the Editor Part, that is, SynchChanges and ApplyChanges. The SynchChanges method is called when you edit the Web Part. We obtain the current value of the Web Part color property and pass it on to the user control embedded in the Editor Part: public override void SyncChanges() { EnsureChildControls(); // Obtain a reference to the hosting Web part AmazingVisualWebPart.AmazingVisualWebPart hostingWebPart = this.WebPartToEdit as AmazingVisualWebPart. AmazingVisualWebPart; // set selected color of the radio button list based // on the hosting Web Part pretty color property string selectedColor = hostingWebPart.textColor.ToString(); userControlReference.selectedColor = selectedColor; }
9. The ApplyChanges method is called whenever OK or Apply is clicked in the Editor Zone. We obtain the currently selected color from the user control embedded in the Editor Part, and then set the Web Part property: public override bool ApplyChanges() { EnsureChildControls(); // Obtain a reference to the hosting Web part AmazingVisualWebPart.AmazingVisualWebPart hostingWebPart = this.WebPartToEdit as AmazingVisualWebPart. AmazingVisualWebPart; // Get selected color of the radio button list and then // set the hosting Web Part pretty color property string selectedColor = userControlReference.selectedColor; // Convert color text to PrettyColors enumeration PrettyColors prettyColor = (PrettyColors)Enum.Parse(typeof(PrettyColors), selectedColor); hostingWebPart.textColor = prettyColor; return true; }
101
Web Part Development 10. Finally, we need to override a method called EditorPartCollection and the following code will add your custom Editor Part to the Editor Part Zone: public override EditorPartCollection CreateEditorParts() { // Create your OWN collection of custom Editor Parts! // In this case we only have one, but this could be many List<EditorPart> editorParts = new List<EditorPart>(1); EditorPart editorPart = new AmazingVisualEditorPart. AmazingVisualEditorPart(); editorPart.ID = this.ID + _EditorPart; editorParts.Add(editorPart); // Do not forget!
In addition to our custom editor Part,
we // need to return all of the OOTB editor parts as well. return new EditorPartCollection(base.CreateEditorParts(), editorParts); }
How it works... Now, it is time to see the results of our work! Press F5 and carry out the following steps: 1. The Chapter 3 website will automatically display. Note that you may see the Truly Amazing Web Part already on your page from the last recipe. This is fine! Please skip the next three steps (that is, go to step 5). 2. Put the home page into Edit mode. Place the cursor just below the welcome text. 3. On the ribbon, select the Insert tab of the Editing Tools section. Click on the Amazing Visual Web Part in the Web Parts section of the ribbon. In the Categories section that appears, click on the group you specified above (in my case, Open Highway). The top part of your screen should now look as follows:
102
Chapter 3
4. Note that the Web Part title and description appear as we set them earlier. 5. Click Add. On the ribbon, select Insert Web Part again. Highlight the Amazing Visual Web Part and click on Add. On the ribbon, go back to the Page tab and click on the Save and Close buttons. Your Web Part should appear on the screen as you had designed it. Note that I have used the Edit Web Part menu to change the Title property to Truly Amazing Web Part, as shown in the following screenshot:
6. Click on the drop-down arrow, and from the menu, select Edit Web Part, as shown in the following screenshot:
7. On the far-right-hand side is the Editor Zone for the Web Part. Collapse the Appearance section and you should see the following screen:
103
Web Part Development 8. Press OK on the Web Part editor dialog. On the Page tab of the ribbon, click on Save and Close. Your page should now look as follows. Note that the Hello text is now in blue:
Congratulations on updating your Web Part project to add a custom Editor Part!
There's more... As we saw earlier, the SynchChanges and ApplyChanges methods were required when we created an Editor Part. But how do these work? Certainly they were not explicitly called anywhere in our code. There is a magical hidden entity on a page that supports the placement of Web Parts—the SharePoint Limited Web Part Manager. Any communication between Web Parts (for example, connected Web Parts) or between Web Parts and Editor Parts is handled by the Web Part Manager. When a Web Part is put into edit mode, the Web Part Manager will automatically call SynchChanges and give you a reference to the Web Part being edited via this WebPartToEdit. When you click on Apply or OK in the Editor Zone, the ApplyChanges method is automatically called, again providing the same reference to the Web Part being edited.
Creating Connected Web Parts The most powerful feature of Web Parts is their ability to work together. Instead of trying to solve a particular problem in one big complicated Web Part, you can break the problem down into several smaller parts and then connect them. By Connected Web Parts, we mean that they are communicating with one another. For example, it is common for one Web Part to allow for the search and selection of information, such as a customer, and it then enables the information to be communicated to another Web Part that shows the customer details for the customer that was selected. In this case, normally something such as the Customer ID is communicated, and the second Web Part will be responsible for looking up the customer details using this information.
104
Chapter 3
Our communication will done by creating a custom interface. An interface, in .NET, is the definition of a class without the implementation. In our case, it is a contract for explicitly specifying the data that will be exchanged between the two (or more) Web Parts. If you program web services in Windows Communication Foundation, you may know that the Service Contract is just a special .NET interface defining the methods available in the service. The implementation of the methods is separate from the interface definition, and in fact, you could now have multiple code implementations from the interface and create a plug and play architecture. Connected Web Parts use a publish and subscribe method of communication. One Web Part will advertise (publish), that is, provide the information for a given interface. The interface could have defined, for example, a Customer ID. Other Web Parts will listen (subscribe) for the publisher to provide new information, receive that information (it will be pushed to them), and then act on it—such as display the customer details. Our recipes in this section will focus on the mechanics of creating connected Web Parts using custom interfaces. A simple example of this will be to choose the color in one Web Part, and have the background color of another Web Part changed to react immediately upon the new selection.
Getting ready Carry out the following steps in order to create the Visual Studio project that we will be working with in this recipe: 1. Open Visual Studio 2010. From the File menu, select New | Project. 2. From the Installed Templates, navigate to the SharePoint 2010 section and select Visual Web Part. In my case, I have named my project SP2010ConnectedWebParts. 3. On the SharePoint Customization Wizard screen, type the Chapter 3 URL in the What local site do you want to use for debugging? textbox. You will only be able to select Deploy as a FARM solution and click on Finish. 4. I prefer to have something better named than the default VisualWebPart1, and it is easier to simply delete it. Right-click on the VisualWebPart1 node and select Delete. 5. In the Solution Explorer, right-click on the project and select Add | New Item. 6. From the Installed Templates for SharePoint 2010, select Visual Web Part. Provide the name AmazingColorSelectorWebPart (or a name of your choice) and click on Add. 7. In the Solution Explorer, right-click on the Project and select Add | New Item.
105
Web Part Development 8. From the Installed Templates for SharePoint 2010, select Visual Web Part. Provide the name AmazingColorDisplayWebPart (or a name of your choice) and click on Add. 9. Rename the Feature from Feature1 to ConnectedWebParts. Open the Feature Designer and provide a Title and Description for the feature. 10. This is an optional step. As we did in Chapter 2, SharePoint Development with Visual Studio, add an image and set the ImageURL property of the Feature. 11. Your Solution Explorer should now look similar to the following screenshot:
How to do it... First, let us set some of the Web Part properties related to the deployment. Carry out the following steps in order to set these properties: 1. Change the Title and Description properties in AmazingColorDisplayWebPart.webpart to something more meaningful: <properties> <property name=Title type=string>Amazing Color Display Web Part <property name=Description type=string>This Web Part will display pretty colors.
106
Chapter 3
2. Change the Title and Description properties in AmazingColorSelectorWebPart.webpart to something more meaningful: <properties> <property name=Title type=string>Amazing Color Selector Web Part <property name=Description type=string>This Web Part will let you pick a pretty color.
3. Edit the contents of the Elements.xml that are in the AmazingColorDisplayWebpart and in the AmazingColorSelectorWebPart sections. The only change to make at this time in both of the Elements.xml is the Value of Group. Here, I am changing it to Open Highway, but you can pick any value that you wish:
4. You will see some familiarity and similarity to our previous two recipes. We will once again define our colors. 5. Right-click on References and choose Add Reference. Add the .NET reference for System.Drawing. 6. Right-click on the SP201ConnectedWebParts project (not the solution), and choose Add | New Folder. 7. Name the folder Enums. 8. Right-click on the Enums folder and click on Add | New Item 9. From the Visual C# section, select the Code category. Choose the code file and name it PrettyColors. 10. Add a public enumeration and add your favorite selection of colors (that match named / known colors in C#. For example, blue will work, chartreuse will not. That is, any valid System.Drawing.Color will work. Your file will look similar to the following screenshot:
107
Web Part Development 11. Let us now define the interface that will allow the Web Parts to be connected: 12. Right-click on the SP201ConnectedWebParts project (not the solution), and choose Add | New Folder. 13. Name the folder Interfaces. 14. Right-click on the Interfaces folder and click Add | New Item 15. From the Visual C# section, select the Code category. Choose the code file and provide a name such as IPrettyColors 16. Define the interface to look similar to the following screenshot. Only one piece of information will be passed between the connected Web Parts, and that is the selected color:
17. Similar to the last recipe, we will format a radio button list to display our colors and allow a person to choose one. Edit the user control file AmazingColorSelectorWebPartUserControl.ascx. Here, you will see the control in Design mode. I have added some text, but most importantly, I have added a radio button list control to the page, named rbPrettyColors. Then I have added a button to trigger the actual color change, as shown in the following screenshot:
108
Chapter 3
18. In the code for the user control, we will populate the radio button list with the color entries in the PrettyColors enumeration. Edit the file AmazingColorSelectorWebPartUserControl.ascx.cs and place / replace the following code immediately beneath the class declaration for AmazingColorSelectorWebPartUserControl: // Provide a default for the selected color private string _selectedColor = PrettyColors.Lime.ToString(); public string selectedColor { get { _selectedColor = rbPrettyColors.SelectedValue; return _selectedColor; } } protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); // Build a dynamic radio button list of available colors rbPrettyColors.Items.Clear(); foreach (object prettyColor in Enum.GetValues(typeof(PrettyCol ors))) { string thisColor = prettyColor.ToString(); ListItem colorOption = new ListItem(thisColor, thisColor); colorOption.Attributes[style] = color: + thisColor; rbPrettyColors.Items.Add(colorOption); } // Set the selected color rbPrettyColors.Items.FindByValue(_selectedColor).Selected = true; } // To communicate with the Web Part (this control's host) we need to // set a reference to it protected AmazingColorSelectorWebPart webPartReference; public void SetWebPartReference(AmazingColorSelectorWebPart hostingWebPart) { this.webPartReference = hostingWebPart; } protected void Button1_Click(object sender, EventArgs e) { _selectedColor = rbPrettyColors.SelectedValue; webPartReference.selectedColor = selectedColor; } 109
Web Part Development 19. Now, we will work on the user control to display our selected color. 20. Edit the user control file AmazingColorDisplayWebPartUserControl.ascx. Here, you see the control in Design mode. I have simply added a Panel control of size 200x200, and changed the background color to the default color, that is, black:
21. In the code for the user control, we will replace the panel's background color with the given color. Edit the file AmazingColorDisplayWebPartUserControl.ascx.cs and place / replace the following code immediately beneath the class declaration for AmazingColorDisplayWebPartUserControl: // Provide a default for the selected color private string _selectedColor = PrettyColors.Black.ToString(); // A public property to control the selected color in the panel public string selectedColor { set { _selectedColor = value; this.Panel1.BackColor = System.Drawing.Color.FromName(_selectedColor); } } // To communicate with the Web Part (this control's host) we // need to set a reference to it protected AmazingColorDisplayWebPart webPartReference; public void SetWebPartReference(AmazingColorDisplayWebPart hostingWebPart) { this.webPartReference = hostingWebPart; }
110
Chapter 3
22. So far, this has been very similar to earlier recipes in this chapter. We have not yet done anything to enable the Web Parts to communicate. That happens in the Web Part code itself. First, let us work on the Publisher, which is the color selector Web Part. 23. Open the AmazingColorSelectorWebPart.cs file for editing. 24. Change the class definition of the AmazingColorSelectorWebPart by adding IPrettyColorProvider at the end of the interface. It means this color selector Web Part will implement the IPrettyColorProvider interface: public class AmazingColorSelectorWebPart : WebPart, IPrettyColorProvider
25. Place the following code immediately beneath the class declaration for AmazingColorSelectorWebPart: // Visual Studio might automatically update this path when you change // the Visual Web Part project item. private const string _ascxPath = @~/_CONTROLTEMPLATES/ SP2010ConnectedWebParts/AmazingColorSelectorWebPart/ AmazingColorSelectorWebPartUserControl.ascx; // We will need to communicate with the User Control private AmazingColorSelectorWebPartUserControl userControlReference; protected override void CreateChildControls() { Control control = Page.LoadControl(_ascxPath); Controls.Add(control); // Give the user control a reference to this Web Part userControlReference = (AmazingColorSelectorWebPartUserControl)control; userControlReference.SetWebPartReference(this); } // Implementation of the IPrettyColor Interface private string _selectedColor; public string selectedColor { get { _selectedColor = userControlReference.selectedColor; return _selectedColor; } set { _selectedColor = value; } }
111
Web Part Development // Publish this interface to make it available to the // Web Part's connection menu [ConnectionProvider(Pretty Color Provider)] public IPrettyColorProvider GetPrettyColor() { return this; }
26. The new and most crucial lines are near the bottom, where we provide the implementation of the interface properties and declare to the ConnectionProvider attribute that we are available to publish pretty color information. 27. We finally need to look at the Consumer, the color display Web Part. 28. Open the AmazingColorDisplayWebPart.cs file for editing. 29. Place the following code immediately beneath the class declaration for AmazingColorDisplayWebPart: // Visual Studio might automatically update this path when you change // the Visual Web Part project item. private const string _ascxPath = @~/_CONTROLTEMPLATES/ SP2010ConnectedWebParts/AmazingColorDisplayWebPart/ AmazingColorDisplayWebPartUserControl.ascx; // We will need to communicate with the User Control private AmazingColorDisplayWebPartUserControl userControlReference; protected override void CreateChildControls() { Control control = Page.LoadControl(_ascxPath); Controls.Add(control); // Give the user control a reference to this Web Part userControlReference = (AmazingColorDisplayWebPartUserControl)control; userControlReference.SetWebPartReference(this); } // Declaring that we are interested in receiving Pretty Color // information private IPrettyColorProvider _prettyColorProvider; [ConnectionConsumer(Pretty Color Consumer)] public void GetPrettyColor(IPrettyColorProvider prettyColorProvider) { _prettyColorProvider = prettyColorProvider; } protected override void OnPreRender(EventArgs e) 112
Chapter 3 { base.OnPreRender(e); // If the Web Part is not connected, will display default // color of black. if (_prettyColorProvider == null) return; else if (!string.IsNullOrEmpty(_prettyColorProvider. selectedColor)) { // Pass the selected color to the user control userControlReference.selectedColor = _prettyColorProvider.selectedColor; } }
The new and most crucial lines are at the end, where we declare our interest in consuming pretty color information, and use the PreRender method to change the background color of the Panel when a change in color is triggered by the Provider / Publisher.
How it works... Now, it is time to see the results of our work! Press F5 and carry out the following steps: 1. The Chapter 3 website will automatically be displayed. Take the home page into Edit mode. Place the cursor just below the welcome text. 2. In the ribbon, select the Insert tab of the Editing Tools section. Click on Web Part in the Web Parts section of the ribbon. In the categories section that appears, click on the group you specified above (in my case, Open Highway). The top part of your screen should now look as follows:
113
Web Part Development 3. Note that the Web Part title and description appear as we set it earlier. 4. Select the Amazing Color Selector Web Part and click Add. On the ribbon, select Insert Web Part again. Highlight the Amazing Color Display Web Part and click Add. In the ribbon, go back to the Page tab and click the Save and Close button. Your Web Parts should appear as shown in the following screenshot:
5. Choose a different color, such as blue, and click the Change Color button. Wait! Nothing happened! Why? Because the Web Parts now need to be physically connected together. From the Web Part menu of the Amazing Color Selector Web Part, choose Edit Web Part. Then select the Web Part menu again and choose Connections | Send Pretty Color Provider To | Amazing Color Display Web Part, as shown in the following screenshot:
114
Chapter 3
You could actually initiate the very same connection from the color display Web Part. Try it! The wordings will be slightly different to reflect the get color from. However, it does not matter which way you establish the connection, as it will operate identically.
6. Choose a different color, such as blue, and click the Change Color button. Watch as the square turns blue! 7. When you change the value of the Property in the Provider that is part of the IPrettyColor interface, you trigger the notification out to all connected Web Parts. The Consumers have their event triggered, receive the updated information, and then can use it. In our case, the new color selection is passed and the display user controls change the background color of the panel control. 8. How did SharePoint know that the Web Parts could be connected? SharePoint is smart enough to examine all Web Parts on the page for the connection interfaces they expose (consume or provide). In this case, it matches up the provider of IPrettyColorProvider (the color selector Web Part) with the consumer (the color display Web Part). Congratulations! You have created and deployed connected Web Parts in SharePoint 2010!
115
4
Development with SharePoint Designer 2010 In this chapter, we will cover the following: ff
Exploring SharePoint Designer 2010
ff
Working with the XSLT List View Web Part
ff
Creating List Forms with SharePoint Designer
ff
Creating List Forms with InfoPath
ff
Enabling Inline Editing Mode
Introduction SharePoint Designer 2010 is the website editing tool for SharePoint. And typically, as the name implies, it is certainly the tool a web designer would use by editing web pages, HTML, styling (CSS), and much more. However, this chapter's focus is more on the use of SharePoint Designer 2010 for developers. This tool is a ground-up redesign from its 2007 predecessor, and it in fact ensures that the developer is a target audience for this tool. SharePoint 2010 is, at its heart, a product that a developer should consider first for configuring the product to do what your users want, before resorting to a code (Visual Studio) solution. You have already performed some out-of-the-box configuration using "in browser" tools, and SharePoint Designer 2010 can take configuration to another level.
Development with SharePoint Designer 2010 And, of course, SharePoint Designer 2010 requires a good exploration of its capabilities, so that you understand if some task would, in fact, require a Visual Studio customization.
Exploring SharePoint Designer 2010 In this recipe, we will create a site for Chapter 4, and edit it in SharePoint Designer 2010. Then we will make some simple changes to the site to demonstrate how the basics work. SharePoint Designer will be used in this and future chapters to explore the following: ff
Lists and Libraries: This chapter
ff
External Content Types and Data Sources: Chapter 6
ff
Workflows: Chapter 7
ff
Site Pages and Master Pages: Chapter 8
As an example, you could redo the Chapter 2 work regarding, Exploring Content Types and Site Columns, using SharePoint Designer 2010.
Getting ready First, we need to create a site collection for this chapter as follows: 1. Go to Central Administration and click on the link for Create Site Collections. 2. Ensure that the correct web application is selected. Enter Chapter 4 for the title and Chapter4 in the textbox for the URL. 3. Leave the Template Selection to the default value Team Site, and enter administrator for the Primary Site Collection Administrator. 4. Leave all other values at their respective default settings. Scroll to the bottom and click OK.
118
Chapter 4
5. When the Top Level Site Successfully Created screen appears, click on the link provided. Bookmark the site to your favorites. Important note: I will refer to the site in this chapter as the Chapter 4 URL, for creating Visual Studio 2010 projects later. For example, in my case, this URL is http://intranet.theopenhighway. net/sites/Chapter4
Please note that the Feature Stapler section from Chapter 2 has resulted in automatic creation of the Proposals library that we will be using in this chapter. I suggest creating ten or more proposals called Proposal1, Proposal2, and so on. Create some of them with the same client name, and create some variety in the other information.
How to do it... Let us explore the capabilities of SharePoint 2010 by opening the Chapter 4 Site Collection: 1. From the Windows Start menu, select All Programs | SharePoint | Microsoft SharePoint Designer 2010. 2. Click on the Open Site button.
119
Development with SharePoint Designer 2010 3. Enter the Chapter 4 URL for the Site Name and click Open. Enter the Administrator account, if prompted to log in. You should be presented with a screen similar to the following one:
The home page displays some of the site properties, which can be changed from here: 1. You will notice that the Chapter 4 title is a link. Click on it, and you can change the text, for example, to Chapter 4 - SharePoint Designer 2010. 2. Click on the link next to the description , and enter In this chapter we explore some of the capabilities of SharePoint Designer 2010. 3. Under the Settings section, click Enable Tree View. Please note carefully that the tab labeled Chapter 4, now has an asterisk next to it, indicating that there are unsaved changes:
120
Chapter 4
4. You MUST click the Save icon to save the changes, and please do so now. This is a recurring pattern in SharePoint Designer 2010; after making some edits and changes, don't forget to Save, as this is necessary for you to see the changes on your site:
5. Interestingly, some links will actually open the browser, and take you to the in browser customization. That means there is no SharePoint Designer-equivalent way of doing the same thing. For example, when you click on Change site theme, the browser opens up to allow you to select a new one. Select the Azure theme (or your own favorite theme) and click Apply. 6. Navigate in the browser to the Chapter 4 URL, and your site will now look similar to the following screenshot:
Congratulations! You have opened the Chapter 4 site in SharePoint Designer 2010, and made a few simple changes to the site.
121
Development with SharePoint Designer 2010
Working with the XSLT List View Web Part If you navigate currently to the Proposals library, you will see a rather uninteresting view—providing exactly none of the information we have available for the Proposals library:
The first thing we will take care of is to modify the default view to include information such as the client, proposal amount, and proposal type. Next, we'll demonstrate how powerful a view can be—with the ability to create grouping, roll ups, sums, and so on. There is a special out-of-the-box Web Part called the XSLT List View Web Part. As this Web Part implies, it can be configured to display a view of a SharePoint List or Library. In fact, the Shared Documents you see by default on a Team Site home page is an XSLT List View Web Part, configured to show the default view for a document library. These are exactly the same four columns shown by default for our Proposal Library – Type, Name, Modified, and Modified By. What is XSLT (Extensible Stylesheet Language Transformations)? From a programmer's point of view, it is a programming language for processing XML data and translating it to HTML output (primarily used for HTML, but really any other output format is possible). For the XSLT List View Web Part—we can apply an XSL transformation to the list view, for example, to apply conditional formatting. The good news is that with SharePoint Designer 2010, we can apply a wide range of transformations without actually having to know the XSLT language!
122
Chapter 4
Getting ready Ensure that SharePoint Designer 2010 has been opened to the Chapter 4 URL: 1. From the Navigation section, under Site Objects, choose Lists and Libraries. 2. In the Lists and Libraries that appear, select the Proposals library. 3. Note that we have the option of maintaining our Proposals list, many of which we will be exploring during this chapter. I will refer to the following screen in this chapter as the Proposals tab:
4. If, in future, I mention the Proposals tab, and it is NOT currently visible, then come back to these instructions to display it again.
123
Development with SharePoint Designer 2010
How to do it... We will modify the default view of the Proposals library to include all the important information for a proposal, including the type, client, and amount: 1. From the Proposals tab, under the Views section, click on All Documents. This is actually a link, which will open the AllItems.aspx page for the Proposals library in editing mode. 2. The AllItems.aspx page is a SharePoint site page that predominately features a We bPartPages:XsltListViewWebPart. You can find this easily in the Code View, or by clicking anywhere in the table in the Design view. 3. With the List View Web Part highlighted, note the new List View Tools section that appears in the ribbon with options such as Design, Web Part, and Table tabs. They appear as follows:
4. In the ribbon, under List View Tools, select Option tab, and click on the Add/Remove Columns icon.Click on the Add >> or