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/">
<XmlDocuments> <XmlDocument NamespaceURI="http://schemas.microsoft.com/ sharepoint/v3/contenttype/forms"> DocumentLibraryForm <Edit>DocumentLibraryForm DocumentLibraryForm
63
SharePoint Development with Visual Studio Your Solution Explorer should now look as follows:
Now, let us deploy the Solution and observe the results: 1. 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. 2. Select Site Actions | Site Settings. Click on Site Collection Features that appears under the Site Collection Administration section. Note that the Proposal Library is there and is activated (same Feature as with the Site Columns recipe):
3. Select Site Actions | Site Settings. Select the Site content types link in the Galleries section. Scroll down and you will see our three custom site columns in the Packt Publishing section:
4. Click on the Proposal Content Type, and note the Columns section includes the Site Columns we defined in a previous recipe:
64
Chapter 2
Congratulations! You have enhanced our Feature with Visual Studio 2010 SharePoint 2010 developer tools, created a Content Type (SharePoint schema), deployed this to the sample site, and activated the Feature.
Creating document libraries with Content Types Now we are going to create an actual document library with the Proposal Content Type attached.
How to do it... Open the SP2010ProposalLibrary Visual Studio Solution you created in the previous recipe: 1. Right-click on the SP2010ProposalLibrary and select Add | New Item. 2. Select List Definition From Content Type from the presented list, provide a name such as ProposalDocumentLibrary and click on the Add button. 3. A dialog will come up. Enter Proposal Document Library in response to the question What is the display name of the list definition?. Choose Proposal in the drop-down in response to the question What content type would you like to use for your list definition?. Ensure the checkbox is enabled for Add a list instance for this list definition, and click on the Finish button. 4. In the Elements.xml (with a ListTemplate node) file that opens, change the Description attribute to something such as List Definition for the Proposal Document Library. 5. In the Proposal Document Library section of the Solution, right-click on ListInstance1 and rename this to ProposalListInstance. Expand this node to expose the Elements.xml file underneath. 6. Edit the Elements.xml file (which will have a ListInstance node in it). Change the Title to Proposals. Change the URL to Lists/ ProposalListInstance. Finally, change the Description to Document Library to manage Proposals. 65
SharePoint Development with Visual Studio 7. Your Solution Explorer should now looks as follows:
Now, let us deploy the Solution and observe the results: 1. 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. 2. Select Site Actions | Site Settings. Click on Manage Site Features that appears under the Site Actions section. Note that the Proposal Library is there and is activated:
66
Chapter 2
3. Note that a Proposals link has appeared in the quick launch (left-hand navigation) under the Libraries section:
4. Click on the Proposals link. On the Documents tab of the ribbon, click on the drop-down New Document – and note the specific option to create a new "Proposal":
5. Note the document that comes up starts with the defined template, and the "document information panel" shows the meta data for the document (the Site Columns that were defined with the Content Type).
6. Close/save the document and provide a name such as Proposal for XYZ Corp. Congratulations! You have enhanced our Feature with Visual Studio 2010 SharePoint 2010 developer tools, created a list definition and list instance, deployed this to the sample site, and activated the Feature. 67
SharePoint Development with Visual Studio
Feature Receivers A Feature Receiver, simply put, is code that you (the developer) can choose to "attach" to a specific feature and that code will (generally) run when either you activate or deactivate the feature. More specifically, when you click on the Activate or Deactivate button. Feature Receivers are important as they provide you the opportunity to run any feature initialization that is required on Activate, and any clean up that is required on Deactivate. In our case, we wish to do the following: ff
On Activate: Set the Management of Content Types setting for the the Proposals list so we can "see" that the correct Proposal Content Type is configured with the list. Code is the only way to accomplish changing this setting.
ff
On Deactivate: Nothing happens to created lists, such as Proposals, when a Feature is deactivated. We are going to make the decision, for the sake of our example, that when the feature is deactivated, then the Proposals list will be deleted.
How to do it... Open the SP2010ProposalLibrary Visual Studio Solution you created in the previous recipe: 1. Underneath the Features node of the project, right-click on the ProposalLibrary Feature and select Add Event Receiver. 2. In the ProposalLibrary.EventReceiver.cs file that opens, uncomment the methods for FeatureActivated and FeatureDeactivating, and delete the remaining lines of comments. Provide the following lines of code for the FeatureActivated method: SPWeb site = properties.Feature.Parent as SPWeb; // Enable Management of Content Types for Proposals Library SPList listProposalLibrary = site.Lists["Proposals"]; listProposalLibrary.ContentTypesEnabled = true; listProposalLibrary.Update();
3. Provide the following lines of code for the FeatureDeactivating method: SPWeb site = properties.Feature.Parent as SPWeb; if (site != null) { SPList list = site.Lists.TryGetList("Proposals"); if (list != null) { list.Delete(); } } 68
Chapter 2
Done! That was easy! Now, let us deploy the Solution and observe the results: 1. 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. 2. Select Site Actions | Site Settings. Click on Manage Site Features that appears under the Site Actions section. Note that the Proposal Library is there and is activated:
3. Click on the Proposals link in the quick launch (left-hand menu). From the Ribbon Library tab, select Library settings. If you see the Content Types section exposed with our Proposal Content Type.
How it works... 1. This is an evidence that our Feature Activated code has executed. This should be clear, as we were working with the FeatureActivated method just a few minutes ago in the How to do it... section.
2. Select Site Actions | Site Settings. Click on Site Collection Features that appears under the Site Collection Administration section. For the Proposal Library Feature, click on the Deactivate button. You will get a warning You are about to deactivate the Proposal Library feature, click on the Deactivate this feature link. Note that the Active text disappears and the button has changed to Activate:
3. Now we have evidence that our Feature Deactivating code has executed, as you will see that the Proposals document library no longer appears in the quick launch – it has been deleted. 69
SharePoint Development with Visual Studio Actually, this is the first C# code you have written in this chapter! You have seen so far in this chapter that much can be accomplished through declarative (using XML) provisioning instructions. Anything is possible as far as initialization and clean up goes with Feature Receivers. For example, you may have decided to pre-populate your list with sample data. You will find many examples in your future where you will want to take advantage of the powerful capabilities provided by Feature Receivers!
List Event Receivers A List Event Receiver, simply put is code that you (the developer) can choose to "attach" to one or more lists and that code will (generally) run when either you add, delete, or update items on a list. List Item Event Receivers are important as they provide you the opportunity to provide some custom error handling or validation logic, and even cancel/prevent the add/ update/delete from taking place. The functionality is provided by inheriting from the SPItemEventReceiver class and overriding one of the following key methods : ff
ItemAdded
ff
ItemAdding
ff
ItemDeleted
ff
ItemDeleting
ff
ItemUpdated
ff
ItemUpdating
You will note from this list the term used – "Before" and "After" events. The before events end in "ing", are trapped before the, say update, takes place, and can be cancelled. The after events end in "ed" and will run after the list has been updated. Normally, if someone has the ability to add an item to a list, then they will have the ability to delete it. We wish to absolutely prevent anyone but the Site Collection Administrator from deleting items from the Proposal list. This problem could be solved by created a "custom permission level" where we remove the Delete ability, but in this case we don't wish to rely on this having been done. We wish to simply guarantee that it cannot be done by anyone except the administrator.
Getting ready For this example, you will require another user who is NOT a Site Administrator. You will log out as the Administrator and log back in as this other user.
70
Chapter 2
I have already created user "Eddy Munster" in Chapter 1 when creating my virtual machine. If you do not currently have another "normal" user, then use the Active Directory Users and Groups to add someone of your choosing – and provide a consistent password such as "Password1" as we used in Chapter 1. You must now also add the user to the "Members" group of the Chapter 2 site: 1. In the Chapter 2 site, select Site Actions | Site Settings. Under the Users and Permissions section, select People and Groups. 2. This should already default to being in the Chapter 2 Members group. Use the New drop-down and select Add Users. 3. In the Users/Groups box, enter the user ID you created. Use the Check Names button to verify. Click on OK. You should see something similar to the following:
How to do it... Open the SP2010ProposalLibrary Visual Studio Solution you created in the previous recipe: 1. Right-click on the SP2010ProposalLibrary and select Add | New Item. 2. Select Event Receiver from the presented list, provide a name such as ProposalLibraryEventReceiver and click on the Add button. 3. On the dialog that comes up, ensure the question What type of event receiver do you want? is answered List Item Events. Ensure Proposal Document Library is selected in response to What item should be the event source?. In the section Handle the following events, select An item is being deleted".
71
SharePoint Development with Visual Studio 4. In the ProposalLibraryEventReceiver.cs file, add the following code in the ItemDeleting event, immediately below the base.ItemDeleting line of code: if (!properties.OpenWeb().CurrentUser.IsSiteAdmin) { properties.Status = SPEventReceiverStatus. CancelWithError; properties.ErrorMessage = "Items can only be deleted by the Site Administrator"; properties.Cancel = true; }
5. Note that CancelWithError will cause the action to be rejected – in this case it will trap and prevent the item from being deleted. Now, let us deploy the Solution and observe the results: 1. 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. 2. Select Site Actions | Site Settings. Click on Manage Site Features that appears under the Site Actions section. Note that the Proposal Library is there and is activated:
4. Click on the Proposals link in the quick launch (left-hand navigation). On the Documents tab of the ribbon, click on the drop-down New Document and note the specific option to create a new "Proposal":
72
Chapter 2
5. Note the document that comes up starts with the defined template, and the "document information panel" shows the meta data for the document.
6. Close/save the document and provide a name such as Proposal for XYZ Corp. Close down "everything", including instances of Internet Explorer, Visual Studio, Microsoft Word, and so on. Log out of Windows and log back in as the user created in the Getting ready section of this recipe: 1. Open Internet Explorer and navigate to the Chapter 2 URL. 2. Click the Proposals link in the quick launch (left-hand navigation). 3. You can either use the checkbox to select the Proposal and use the Delete Document button in the ribbon, or use the drop-down from the document name (the "ECB" or Edit Control Block menu) to attempt to delete the document:
73
SharePoint Development with Visual Studio 4. You will get the following error, which verifies that our List Item Event Receiver is working!
5. Log out as the user and back in as the Administrator. Navigate back to this document in the Proposals library of the Chapter 2 site. Verify, as the Site Administrator, that you can delete the document. The set of List Event Receivers forms another important "building block" towards creating a complete and professional solution for SharePoint lists and schema. With Item Event Receivers, you can "guarantee" the behavior of your list as it is maintained – regardless of where it used, how it is used, or what security has been applied. Providing this consistency can be very important in meeting your requirements.
Feature Staplers When a new team site gets created, note that several lists and libraries get created automatically. In the Chapter 2 site, go to Site Actions | View All Site Content. Shared Documents, Tasks, Announcement, Calendar, Links all exist because the site definition for a team site (the provisioning instructions for creating the site) included the creation of these lists. What if you wanted to include the automatic creation of a Proposals document library every time a team site was created? You may think to modify the out-of-the-box team site definition to accomplish this. Please DO NOT ever modify an existing site definition, out-of-the-box or otherwise! You will introduce breaking changes if you do! You may then wish to create your own custom site definition, which can be a daunting and non-trivial task. In over 90% of cases, what you are looking to do can be accomplished using a Feature Stapler.
74
Chapter 2
A Feature Stapler is used to literally attach (or "staple", I guess) an additional Feature to an existing site definition. So, by stapling the Proposal Library feature to the team site definition, we will accomplish the behavior that every time a team site is created, we will see a Proposals library. Simple!
How to do it… Open the SP2010ProposalLibrary Visual Studio Solution you created in the previous recipe: 1. Right-click on the SP2010ProposalLibrary and select Add | New Item. 2. Select Module from the presented list, provide a name such as ProposalLibraryFeatureReceiver and click on the Add button. 3. Provide the following lines of XML to the Elements.xml file:
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> <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 << Remove buttons. In the Displayed Fields dialog, remove the Modified field, and add Proposal Client, Proposal Type, and Proposal Amount. Click OK, as shown in the following screenshot:
5. You will see that the view changes to your selected columns: 124
Chapter 4
6. We will now add conditional formatting to the Proposal Amount column. Click directly on one of the amounts and ensure that the field displays as follows:
7. In the ribbon, select the Conditional Formatting drop-down and choose Format Column, as shown in the following screenshot:
125
Development with SharePoint Designer 2010 8. Enter the criteria that the Proposal Amount is less than or equal to '1000':
9. Click on the Set Style button, and set the background to a different color (I've chosen a light blue color):
126
Chapter 4
10. Click OK, and you can see the immediate effect of this in your preview window! Note that you will only see changes in your preview window, if you have entered some of the proposal amounts to be $1,000 or less. Here is an example of what you might see:
11. DO NOT FORGET to press the Save icon to commit all your work. 12. In Internet Explorer, navigate to the Chapter 4 URL and then to the Proposals library. Note that the selected columns and the conditional formatting are in effect for your default view.
This time, let us create a new view and explore some other interesting capabilities, such as grouping and subtotaling: 1. From the Proposals tab, under the Views section, click on the New button. In the Create New List View dialog, enter a Name, such as AmountByClient, and click OK, as shown in the following screenshot:
2. From the Proposals tab, under the Views section, click on AmountByClient. This is actually a link, which will open the AmountByClient.aspx page for the Proposals library in editing mode.
127
Development with SharePoint Designer 2010 3. Click somewhere within the view or click on WebPartPages:XsltListViewWebPart in the code mode. In the ribbon, click on the Sort and Group icon on the List View Tools Options tab. Group by Proposal Client in an Ascending order, as shown in the following screenshot:
4. Just to keep things interesting, we will work with the view in the code mode! Within the view definition, locate the line that indicates the RowLimit of 30. Right underneath it, put the following code:
5. The entire code for the view should now appear as follows (Note that your GUID value will be different):
128
Chapter 4 30
6. DO NOT FORGET to press the Save icon to commit all your work. 7. You should see the data preview update similar to the following screenshot. Hit the Refresh Data button in the toolbar, if you do not immediately see the changes:
The fact that these views are available from the Proposals library itself is not that interesting. A better way to take advantage of your carefully crafted views is to feature them on a web page, such as the home page: 1. Open Internet Explorer and navigate to the Chapter 4 URL. 2. From the ribbon Page tab, put the page in Edit mode. Position the cursor above the Shared Documents Web Part and below the welcome text. 3. From the Editing Tools Insert tab, choose Web Part. In the Web Parts section, choose Proposals and click Add.
129
Development with SharePoint Designer 2010 4. From the Web Part drop-down menu, select Edit Web Part. In the Web Part Properties window, choose All Documents in the Selected View. Expand the Appearance section and change the Title to Proposal List. Click OK to close the Web Part Properties window:
5. We are going to insert Proposals again, but this time with our other defined view. Position the cursor above the Proposal List Web Part and below the welcome text. 6. From the Editing Tools Insert tab, choose Web Part. In the Web Parts section, choose Proposals and click Add. 7. From the Web Part drop-down menu, select Edit Web Part. In the Web Part Properties window, choose AmountByClient in the Selected View. For Toolbar Type, choose No Toolbar. Expand the Appearance section, and change the Title to Proposals By Client. Click OK to close the Web Part Properties window, as shown in the following screenshot:
8. In the ribbon on the Page tab, choose Save and Close. 130
Chapter 4
Examine the home page to see the results of your good work. The key here is that you can feature the same information multiple times, yet present the information in completely different and meaningful ways!
131
Development with SharePoint Designer 2010
Creating List Forms with SharePoint Designer SharePoint is great, because all you have to do is define your list and you get all of the forms for free, such as the form to edit the list item:
This is actually a physical ASPX page. In SharePoint Designer, go to the Proposals tab (or open Proposals from the Lists and Libraries section). Under the Forms section, you will see, for example, EditForm.aspx. But what if you wanted to have an edit form, where you were not able to edit the Title of the document? The following recipe will show you how to create an additional Edit form, and then customize it to your needs.
How to do it... Let us create a new edit form and then customize it: 1. From the Proposals tab, select the Forms section and click on the New button. In the Create New List Form dialog, enter a filename of EditRevised. Ensure that the Edit item form option is selected, as well as the checkbox for Set as default. Also, select the checkbox for Create link and provide a name for the Link and Command Name field. Click OK. This is shown in the following screenshot:
132
Chapter 4
2. From the Proposals tab, select the Forms section, click on EditRevised.aspx. This is actually a link which will open the EditRevised.aspx page for the Proposals library in editing mode. 3. First, we will change the Title field to be read only. On the Edit form, click on the Title field to highlight it. A chevron (a greater than sign) appears on the right-hand side of the control. Click on it, and you will see the Common FormField Tasks menu. Drop-down the Format as and select Label, as shown in the following screenshot:
133
Development with SharePoint Designer 2010 4. The control to show the value of Title changes from a textbox to a label control—effectively changing the field to be read only. Furthermore, I added a row at the top of the table to add a picture and some text. I changed all of the label descriptions and then added a footer. This is truly an ASPX page, so as a developer, you can really let your imagination run wild here:
5. DO NOT FORGET to press the Save icon to commit all your work. 6. Open Internet Explorer, navigate to the Chapter 4 URL, and go to the Proposals library. Pick any proposal and use the drop-down menu. You will notice our new form called Revised Edit. Select this option, as shown in the following screenshot:
134
Chapter 4
7. Our new form comes up to edit the Proposal properties, as shown in the following screenshot:
Congratulations on creating a new list edit form that is an ASPX page and then making modifications to that form.
Creating List Forms with InfoPath If you had even tried to create your own custom list forms with ASPX pages in the 2007 days, you would already know how astonishingly easy it is to do using SharePoint Designer 2010 (and not even Visual Studio). But it still generally takes the skills of a developer to properly work with an ASPX page. Isn't there another option? A no code option? I am certainly glad you asked, because the answer is, yes there is!. Have you developed electronic forms with InfoPath? This Microsoft Office Suite tool is a very powerful and capable forms designer. In SharePoint 2010, you can apply this tool to create list forms! Even if you do not have the Enterprise version of SharePoint (which is normally the version that has the InfoPath forms services required to do the browser-based rendering of InfoPath forms), you can still create list forms! Important note: Microsoft does NOT provide this feature for Document Libraries. So, unfortunately, this will not work for our Proposals library.
So this time, let us create our Edit form in InfoPath.
135
Development with SharePoint Designer 2010
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 Announcements list. 3. On the Announcements tab, under the Settings section, select the checkbox Display this list on the quick launch. 4. Click the Save icon to commit the change. 5. Open Internet Explorer and navigate to the Chapter 4 URL. 6. Click on the Announcements link in the Quick Launch. 7. Select Add a New Announcement Link. Notice that the labels have very plain descriptions. Note that the expiry date is blank. Enter a date in the past, and note that the date is accepted.
How to do it... We will create a new Edit form for our Announcements list, using InfoPath as follows: 1. From the Proposals tab, note the List Settings section of the ribbon. Click on the Design Forms in InfoPath icon and select Announcement, as shown in the following screenshot:
2. The InfoPath application will open and generate a starter form. Let us first add a default value for the Expires field. Click on the field to highlight it, as shown in the following screenshot:
136
Chapter 4
3. In the ribbon, under Control Tools, click on Control Properties near the bottom left-hand side:
4. On the Date Picker Properties, click the Format... button, as shown in the following screenshot:
5. Scroll down and chose the M/D/YYYY format. Click OK:
137
Development with SharePoint Designer 2010 6. On the Date Picker Properties, click the fx button next to the Value textbox. When the Insert Formula screen appears, click on the Insert Function… button. Select the Date category and select the function today. Press OK, as shown in the following screenshot:
7. The Insert Formula screen should now look as follows. Click OK:
8. The Date Picker Properties screen should now look as follows. Check the Cannot be blank checkbox. Click OK:
138
Chapter 4
9. Now, we are going to add a validation rule to the expiry date to ensure that it cannot be before today's date. In the ribbon, click the Add Rule drop-down. Then select Is Before... | Show Validation Error, which is shown as follows:
139
Development with SharePoint Designer 2010 10. The Rule Details screen will be displayed. In a similar fashion to setting the default value for Expires to today(), click the fx button, then the Insert Function button, and then select Date | today(). Click OK:
11. Note that the Rules task pane appears, where you can confirm the details of the rule you just created. This is shown as follows:
12. Let us presume that we do NOT want people to upload Attachments to the Announcement. Highlight the table row. Right-click and select Delete | Rows:
140
Chapter 4
13. Similar to the ASPX Edit form of the previous recipe, I've added a top row with a graphic and text. I have also added footer text and changed the labels of the field. My form now looks as follows:
14. On the File tab, under the Info section, click on the Quick Publish icon, as shown in the following screenshot:
15. InfoPath seems to know that you are anxious to test your new form! Click on the link to Open the SharePoint list in the browser, as shown in the following screenshot:
141
Development with SharePoint Designer 2010 We can now test our new form as follows: 1. From the Announcements list, click on Add new announcement. Note that the new InfoPath form pops up. Note the expiry date has defaulted to today(). Change the date to yesterday or some other date in the past. The field turns red, and if you hover over the date, you will see a pop-up with the validation text from the defined rule as follows:
2. Change the date back to today() (or later). Enter other properties and press Save. Congratulations on using InfoPath to customize SharePoint List forms! InfoPath is a great tool to take control of item editing with powerful no code validation capabilities.
Enabling Inline Edit mode So far, when you edit a SharePoint list item, a form pops up for Edit. If you need to edit many items, there is a more convenient way, which is to enable a little known feature called Inline Edit using SharePoint Designer 2010. This recipe will demonstrate how to enable and use this feature.
How to do it... Ensure 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. 142
Chapter 4
3. From the Proposals tab, under the View section, click on All Documents. This is actually a link that will open the AllItems.aspx page for the Proposals library in editing mode. 4. With the List View Web Part highlighted, note the new List View Tools section that appears in the ribbon with Options, Design, Web Part, and Table tabs, as shown in the following screenshot:
5. Click on the Inline Editing icon. And that is it! 6. Press the Save icon to commit the change. Now, we can test the new Inline Editing mode as follows: 1. Open Internet Explorer and navigate to the Chapter 4 URL. 2. Click on the Proposals library in the Quick Launch. 3. If you hover over a line, note that the Edit icon now appears. Click on the Edit icon:
4. Note that the fields open for editing inline. Make a change and click the Save icon:
This is a great and easy way to provide another convenient method for editing SharePoint list items.
143
5
Using the ClientOM and REST In this chapter, we will cover: ff
Retrieving data using LINQ to SharePoint
ff
Retrieving SharePoint data using the list data service
ff
Working with the .NET Client Object Model
ff
Working with the Silverlight Client Object Model
Introduction The purpose of SharePoint lists is to store data. This may be information in the form of a contacts list about your customers or the document library we previously created to store proposals (Microsoft Office documents in general). As a SharePoint developer, you will want to access the data both within the SharePoint environment – but equally importantly from outside the SharePoint environment. For example, you may have a Windows Forms application, Windows Presentation Foundation application, a Silverlight (Rich Internet) application, or a regular web application in which you are using JavaScript. And in these applications, you may need to access data that is in fact stored within one of your SharePoint site collections. In the example for this chapter, let us say we are interested in the Top 5 proposals from our Proposals library – ranked in descending order by dollar value.
Using the ClientOM and REST
Retrieving data using LINQ to SharePoint You can write a book on LINQ. Many books, in fact, have been written on LINQ. I suggest you seek out 101 LINQ Samples on MSDN to get a feel for the vaguely SQL-like syntax for querying data. You can use LINQ to query just about anything, as Microsoft has "providers" for SQL data, XML, objects, and now…. SharePoint! The role of the provider is to translate the LINQ query into the "native" query format – in the case of SharePoint that is actually CAML (Collaborative Application Markup Language). But to use LINQ against SharePoint, you need a "data context" – physically a C# class that is generated from the data source – meaning in our case the SharePoint lists in your site. There is a command-line utility called SPMetal.exe, whose purpose in life – besides having the coolest name Microsoft has come up with – is to generate said C# file when pointed at a SharePoint site. It is a bit of a bother to run that utility, so the recently available Visual Studio 2010 SharePoint Power Tools integrate this tool into Visual Studio. It was a suggested part of your development environment setup in Chapter 1, Setting Up a Development Environment, but we will download this as part of the Getting ready exercise.
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 5 for the title and Chapter5 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 Top Level Site Successfully Created screen appears, click on the link provided. Bookmark the site to your favorites. IMPORTANT NOTE: I will refer to this site in this chapter as the Chapter 5 URL, for later purposes of creating Visual Studio 2010 projects. For example, in my case, this URL is http://intranet.theopenhighway.net/sites/ Chapter5: .
The Feature Stapling from Chapter 2, SharePoint Development with Visual Studio, has resulted in the automatic creation of the Proposal library we will be querying. Create six or more Proposals called "Proposal1", "Proposal2", and so on. Ensure the amounts are different as our Top 5 will be based upon this amount. 146
Chapter 5
I strongly recommend you download the following productivity tool. It is a brilliant little Visual Studio Server Explorer extension from fellow SharePoint MVP Waldek Mastykarz that will greatly help with your SharePoint LINQ development. I will be using it during the recipe: 1. Use your favorite search engine to find "Imtech Get SPMetal Definition Extension". Download and install the software. 2. We will create the Visual Studio project that we will be working with in this recipe. Open Visual Studio 2010. From the File menu, select New | Project. 3. From the Installed Templates, navigate to the SharePoint 2010 section and select Empty SharePoint Project. In my case, I have named my project Chapter5LINQWebPart. 4. On the SharePoint Customization Wizard screen, type in the Chapter 5 URL in the box What local site do you want to use for debugging?. Ensure that you select Deploy as a FARM solution and click on Finish. 5. In the Solution Explorer, right-click on the project and select Add | New Item. 6. From the Installed Templates for SharePoint 2010, select Web Part (Note: Do NOT select Visual Web Part). Provide the name WebPartLINQProposals. Click on Add. 7. Rename the Feature from Feature1 to WebPartLINQProposals. Open the Feature Designer and provide a Title and Description for the Feature. 8. Optional: As we did in Chapter 2, add an image and set the ImageURL property of the Feature. Your Solution Explorer should now look similar to the following:
147
Using the ClientOM and REST
How to do it... First we need to generate our Data Context. And Waldek's utility is going to help us out. And it gives us an opportunity to check out the SharePoint Connections section of Server Explorer! 1. Open the Server Explorer (same area as your ToolBox). If you do not see it, then you will find it under the View menu of Visual Studio. 2. Right-click on SharePoint Connections and add the Chapter 5 URL of your site collection. 3. Expand the nodes. Expand into Lists and Libraries, and then Document Libraries. Your Server Explorer should look similar to the following:
4. Right-click on Proposals and select Get SPMetal definition:
148
Chapter 5
5. Wait patiently, and a Proposals.cs file will appear in your Visual Studio Solution. Open the Proposals.cs file to examine the generated content. You will see the definition for the ProposalsDataContext – exactly what we will need for SP LINQ! Now it is time to write our first SharePoint LINQ Query! 1. Open the WebPartLINQProposals.cs file and add the following code in the CreateChildControls method. The first thing we should do is ensure that the Proposals list actually exists in this site (that is, the Proposal Library Feature has been activated on this site): const string PROPOSAL_LIBRARY = "Proposals"; Label myLabel1 = new Label(); SPWeb site = SPContext.Current.Web; string siteUrl = SPContext.Current.Web.Url; // Make sure the site you are placing the web part on actually // has a Proposals list defined! SPList proposals = site.Lists.TryGetList(PROPOSAL_LIBRARY); if (proposals != null) { //TODO: LINQ Query to retrieve proposals } else { // Likely, the Proposal Library feature has not been // activated on this site myLabel1.Text = "There is no proposal list on this site."; this.Controls.Add(myLabel1); }
2. In place of TODO: LINQ Query to retrieve proposals from the preceding code, add the following code. Here we are performing the actual LINQ query and ensuring that we have at least one result (that is, the Proposals list could be empty): #region LINQ Query to retrieve proposals ProposalsDataContext pdc = new ProposalsDataContext(siteUrl); // Here we sort proposals in descending amount order. // Be sure to only select the fields we specifically need, // and use the opportunity to give them a "friendly" name. var query = from proposal in pdc.Proposals orderby proposal.ProposalAmount descending select new+ 149
Using the ClientOM and REST { Name = proposal.Name, Client = proposal.ProposalClient, Amount = proposal.ProposalAmount, }; if (query.Count() == 0) { //The proposal library is currently empty myLabel1.Text = "There are currently no Proposals."; this.Controls.Add(myLabel1); } else { //TODO: Create link buttons for top 5 proposals } #endregion
3. In place of TODO: Create link buttons for top 5 proposals from the preceding code, add the following code. Here we "take" the top 5 (Take is a LINQ Extension method), and then format the results into a list of links. That is, clicking the link will download the document: #region Create link buttons for top 5 proposals // Take the top 5 proposals var top5Proposals = query.Take(5); myLabel1.Text = "Here are the top 5 Proposals:"; this.Controls.Add(myLabel1); this.Controls.Add(new HtmlGenericControl("br")); foreach (var thisProposal in top5Proposals) { LinkButton proposalLink = new LinkButton(); string formatAmount = ((double)thisProposal.Amount).ToString("C2"); proposalLink.Text = thisProposal.Client + "(" + formatAmount + ")"; proposalLink.PostBackUrl = siteUrl + @"/" PROPOSAL_LIBRARY + @"/" + thisProposal.Name; this.Controls.Add(proposalLink); } #endregion
4. Open the Elements.xml file and change the group to your own value – in my case "Open Highway". 5. Open the WebPartLINQProposals.webpart file and provide a title and description for the Web Part. 150
Chapter 5
How it works... That is it! Now we can deploy and test our Web Part: 1. Press F5 to deploy the Solution and enter the debugging mode. 2. From the home page, put the home page in edit mode. Place your cursor under the welcome text. From the Insert tab in the ribbon, click on the Web Part icon. Under the category you created in the .webpart file (in my case Open Highway), select the Proposals Web Part and click on Add. 3. You should see something similar to the following:
4. By clicking on any of the links, you will download the corresponding document. Congratulations! You have accomplished your first "real" data access in SharePoint 2010 using the new capabilities of LINQ to SharePoint. This forms a core and common task in SharePoint development – creating a Web Part that queries SharePoint data and performs some type of "content roll up" and display.
Retrieving SharePoint data using the list data service I will have to admit something here first. I am not a "front end web developer" in the sense that I do not have anything beyond a working knowledge of HTML, CSS, JavaScript, and (increasingly importantly) jQuery. The web programming I do is typically with server-side controls and code behind in C#. As such, I do not personally have much call for consuming data that is not "natively" .NET, or which Visual Studio .NET abstracts away from me with references and proxy classes. But I have witnessed wizards in jQuery, who have little to no knowledge of SharePoint or its object model, directly consume SharePoint data and the result is sheer UI magic. In fact, the UI platform may not even be Microsoft – nor need it be. These developers only ask that you provide the data in an "industry standard" format such as ATOM. And then query that data using industry standard REST. REST stands for Representational State Transfer and what it means is a query format that is URL-driven. That is, you provide a query formatted as a URL – and you will get back data in ATOM format. You may know ATOM better as the underlying data format for RSS feeds. 151
Using the ClientOM and REST P.S. Another industry standard data format is JSON (JavaScript Object Notation). So while I cannot provide you the practical usage side, if you are such a front end web developer as described, I wanted to make you aware there is a way of getting to SharePoint data "out-of-the-box" without having to know anything about SharePoint.
How to do it... There is a WCF Service known as the List Data Service. You can access this manually by typing /_vti_bin/listdata.svc at the end of any site name: 1. Open Internet Explorer. Type in the Chapter 5 URL followed by /_vti_bin/ listdata.svc. In my case the full URL would be http://intranet. theopenhighway.net/sites/chapter5/_vti_bin/listdata.svc. 2. In ATOM format, you will get back the SharePoint Lists on the site. If you scroll down, you will see the Proposals library. You will see the following:
152
Chapter 5
3. Add one of the list names to the end of the URL. In our case, add "Proposals". Internet Explorer will respond to seeing this data provided as ATOM with an RSS Feed view:
153
Using the ClientOM and REST 4. In reality, that only serves for demonstration purposes. You many think you did not in fact get back all the information about the proposal, such as the client and the amount. But you did! Simply look at a View source. You will see that all the properties are in fact there for your use behind the scenes!
My goal for this recipe was to ensure that you are aware that SharePoint 2010 can natively expose SharePoint list data in ATOM format via REST.
154
Chapter 5
Working with the .NET Client Object Model To access data from outside of the SharePoint world was a tedious proposition in the previous version of SharePoint. I personally found the "lists web service" lacking, and let us leave it at that. The best and often quickest solution was to use something I was very familiar with – the SharePoint object model – to access lists and libraries. But of course you could not run that on the client (for example, a Windows Forms or Windows Presentation Foundation application). Your SPList code had to run physically on the SharePoint server. So we wrote our own web services (ASMX) that ran exactly the friendly and easy-to-write code we wanted, then packaged it up for deployment alongside SharePoint's other web services (in the 12/ISAPI folder, mapped to _vit_bin virtual directory). It was an entirely new level of fun to AJAXenable first SharePoint and then your web services so that you could use an asynchronous execution model and avoid the usual postbacks involved with executing server-side code. This is another way of saying I spent a lot of time writing "plumbing code" for data access (web service wrappers and AJAX). Descriptions of how to spend a great deal of time on the very technical bits of "how to be a plumber" for example, "AJAX-enabling your web.config" or "writing custom ASMX in SharePoint" before you could even start to consider the business of "How do I display the top 5 proposals in my Windows Application"? I am sure you have heard the good news that SharePoint 2010 features the Client Object Model (with the rather unfortunate acronym of "COM" – in case any of you are old enough to remember THAT "easy to use and understand" legacy Microsoft technology). In simple terms, the Client Object Model literally means that I can program the SharePoint Object Model (as represented by the namespace Microsoft.SharePoint) on the client application side. In this chapter, we will explore using the object model for a Silverlight application and for a Windows Forms application. The SharePoint Client Object Model is exposed from the server, literally and physically, as a WCF service named Client.svc. There is much by way of explanation of how Client.svc works. Honestly, though, I do not think you really care, but feel free to look up some great descriptions of the inner workings and interactions on the web. What is important to know though is that the client object model does not actually run on the client – if, for example, you want the top 5 list items queried from the Proposals list in the Windows Application, needing access to SPWeb, SPList, and SPListItems, the object model access must still occur on the server. So the pattern of development is to "batch up" the SharePoint object model commands, send them to the server for execution (through the Client.svc WCF service), and then you receive the physical SharePoint objects back in response. In this recipe, we will prepare our query for the top 5 proposals from the Proposals Library. Then we will send it to the server for execution. Finally, we will "foreach" our way through the returned list items.
155
Using the ClientOM and REST
Getting ready We will create the Visual Studio project that we will be working with in this recipe. For pure nostalgia reasons, I have chosen Windows Forms to be my .NET client application: 1. Open Visual Studio 2010. From the File menu, select New | Project. 2. From the Installed Templates, navigate to the Windows section and select Windows Form Application. In my case, I have named my project Chapter5ClientOMWindows. 3. Right-click on Reference and select Add Reference. From the .NET tab, add references to Microsoft.SharePoint.Client and Microsoft.SharePoint.Client.Runtime. 4. Add a Button to the Windows form. Your form should look similar to the following:
Your Solution Explorer should now look similar to the following:
156
Chapter 5
How to do it... Now it is time to use the .NET Client Object Model to retrieve information for the top 5 proposals from the Chapter 5 Proposals library: 1. Double-click the button on the form, and then place the following code in the button click event: int labelPositionYStart = 60; int labelPositionYIncrement = 30; const string PROPOSAL_LIBRARY = "Proposals"; // Substitute YOUR "Chapter 5 URL here const string SITE_COLLECTION_URL = "http://intranet.theopenhighway.net/sites/Chapter5"; const string WEB_APP_URL = "http://intranet.theopenhighway. net"; using (ClientContext clientContext = new ClientContext(SITE_COLLECTION_URL)) { // TODO: Retrieve Top 5 Proposals }
2. Place the following code above the button click event (and below the Form initialize event): // We will store URLs to the proposal documents in this // string array. string[] proposalURL = new string[5];
3. Put in the following using declarations (below the others): using System.Diagnostics; using Microsoft.SharePoint.Client;
4. Add the following method below the Clicked event: private void linkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { // Via this generic click event, I am having a Windows Link // label behave like a URL hyperlink. Really in Windows a link // label normally behaves exactly like a regular button // control. LinkLabel llClicked = (LinkLabel)sender;
157
Using the ClientOM and REST int linkNumber = Convert.ToInt32(llClicked.Name); // Since the link starts with "http://", the Process. Start // will automatically know to launch IE and navigate to // the link provided. We use the string array position // corresponding to the control that was clicked. Process.Start(proposalURL[linkNumber]); }
5. Place the following code where TODO: Retrieve Top 5 Proposals appears. Note that we get a reference to the Proposals list and then we execute a SharePoint CAML (Collaborative Application Markup Language) style query against it. The query works the same as a SQL "Order By Proposal Amount Descending". The row limit works the same as a "Top 5" in SQL or a "Take(5)" in LINQ: Web site = clientContext.Web; ListCollection siteLists = site.Lists; List proposalList = siteLists.GetByTitle(PROPOSAL_LIBRARY); CamlQuery camlQuery = new CamlQuery(); camlQuery.ViewXml = "" + "" + "" + "" + "" + "" + "5" + ""; ListItemCollection proposalItems = proposalList. GetItems(camlQuery); // The Load command batches up our commands. Nothing actually // happens yet. If you check out the actual ListItemCollection // that is proposalItems, you will note it is still "null". clientContext.Load(proposalItems); // Now the commands are sent to the SharePoint server via // the Client.svc. When this line of code completes, you will // note that proposalItems is now populated! The server has // returned the object back to the client. clientContext.ExecuteQuery(); // TODO: Format links for the Top 5 Proposals 158
Chapter 5
6. Finally, place the following code where TODO: Format links for the Top 5 Proposals appears: int i = 0; foreach (ListItem proposalItem in proposalItems) { // Format the hyperlink based on the information for // this proposal double doubleAmount = (double) proposalItem["ProposalAmount"]; string formatAmount = doubleAmount.ToString("C2"); string proposalText = proposalItem["ProposalClient"] + " (" + formatAmount + ")"; proposalURL[i] = WEB_APP_URL + (string) proposalItem["FileRef"]; // Create a windows link label control and dynamically add it // to the Windows Form controls collection. LinkLabel ll = new LinkLabel(); int labelPositionY = labelPositionYStart + (i * labelPositionYIncrement); ll.Name = (i).ToString(); ll.Width = 400; ll.Location = new Point(20, labelPositionY); ll.Text = proposalText; ll.LinkArea = new LinkArea(0, proposalText.Length); ll.LinkClicked += new LinkLabelLinkClickedEventHandler(this.linkLabel_ LinkClicked); this.Controls.Add(ll); i++; }
159
Using the ClientOM and REST 7. Press F5 to run the Windows application. Click the button and you should see a result similar to the following. Try clicking on a link and you will be prompted to download/view the Microsoft Word document:
Congratulations! You have accomplished using the .NET Client Object model from a Windows Form application. Note again that you could have easily followed nearly the same instructions to accomplish this running the .NET Client Object model in either a Windows Presentation Foundation (WPF) application or a Console application.
There's more... CAML queries are the native language for querying data in SharePoint. Unfortunately, we SharePoint folks have had to learn yet another proprietary "data access syntax" for querying SharePoint data – one that is not like anything else that had yet existed from Microsoft. Even when you are performing SP LINQ, it is actually a LINQ to CAML query translator. For the Client Object Model, you will need to supply the CAML syntax in order to submit queries to the server. The following CAML query was used to obtain the top 5 proposals (using row limit), after ordering by Proposal Amount descending. Yes, you read that correctly – Ascending = False means descending. CAML syntax certainly has its quirks. You can add the Where clause criteria as well: 5
160
Chapter 5
Use your favorite search engine in order to find a topic such as CAML tutorial to get the basics (find one for at least SharePoint 2007). Better yet, do NOT learn CAML, but instead get a tool such as U2U's free CAML Query Builder to visually build out the query, than you can then simply cut-and-paste, not only to build the query, but to test it out as well. Search for "u2u caml query builder for sharepoint 2010".
Working with the Silverlight Client Object Model To me, and put simply, Silverlight is Microsoft's answer to Adobe Flash, as both provide the ability to deliver Rich Internet Applications (or RIA). The high visual appeal is often highlighted in these types of applications, but as a developer this is the web's way of creating a fully client-side running application, in our case executing in the Silverlight run time environment. It is also my developer way of saying that I cannot Graphic Design my way out of a wet paper bag. Please do not count on any stunning visuals in this section. While I know that WPF and Silverlight are quite different, I like to think of Silverlight as WPF's younger cousin – in that they both rely on creating user interface by painting canvases of XAML (eXtensible Application Markup Language). Fortunately, SharePoint 2010 now provides integrated support for hosting Silverlight applications, and as a matter of fact uses Silverlight itself to replace the boring old user interface that used to be there. For example, if you use Site Actions | More Options to create a new list or library, the selection of the list or library type is a Silverlight application. You could, with some effort, integrate Silverlight applications into SharePoint 2007, but the real problem was getting SharePoint data "there" (remember, client-side) in the running application – because I found the old lists web service (lists.asmx) relatively clumsy and unusable. In a similar fashion to the Windows Application, we will use the SharePoint Client Object Model to get the data to our Silverlight application. The SharePoint Client Object Model references for each type of application – .NET Client, Silverlight, and ECMAScript (next section) are different. That is why you will see this referred to specifically as the .NET Client OM, the Silverlight Client OM, and the ECMAScript Client OM. Also the mechanisms change – the .NET Client OM is a synchronous model (you wait for the answer when you ask for it) and both Silverlight and ECMAScript are asynchronous (a callback function will be triggered to deliver the result).
161
Using the ClientOM and REST
Getting ready We will 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 Empty SharePoint Project. In my case, I have named my project Chapter5ClientOMSilverlight. 3. On the SharePoint Customization Wizard screen, type in the Chapter 5 URL in the box What local site do you want to use for debugging?. Ensure you select Deploy as a SANDBOXED solution and click on Finish. No, that was not a typo – please ensure you select SANDBOXED solution, which will be explained in more detail later.
1. From the File menu, select Add | New Project. In the Installed Templates section, select Silverlight and then select Silverlight Application. Provide a name such as SilverlightClientOM and click on OK. 2. Uncheck the box Host the Silverlight application in a new website and click on OK. 3. When the MainPage.xaml appears, I took a quick moment to change the background color. As I want to feel more in tune with emerging technology, I chose the background color "Azure". 4. In the Solution Explorer, right-click the references of the SilverlightClientOM project and choose Add Reference. You will (inconveniently) need to use the Browse tab and navigate manually to the C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin folder. 5. Add references for both Microsoft.SharePoint.Client.Silverlight and Microsoft. SharePoint.Client.Silverlight.Runtime. 6. In the Solution Explorer, right-click on the Chapter5ClientOMSilverlight (the empty SharePoint) project and select Add | New Item. 7. From the Installed Templates for SharePoint 2010, select Module. Provide the name SilverlightClientOM and click on Add. Be sure to right-click and delete the Sample.txt file that was automatically created. 8. Note that when we added the module, we automatically got a Feature. Rename the Feature from Feature1 to SilverlightClientOM. Open the Feature Designer and provide a Title and Description for the Feature.
162
Chapter 5
Your Solution Explorer should now look similar to the following:
As this is a "Sandboxed" solution, this execution model relies on a very specific SharePoint service that we need to start: 1. Open Central Administration. Click on the Manage services on server link that appears under the System Settings section. 2. Locate the Microsoft SharePoint Foundation Sandboxed Code Service in the list. If the current status is Stopped, then click on the Start link. It should display as follows:
How to do it... Note that a Silverlight application is packaged as a XAP file (in an analogous way that the SharePoint solution is packaged as a WSP file). The XAP file is the official output of this type of Visual Studio project, as a DLL would be the official project output of a class library. Finally, for our case, the Silverlight application must be loaded into SharePoint and that means we have to get the XAP file physically from somewhere. That "somewhere" will be the out-of-thebox "Site Assets" library for your site. You can view the Site Assets library from Site Actions | View All Site Content.
163
Using the ClientOM and REST Our first recipe must then deal with the SharePoint deployment aspects of the Silverlight XAP file. We will include the Silverlight project output (XAP file) as part of our Solution, and then deploy it to our site into the Site Assets library: 1. In the Chapter5ClientOMSilverlight project, click on the SilverlightClientOM module and note the properties:
2. Click on the ellipses of the property Project Output References. Click on Add. When you change the drop-down selection for Project Name to SilverlightClientOM and the Deployment Type drop-down to ElementFile you will see the following:
164
Chapter 5
3. Click on OK. 4. Under the SilverlightClientOM module folder, open the Elements.xml file. By default, it wants to deploy our XAP file to a URL (a document library) that matches our Silverlight project name. Change SilverlightClientOM to SiteAssets in the URL property. This file should now look as follows: <Elements xmlns="http://schemas.microsoft.com/sharepoint/"> <Module Name="SilverlightClientOM">
5. Silverlight applications can be easily hosted in SharePoint with the Silverlight Web Part. We are going to verify our work to date by adding the Silverlight Web Part to our home page and configuring it. Press F5 to build and deploy your application. Click on Attach on the Attach Security Warning dialog. 6. When the home page opens, go to Site Actions | View All Site Content and choose the Site Assets Library. Verify that the Silverlight XAP file was correctly deployed as follows:
165
Using the ClientOM and REST 7. Go back to the home page and put the home page in edit mode. Place your cursor under the welcome text. From the Insert tab in the ribbon, click on the Web Part icon. Under the Media and Content category, select the Silverlight Web Part and click on Add. Enter the full path for the URL and click on OK – in my case it is
http://intranet.theopenhighway.net/sites/Chapter5/SiteAssets/ SilverlightClientOM.xap. At the same time I changed the Title property under
the appearance section to Top 5 Proposals. Click on OK on the Web Part properties dialog and save your page edits.
8. You should now see the Web Part appear on the page as a rather uninteresting Azure colored square. This first little recipe is once again applicable to any Silverlight application you wish to develop in SharePoint. Now it is time to use the Silverlight Client Object Model to show the top 5 proposals in our Silverlight Web Part: 1. Open the MainPage.xaml.cs file, and add the following code immediately above the MainPage method, in order to declare the required variables: int labelPositionYStart = 10; int labelPositionYIncrement = 30; const string PROPOSAL_LIBRARY = "Proposals"; // Replace the following with your web application const string WEB_APP_URL = "http://intranet. theopenhighway.net"; private private private private private
Web site; ListCollection siteLists; List proposalList; CamlQuery camlQuery; ListItemCollection proposalItems;
2. Add the following using statement: using Microsoft.SharePoint.Client;
3. Add the following code as a new method below the MainPage method, which will create the series of hyperlinks for the top 5 proposals when the query is returned: private void CreateHyperLinks() { // THIS method is running on the UI thread int i = 0; foreach (ListItem proposalItem in proposalItems) { // Format the hyperlink based on the information for // this proposal 166
Chapter 5 double doubleAmount = (double)proposalItem["ProposalAmount"]; string formatAmount = doubleAmount.ToString("C2"); string proposalText = proposalItem["ProposalClient"] + " (" + formatAmount + ")"; // Create a windows link label control and dynamically add // it to the Windows Form controls collection. HyperlinkButton hlb = new HyperlinkButton(); int labelPositionY = labelPositionYStart + (i * labelPositionYIncrement); hlb.Width = 400; hlb.NavigateUri = new Uri (WEB_APP_URL + (string)proposalItem["FileRef"] ); hlb.Margin = new Thickness(10, labelPositionY, 0, 0); hlb.Content = proposalText; LayoutRoot.Children.Add(hlb); i++; } }
4. Add the following two methods immediately above the CreateHyperLinks method you just added. These are the call back functions for the asynchronous call to the client service: private void OnRequestSucceeded(Object sender, ClientRequestSucceededEventArgs args) { // Classically, this callback executes on a "background thread", // and therefore you will find yourself without access to // create controls on the Main Page. So, we give control back // to a method on the main UI thread using BeginInvoke Dispatcher.BeginInvoke(CreateHyperLinks); } private void OnRequestFailed(Object sender, ClientRequestFailedEventArgs args) { // Handle error, display error message } 167
Using the ClientOM and REST 5. Add the following code within the MainPage method, and immediately below the InitializeComponent() statement. Similar to the previous recipe on the .NET Client Object Model, this will prepare the CAML query and send it to the server for execution: string SiteCollectionURL = ApplicationContext.Current.Url; using (ClientContext clientContext = new ClientContext(SiteCollectionURL)) { site = clientContext.Web; siteLists = site.Lists; proposalList = siteLists.GetByTitle(PROPOSAL_LIBRARY); camlQuery = new CamlQuery(); camlQuery.ViewXml = "" + "" + "" + "" + "" + "" + "5" + ""; proposalItems = proposalList.GetItems(camlQuery); // The Load command batches up our commands. Nothing actually // happens yet. If you check out the actual ListItemCollection // that is proposalItems, you will note it is still "null". clientContext.Load(proposalItems); // Now the commands are sent to the SharePoint server via // the Client.svc. When this line of code completes, you will // note that proposalItems is now populated! The server has // returned the object back to the client. clientContext.ExecuteQueryAsync(new ClientRequestSucce ededEventHandler(OnRequestSucceeded), new ClientRequestFailedEvent Handler(OnRequestFailed)); }
168
Chapter 5
6. Press F5 to run deploy and run the Silverlight application. When the home page appears you should see a result similar to the following. Try clicking on a link and you will be prompted to download/view the Microsoft Word document:
Congratulations! You have successfully created a Silverlight application that uses the Client Object Model to retrieve the top 5 proposals from the Proposals Library.
There's more... A Sandbox Solution (versus Farm Solution) is simply an alternative method of deployment that has a different execution model. The differences are: 1. Where the SharePoint solution file ( WSP) is deployed 2. How the code is loaded and executed To address the first point, a Sandbox Solution is deployed and activated at the Site Collection level, not the Farm level. There is a special gallery called the Solutions gallery, which is just a special library for WSP files. By the way, "yes", this also implies that you would by definition need to deploy this feature to the Solution gallery of each site collection where you wanted to use this Silverlight application. From Site Actions | Site Settings, click on the Solutions link that appears under the Galleries section. You will see our Chapter5ClientOMSilverlight Solution (WSP file) as Activated.
169
Using the ClientOM and REST If you go to the Site Features page (from Site Settings), you will see our Feature appear, activated, "as normal":
Our second point was in how the code is executed. Remember in the Getting ready section that you had to ensure the "Sandboxed Code Service" was running on the server? To execute the code, it is NOT loaded in process with the IIS Application pool worker process (w3wp. exe), but rather an instance of a "sandbox" process (SPUCWorkerProcess.exe). Feel free to check out the processes in Task Manager to verify this. This means the code is running in a "sandbox" – a safe, secure, and isolated process. For example, if the application were to fatally crash, it would only take out the sandbox, not your whole web application – where, I assure you, your Farm Administrators would not be so pleased! There is a whole new world to Sandboxing you should explore – such as the ability to assign resources and quotas to the solutions. And also limitations – such as you can only use a subset of the SharePoint object model. Please take time to research your Sandbox options online.
170
6
External Data In this chapter, we will cover: ff
Getting your data ready for the chapter
ff
Using the Data Form Web Part with SQL Server
ff
Using the Data Form Web Part with WCF Data
ff
External Content Types and Lists
ff
Using Business Data Web Parts
ff
Creating a Custom BCS Model in Visual Studio 2010
Introduction The previous chapter showed you how to work with data that was inside SharePoint, that is, Lists and Libraries. This chapter, however, may be the most eye-opening one for you in this book, in terms of the development possibilities that the SharePoint platform can offer. In the vast majority of cases in my experience in custom development, the application needs to involve and/or directly integrate data that comes from other resources to SharePoint. Most of the time, this data resides in a relational database or is available via a web services call—data such as customers, employees, products, orders, lookup tables, and so on. SharePoint Designer 2010 will once again prove itself a capable development tool to offer you no code solutions for integrating external data. The ease of connecting to relational data or web service data will be demonstrated in this chapter, and then we will explore many different techniques to exploit these data connections in SharePoint. The net result shows why many people are choosing SharePoint 2010 as the integration platform—for the rapid delivery of custom applications!
External Data
Getting your data ready for the chapter Before we can begin, we will need some external data in the form of data stored in SQL Server. It seems fashionable to use Adventure Works, but I am feeling a bit nostalgic. Who remembers good old PUBS and Northwind here? PUBS (short for Publishers) is the very first sample database. I can remember going back to the very first version of Microsoft SQL Server and even prior to that—to its Sybase predecessor! OK, before you start making jokes involving dinosaurs, we will find and install these classic sample databases. Next, we will also create a state of the art Windows Communication Foundation (WCF) or a Data Service—a means of putting a RESTful interface on top of our SQL Server Data. With data fed from an industry-standard data format (ATOM: A syndication format that is an XML language used for web feeds similar to RSS), literally you can consume data from anywhere and be backed by any source of data from any system. Imagine a service that returns data from a non-Microsoft source, such as Oracle on Unix, or from DB2 on AS/400.
Getting ready First, 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 correct web application is selected. Enter Chapter 6 for the title and Chapter6 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 defaults. Scroll to the bottom and click OK. 5. When the Top Level Site Successfully Created screen appears, click on the link provided on this screen. Bookmark the site to your favorites. Note that I will refer to this site in this chapter as the Chapter 6 URL for creating Visual Studio 2010 projects later. For example, in my case, this URL is: http:// intranet.theopenhighway.net/sites/Chapter6
Download and install the SQL Server sample databases: 1. Download the Pubs and Northwind SQL Server sample databases from the CodeProject site using the following link, or type codeproject northwind download into your favorite search engine: 2. http://www.codeproject.com/KB/database/ InstallingNorthwindAndPub.aspx 172
Chapter 6
3. Unzip the file to a convenient location within your virtual machine. 4. Open the Microsoft SQL Server Management Studio. 5. Double-click on the instnwnd.sql file which will open the SQL script in SQL Management Studio. Click on Execute. This will create the database, tables, and load the tables with data. 6. Double-click on the instpubs.sql file which will open the SQL script in SQL Management Studio. Click on Execute. This will create the database, tables, and load the tables with data. We must now change the configuration of SQL Server to use Mixed Authentication and we must set up a SQL Server user named SPD2010: 1. Launch SQL Server Management Studio (from the Start menu | All Programs | SQL Server 2008 R2). Once connected, right-click the SQL server name and choose Properties, as shown in the following screenshot:
173
External Data 2. On the Security page, change the Server authentication to SQL Server and Windows Authentication and click OK, as shown in the following screenshot:
3. Back in Object Explorer, expand the Security node. Right-click on Logins and select New Login, as shown in the following screenshot:
4. On the General page of the Login – New screen, enter the Login name SPD2010. Choose SQL Server authentication and enter a password and confirm the password (my password here is Password1). Also, uncheck the Enforce password policy checkbox, as shown in the following screenshot:
174
Chapter 6
5. On the User Mapping page of the Login – New screen, click the Map checkbox for each of the Northwind and pubs databases. Highlight each database, and in the Database role membership for: Northwind window, select the db_owner checkbox. Your screen should now look similar to the following screenshot. Repeat the preceeding steps for the pubs database:
6. Click on OK. You can now close the SQL Management Studio application.
How to do it... Carry out the following steps in order to create a Visual Studio solution, that is, our WCF Data Service: 1. Open Visual Studio 2010. From the File menu, select New | Project.
175
External Data 2. From the Installed Templates, navigate to the Web section and select ASP.NET Web Application. In my case, I have named my project Chapter6NorthwindDataService, as shown in the following screenshot. Ensure the .NET Framework Version is set to 4.0:
3. In the Solution Explorer, right-click on the project and select Add | New Item. 4. From the Installed Templates Data section, select ADO.NET Entity Data Model. Provide the name Northwind.edmx and click on Add, as shown in the following screenshot:
5. On the Entity Data Model Wizard that appears, select Generate from database and click Next, as shown in the following screenshot: 176
Chapter 6
6. On the Data Connection screen, click the New Connection button. Choose data source as Microsoft SQL Server and click Continue. 7. On the Connection Properties, you can enter a period (.) for the server name, which means it is the default local instance. From the Select or enter a database name drop-down, choose Northwind. Use the Test Connection button, if you wish to verify the settings, and click OK. 8. Back on the Choose Your Data Connection screen, click Next. 9. In the Choose Your Database Objects screen, click the Tables checkbox and click Finish, as shown in the following screenshot:
177
External Data 10. Your new entity model will be displayed in Visual Studio. It should look similar to the following screenshot Please take the time to explore it:
11. In the Solution Explorer, right-click on the Project and select Add | New Item. 12. From the Installed Templates, click on the Web section and select WCF Data Service. Provide the name NorthwindDataService.svc and click Add, as shown in the following screenshot:
178
Chapter 6
13. When the NorthwindDataService.svc.cs file opens, note the TODO item in the class definition. Replace this comment with NorthwindEntities. Uncomment the SetAccessRule line of code and replace MyEntitySet with * (an asterisk to indicate all). The resulting code should look as follows: public class NorthwindDataService : DataService< NorthwindEntities > { // This method is called only once to initialize service-wide // policies. public static void InitializeService(DataServiceConfiguration config) { // TODO: set rules to indicate which entity sets and service // operations are visible, updatable, etc. // Examples: config.SetEntitySetAccessRule("*", EntitySetRights. AllRead); // config.SetServiceOperationAccessRule("MyServiceOperati on", ServiceOperationRights.All); config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2; } } 179
External Data 14. Build the solution to ensure that there are no errors. Right-click on NorthwindDataService.svc and select View in browser. You should see the following screen, which, if you look closely, is in the ATOM data format, and you can see the name of all the Entities available from this data service:
15. Copy the URL and leave this browser running, as it will be required when we get into the exercises that will use this data. Congratulations! Perhaps this is even your first experience with building a WCF Data Service—even better then! Surprisingly, it is really simple to set up a state of the art oData (RESTful) WCF service based upon an Entity Framework source of data. I highly recommend you spend some more time reading up on these subjects.
180
Chapter 6
Note that when I refer in future to ensure that the WCF Data Service is running, that means opening this solution, right-clicking on the NorthwindDataService.svc file, and clicking View in the browser. Copy the browser URL and be ready to enter it when prompted. Again, in my case, the URL was http://localhost:41664/NorthwindDataService. svc/. Yours will likely be the same, differing only by the port number.
Using the Data Form Web Part with SQL Server In Chapter 4, Development with SharePoint Designer 2010, we explored the use of the XSLT List View Web Part, a very specialized and powerful Web Part for use with SharePoint lists and libraries. At the base of this Web Part is the Data Form Web Part. This more fundamental Web Part can still easily make use of SharePoint's List and Library data, but it can also make direct use of external data connections to relational databases, REST Services, web services, or even plain old XML files. In this recipe, we will use two connected Data Form Web Parts. One will display the list of publishers directly from the pubs database, and the second connected list will show the books (publications) from the selected publisher.
Getting ready Ensure SharePoint Designer 2010 has been opened to the Chapter 6 URL: 1. From the Navigation section, under Site Objects, choose Data Sources. 2. From the Data Sources tab in the ribbon, click on Database Connection, as shown in the following screenshot:
3. On the Data Source Properties window, click on the Configure Database Connection button.
181
External Data 4. On the Configure Database Connection screen, enter your server name (in my case, it is OPENHIGHWAY). In the Authentication section, fill in the user name SPD2010 (the one we set up earlier in the SQL Server database), and Password1 for the password, as shown in the following screenshot. Click OK on the warning: This information will be stored in the connection string. and click Next. Please wait patiently! There will be no feedback while you are waiting for the next screen:
5. In the Select Database and Table screens, choose the pubs database from the drop-down and choose the publishers table. Then click Finish:
182
Chapter 6
6. The Data Source Properties screen should now appear as follows. Click the OK button, as shown in the following screenshot:
7. Repeat steps 2 to 6 exactly, except that in step 5, choose the titles table. When done, your database connections section should appear as follows:
How to do it... In this recipe, we will use the external Publishers data directly with a new SharePoint web page. Carry out the following steps to complete this recipe: 1. Ensure SharePoint Designer 2010 has been opened to the Chapter 6 URL. 2. From the Navigation section, under Site Objects, choose Site Pages.
183
External Data 3. From the Pages tab in the ribbon, choose Web Part Page from the Page drop-down, and choose the very first template (top left), as shown in the following screenshot:
4. Rename the new page to Publishers.aspx. When you click on Publishers.aspx, it will open as a tab. In the Customization section, click on Edit File. 5. Click inside the PlaceHolderMain (you will find this inside the page body area; if not, then put the view into split mode and search for this text). On the Insert tab of the ribbon, click the Data View drop-down and choose More Data Sources, as shown in the following screenshot:
184
Chapter 6
6. On the Data Sources Picker window, scroll down to Data Connections and choose publishers. 7. Click underneath the publishers table, and repeat steps 6 and 7; except that this time, we choose titles. 8. Click anywhere on the titles table. On the Data View Tools Options tab, click on the Add/Remove Columns button on the ribbon, as shown in the following screenshot:
9. Select Type and pub_id and click the Remove button and then click OK, as shown in the following screenshot:
10. Change some of the column headers to be more readable. You can do so by clicking on the current title and then replacing the text. 11. Now we are going to connect the two Web Parts together so that they can interact. Click anywhere in the publishers table. In the Data View Tools Web Part on the ribbon, click on Add Connection:
185
External Data 12. The Web Part Connection Wizard will now be displayed. Just click Next, as shown in the following screenshot:
13. On the next page of the wizard, choose Connect to a Web Part on this page and click Next. 14. On the next page, leave the defaults (Target Web Part: titles on pubs and Target action: Get Filter Values From) and click Next. 15. Here is where we make the connection. Scroll down until you see pub_id in the Inputs column (right-hand side). In the Columns in publishers on pubs section, choose pub_id and click Next, as shown in the following screenshot:
186
Chapter 6
16. On the next screen, leave the default selection of pub_id for Create hyperlink on and click Next. 17. On the final screen of the Wizard, click Finish. 18. Save your work. In the Site Pages section on the left-hand side of the screen, right-click on Publishers.aspx and choose Preview in browser, as shown in the following screenshot:
19. When the page shows in the browser, click on the first few publisher ID links and note that the Titles Web Part shows the publications for the selected publisher, as shown in the following screenshot:
Congratulations! You have used the Data Form Web Part in order to not only display information directly from an external source, but also to use SharePoint Web Parts to connect Publishers and Titles to work together interactively.
187
External Data
Using the Data Form Web Part with WCF data In this recipe, we will use two connected Data Form Web Parts. One will display the list of Suppliers directly from the Northwind database via RESTful WCF Data Services. Then we will connect a second list that will show the products from the selected supplier.
Getting ready Carry out the following steps in order to 1. Ensure that your Northwind data service is running: Ensure that your Chapter6NorthwindDataService solution is open in Visual Studio 2010. Right-click on NorthwindDataService.svc and choose View in browser. Copy the URL to the clipboard and get ready to use it for your data source. 2. Ensure SharePoint Designer 2010 has been opened to the Chapter 6 URL: From the Navigation section, under Site Objects, choose Data Sources. From the Data Sources tab in the ribbon, click on REST Service Connection, as shown in the following screenshot:
On the Data Source Properties window, paste your WCF Service URL into the Enter the URL to a server-side script: textbox. Add Suppliers to the end of the pasted URL and click OK, as shown in the following screenshot:
188
Chapter 6
Repeat steps 2 to 3 exactly, except that in step 3, put Products at the end of the pasted URL. When done, your RSS, REST, Server Scripts section should appear as follows:
How to do it... In this recipe, we will use the external Northwind data via RESTful WCF Services with a new SharePoint web page: 1. Ensure that SharePoint Designer 2010 has been opened to the Chapter 6 URL. 2. From the Navigation section, under Site Objects, choose Site Pages.
189
External Data 3. From the Pages tab in the ribbon, choose Web Part Page from the Page drop-down, and choose the very first template (top-left), as shown in the following screenshot:
4. Rename the new page Suppliers.aspx. When you click on Suppliers.aspx, it will open as a tab, and in the Customization section, click on Edit File. 5. Click inside the PlaceHolderMain. On the Insert tab of the ribbon, click on the Data View drop-down and choose More data sources, as shown in the following screenshot:
190
Chapter 6
6. On the Data Sources Picker window, scroll down to RSS, REST, Server Scripts, choose Suppliers, and then click OK. 7. With the Suppliers table highlighted, on the Data View Tools Options tab, click on the Add/Remove Columns button on the ribbon, as shown in the following screenshot:
8. Select ddw1:id and ddw1:updated and click the Remove button. Add the SupplierID that is at the bottom of the Available Fields window (and not the one that ends with m:type) and click the Add button. Also add the CompanyName and City properties and click OK, as shown in the following screenshot:
9. Click underneath the Publishers table, and repeat steps 5 to 8, except that this time, choose the Products table, and ProductName, UnitPrice, and UnitsInStock columns. 10. Change some of the column headers to be more readable. 11. Now we are going to connect the two Web Parts together so that they interact! Click anywhere on the Suppliers table. In the Data View Tools Web Part on the ribbon, click on Add Connection, as shown in the following screenshot:
191
External Data 12. The Web Part Connection Wizard will be displayed. Click on Next, as shown in the following screenshot:
13. On the next page of the wizard, choose Connect to a Web Part on this page and click Next. 14. On the next page, leave the defaults, that is, Target Web Part: Products on localhost:41661 and Target action: Get Filter Values From as they are, and click Next. 15. Here is where we make the connection! Scroll down until you see SupplierID in the Inputs to Products on localhost column (right-hand side). In the Columns in publishers on pubs, choose SupplierID and click Next, as shown in the following screenshot:
192
Chapter 6
16. On the next screen, leave the default selection of SupplierID for Create hyperlink on and click Next. 17. On the final screen of the Wizard, click Finish. 18. Save your work. In the Site Pages section on the left-hand side of the screen, right-click on Suppliers.aspx and choose Preview in browser, as shown in the following screenshot:
When the page is shown in the browser, click on the first few Supplier ID links and note that the Products Web Part shows the products for the selected supplier, as shown in the following screenshot:
Congratulations! You have used the Data Form Web Part in order to not only display information from a RESTful WCF data service, but also to use SharePoint Web Parts to connect Suppliers and Products to work together interactively.
193
External Data
External Content Types and Lists In SharePoint, a Content Type for a SharePoint List is very similar to a Schema for a relational database table. So, you can think of an External Content Type as the schema (definition) for an external (outside of SharePoint) list. For example, properties, and data types. External Content Types use a service application called Business Data Connectivity Services to perform the actual connection to the external data sources. You may see the acronyms BDC for Business Data Connectivity or BCS for Business Connectivity Services further in the chapter, which all mean the same thing from your perspective. One of my favorite things about SharePoint 2010 is the brilliant simplicity of connecting to an external data source, and then creating an external list. This list looks and behaves exactly like a SharePoint List, including the ability to update data from within SharePoint. The best way to prove the simplicity of the setup and power of this feature is to dive right into a working example!
How to do it… Ensure that SharePoint Designer 2010 has been opened to the Chapter 6 URL. Carry out the following steps in order to accomplish this: 1. From the Navigation section, under Site Objects, choose External Content Types. Be patient while this loads for the first time. 2. Click on External Content Type in the ribbon, as shown in the following screenshot:
3. On the tab that comes up, in the Information section, change the name to Publishers. Next to External System, click on the link Click here to discover external data, as shown in the following screenshot:
194
Chapter 6
4. On the tab that opens up, click on Add Connection:
5. From the drop-down, choose SQL Server as the Data Source Type and click OK:
6. Enter a period (.) for the Database Server (which is shorthand for the local default SQL Server instance), pubs for the Database Name, and give this connection the name of Publishers. Choose to connect with the User's Identity and click OK, as shown in the following screenshot:
7. Your database explorer should now look as follows. Expand the tables section and you should see all the available tables from the Publishers database:
195
External Data 8. Now, SharePoint Designer will generate all of the operations to interact with the publishers table, including the ability to Create, Read, Update, and Delete. Right-click on the publishers table and choose Create All Operations, as shown in the following screenshot:
9. In the All Operations window that comes up, click on Operations Properties and then click Next. On the Parameters Configuration screen, click on each of the Data Source Elements, provide a friendly display name, and click Next:
196
Chapter 6
10. We are now going to set up some filter values for later use. On the Filter Parameters Configuration screen, click on the Add Filter Parameter button. In the Properties pane, click on the link beside Filter that says Click to Add. On the Filter Configuration screen, change the filter name to pub_name, and choose the Filter Type Wildcard. It is very important to check the box for Ignore filter if Value is and ensure that the selection is Null. Click OK when done:
11. The Properties pane should now appear as follows. Be sure to change the Data Source Element to match the filter we are creating. Also, it is very important to change the Default Value to <>, as shown in the following screenshot:
12. Repeat steps 10 and 11 to add a Wildcard criteria for City, State, and Country fields. The result should appear as follows:
13. Click on the Finish button. Ensure that you save your work at this point. 197
External Data 14. On the External Content Types ribbon, click on the Summary View icon. Once you do this, your External Content Type Operations section should now appear as follows:
So far, we have only defined an actual connection to the database. Now we will get a user interface generated by SharePoint for us. Carry out the following steps to accomplish this: 1. From the Navigation section, under Site Objects, choose External Content Types. Click on Publishers to open it. 2. On the External Content Types ribbon, click on Create Lists and Forms, as shown in the following screenshot. If you had not previously saved it, you will get a warning about this (and you can click Yes):
3. On the Create List and Form for Publishers window, provide the List Name Publishers and a description. Be sure to check the Create InfoPath Form checkbox, as shown in the following screenshot. Click OK and you are done! Ensure that you save your work:
198
Chapter 6
4. In Internet Explorer, navigate to the Chapter 6 URL, and click on the Publishers link that now appears under lists. Oh no..! What?!? You get access denied, as shown in the following screenshot:
Believe it or not, you could interact with the database in SharePoint Designer to create the External Content Type and List, but you will still get an access denied message even though you are the Server Administrator, Farm Administrator, and SQL Administrator! Access to data through Business Connectivity Services is secure, by default, and it requires the Farm Administrator to set these permissions. That is, there is nothing the SharePoint Designer or the Site Collection Administrator can do about this. So let's fix our permission problem! 1. Open SharePoint Central Administration. In the Application Management section, click on Manage service applications, as shown in the following screenshot:
2. Highlight Business Data Connectivity Services. In the ribbon, click on the Manage icon, as shown in the following screenshot:
199
External Data 3. You will see the Publishers External Content Type that you had created in SharePoint Designer 2010. From the drop-down on Publishers, choose Set Permissions:
4. In the first textbox, type the name of the Administrator account and click on Add. Then, check all the checkboxes under permissions. Your screen should look similar to the following screenshot. Finally, click on OK, as shown in the following screenshot:
200
Chapter 6
5. Unfortunately, these permissions will NOT take effect until you reset the web server. Open a command prompt and type iisreset, as shown in the following screenshot:
6. When the reset completes, you can close the command prompt window. Open Internet Explorer and navigate once again to the Chapter 6 URL. After this reset, it may take 30 seconds or so for your site to appear again.
How it works… Ok, now we can (finally) test our new External list! Carry out the following steps to do so: 1. From the Chapter 6 URL in Internet Explorer, click on the Publishers link under Lists. 2. Using the drop-down for the item, select Edit Item. Change the New Moon Books publisher name to Old Moon Books, as shown in the following screenshot:
201
External Data 3. The resulting list should appear as follows:
Congratulations! You have used a very important and powerful new SharePoint 2010 feature to create an External Content Type and External list with SharePoint Designer 2010.
There's more... The External Content Type created with SharePoint Designer 2010 is actually published to the SharePoint Farm. One key benefit is that Publishers information will be available across site collections and web applications. In other words, your work is highly reusable! You should take a moment to explore the view of the External Content Type as it appears in the Central Administration: 1. Open SharePoint Central Administration. In the Application Management section, click on Manage service applications:
2. Highlight the Business Data Connectivity Services. In the ribbon, click on the Manage icon. 3. You will see the Publishers External Content Type that you had created in SharePoint Designer 2010. From the drop-down on Publishers, choose View External Content Type, as shown in the following screenshot:
202
Chapter 6
4. View the details for Publishers. Scroll down further on the screen to see the defined filters, as shown in the following screenshot:
Using Business Data Web Parts There are several out-of-the-box Web Parts that can highly leverage your External Content Type definitions! You should definitely explore these Web Parts, because usually I see developers immediately creating a custom Web Part, which does the same thing simply because they were not aware of these features. In this recipe, we will have one quick and powerful demonstration by using the Business Data List Web Part to create a Publishers Search in just a few clicks!
203
External Data
Getting ready This recipe relies on having set up the Publishers External Content Type in the previous exercise.
How to do it... In this recipe, we will use the Publishers External Content Type and an out-of-the-box Business Data Web Part in order to query the Publishers information. Carry out the following steps to do so: 1. Ensure that SharePoint Designer 2010 has been opened to the Chapter 6 URL. 2. From the Navigation section, under Site Objects, choose Site Pages. 3. From the Pages tab in the ribbon, choose Web Part Page from the Page drop-down, and choose the very first template (top-left), as shown in the following screenshot:
4. Rename the new page PublisherSearch.aspx. When you click on PublisherSearch.aspx, it will open as a tab, and in the Customization section, click on Edit File.
204
Chapter 6
5. Click inside PlaceHolderMain. On the Insert tab of the ribbon, click the Web Part drop-down and choose the Business Data list, as shown in the following screenshot:
6. Do not worry about the error where it shows Preview not returned by server. We will fix this in a moment. In the ribbon, switch to the Format section of Web Part Tools and choose Properties (on the left-hand side):
205
External Data 7. In the Business Data List Web Part properties window, type Publishers in the Type textbox and click on the Check if External Content Type exists icon that is immediately beside the Type textbox. Expand the Appearance section and change the title to Search Publishers, as shown in the following screenshot:
8. Save your work. In the Site Pages section on the left-hand side of the screen, right-click on PublisherSearch.aspx and choose Preview in browser, as shown in the following screenshot:
206
Chapter 6
9. When the page shows up in the browser, choose some criteria and try out the new Publisher search! Here are the display results for a publisher with the name Publish and the country US, as shown in the following screenshot:
Congratulations! You have leveraged the previously-defined Publisher External Content Type with an out-of-the-box Business Data List Web Part to create a flexible Publisher search. All with very little effort!
207
7
SharePoint Workflows In this chapter, we will cover: ff
Using out-of-the-box workflows
ff
Copy and extend out-of-the-box workflows with SharePoint Designer 2010
ff
Using Visio 2010 to create workflows
ff
Using SharePoint Designer 2010 to implement Visio 2010 workflows
ff
Developing workflows in Visual Studio 2010
Introduction Nearly every time that you need to provide SharePoint 2010 customizations involving document collaboration, you will need to create one or more corresponding workflows. In the past, the out-of-the-box workflows were not customizable, and the previous version of SharePoint Designer sadly lacked and was very limited in its workflow creation capabilities. Every time, one quickly cracked open Visual Studio and created custom workflows from scratch. SharePoint workflows are a unique type of workflow. They are typically assigned to a library or list, and revolve around assigning tasks for people to complete. Generally, once the tasks are completed, the workflow ends. Since SharePoint 2010 has come along, I am proud to say I have not yet had to resort to Visual Studio 2010 in order to create a workflow! I have found SharePoint Designer 2010 to be a very capable workflow development tool, and it has met every workflow requirement to date. The reason is that most workflows honestly are quite simple, and often a variation / extension of the approval workflow.
SharePoint Workflows This chapter will walk you through recipes that will cover the majority of the workflow development tasks you will encounter in the real world. It will also progress logically from one scenario to the next as you reach the limits of the current technique. We will move from out-of-the-box workflows to customizing them with SharePoint Designer 2010. Then we will cover the process of creating workflows with a combination of tools – Visio 2010 and SharePoint Designer 2010. Finally, we will employ a similar workflow developed using Visual Studio 2010 with Windows Workflow Foundation programming. By covering all these scenarios in a logical sequence, you should come away with a good understanding of which workflow scenario will apply in a given situation.
Using out-of-the-box workflows Why would a development book cover using out-of-the-box workflows?!? Well, at times I do see people often turning to creating a custom workflow without first understanding in depth the capabilities of the workflows that are already available. Secondly, this topic will help illustrate the terminology behind the key "phases" of a SharePoint workflow – being Association, Initiation, Modification, and Task Edit – and the forms that can be associated with each of these phases. This, in turn, prepares us for the other recipes in this chapter as we move on to customize the out-of-the-box workflows In this recipe, we will utilize an out-of-the-box approval workflow against our Proposal library.
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 7 for the title and Chapter7 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 with their default values. Scroll to the bottom and click on Ok.
210
Chapter 7
5. When the Top Level Site Successfully Created screen appears, click on the link provided. Bookmark the site to your favorites. I will refer to this site in this chapter as the Chapter 7 URL for later purposes of creating Visual Studio 2010 projects and/or SharePoint Designer 2010. For example, in my case, this URL is: http:// intranet.theopenhighway.net/sites/Chapter7.
6. Note that the Feature Stapling from Chapter 2, SharePoint Development with Visual Studio, has resulted in automatic creation of the Proposal library we will be working with. Create six or more Proposals called "Proposal1", "Proposal2", and so on. Ensure the amounts are different as we will create a workflow based on the Proposal Amount.
How to do it... In this recipe, we will configure an out-of-the-box approval workflow for the Proposals library. Remember the main purpose of this exercise is to highlight specific terminology involved with SharePoint workflows: 1. Go to the Proposals document library in the Chapter 7 URL. 2. On the Library tab, in the Library Tools section of the ribbon, in the Workflow Settings drop-down choose Add a Workflow:
211
SharePoint Workflows 3. The following screen appears for every workflow (out-of-the-box or custom). It is important to understand that you are taking a workflow template and associating it with the list or library. You must specify to the workflow a Task List and a workflow History List, and how the workflow will start. Here we choose to run this Approval – SharePoint 2010 workflow against the Proposal - Content Type and call it OOTBApproval. Click on Next:
You will want to put some thought out in the real world, as to whether you should have all your workflows running from one Task / History List or whether you may in fact want unique lists for this workflow. One factor will be the growing size of the actual lists, and another is how you expect people to work with the Task List(s) to perform the approvals themselves.
212
Chapter 7
4. The following screen is the Association Form for the workflow. It is optional for any workflow and provides the ability to specify default data to workflows as they are started. Choose Administrator and fill in the Request field with a message. Click on Save:
5. Go back to the Proposals library. Select a proposal you wish to approve. On the Documents tab of the ribbon in the Library Tools section, click on Workflows:
213
SharePoint Workflows 6. Under Start a New Workflow, click on OOTBApproval:
7. The form that comes up now is called the Initiation Form. Very often this form is the very same one as the Association Form, but it does not necessarily have to be. Note that the "default data" we set up at workflow association time appears on the form. Feel free to modify it (such as the Request text) and click on the Start button:
8. Note the new column that appears in the Proposals library with the title of the workflow and a note for your selected proposal that the workflow is In Progress:
9. Click on In progress, which is a link that takes you to the Workflow Status page. Note the very cool "Workflow Visualization" courtesy of Visio Services! Just below this visualization, you will see a link that says Add or update approvers of this Approval. Click on the link to see an example of a workflow Modification Form. The form is optional, and if present is often different to either the Association or Initiation Form. Note that it brings up the current data for this workflow. Click on Cancel when you are finished examining this form:
214
Chapter 7
10. On the workflow status page scroll down and view the information coming from the Tasks and workflow History List for this approval. For your future reference in custom workflow development, it is best practice to ensure you write out an entry to the workflow History List every time something happens or changes, as somewhat of an audit trail of who did what when, or tracking outcomes. Put another way, workflow history entries do not happen automatically! They are a deliberate action you take in the workflows you develop. Do not be concerned about the errors generated, as we do not have e-mail capabilities set up in this development virtual machine.
215
SharePoint Workflows 11. In the Task section, use the drop-down under Title and select Edit Item:
12. The final workflow form of note is the Task Edit Form. A custom Task Edit form is optional. If one is not provided, you will get the out-of-the-box Task Edit form (the one with priority and percentage complete and such). Update the comments and click on Approve.
If you wish to see the out-of-the-box Task Edit form, simply go to the Tasks list itself and create a new item.
13. Examine the updates to the workflow status page (for example, workflow history). Go back to the Proposals list and note the text under OOTBApproval column has changed to Approved.
216
Chapter 7
By reviewing the out-of-the-box approval workflow, we have noted it has all of the possible workflow "form" types including Association, Initiation, Task Edit, and Modification. All workflow forms are optional, and only required if you need to collect information from the user. Workflows can often have no forms associated with them whatsoever.
There's more... The workflow status page is more for the administrator's benefit than the actual person doing the approval. In the real world, I would suggest directing the person to the Task list where they can see the status of all of the workflow tasks:
However, the All Tasks view is probably useless for a large number of items. The task list itself has many interesting and useful views that actually will help a person get their work done! Such as My Tasks, Due Today, or Active Tasks. You should change the default view in this case.
Copying and extending out-of-the-box workflows with SharePoint Designer 2010 The out-of-the-box approval workflow is awesome and the majority of workflows in my experience tend to be some form of approval. The number one frustration with the previous version (2007) of the approval workflow was that it was not customizable. One small change request, no matter how trivial, meant creating an approval type workflow entirely from scratch. In SharePoint 2010, you are 100 percent able to leverage the out-of-the-box approval workflow using SharePoint Designer 2010! 217
SharePoint Workflows If you have been jaded in the past by turning to the previous version of SharePoint Designer and its severe limitations on workflow development, I encourage you to look again! SharePoint Designer 2010 is a spectacular leap forward in SharePoint 2010 workflow development capabilities! Now, I recommend you never, ever "touch" something provided out-of-the-box, so you will be directed first to make a copy of the out-of-the-box approval workflow, and then make your changes to that copy. Firstly this is a safety net in case anything goes terribly wrong with your changes, but importantly if anyone goes to use the "out-of-the-box approval" and it has in fact been changed, they will be mystified as to why it is not working the way they would expect.
Getting ready Let us get ready by making a copy of the out-of-the-box workflow: 1. Open the Chapter 7 URL in SharePoint Designer 2010. In the Navigation section click on Workflows. Ensure the approval workflow is highlighted. In the Workflows ribbon, click on Copy and Modify:
2. In the Create Reusable Workflow dialog, name the workflow template External Proposal Approval. Modify the description if you wish. Choose Content Type as Proposal from the drop-down. Click on OK:
218
Chapter 7
3. You are ready to begin modifying this workflow!
How to do it... In this recipe, the goal is to modify the workflow so that only Proposal Types of External will go through the approval process. Otherwise the proposal will automatically be approved. In either case, we should write to the History Log to show what type of proposal it was: 1. I will be referring to the following commands in the workflow ribbon:
2. Your workflow edit screen currently appears as follows. Where the flashing orange bar is will be referred to as the "cursor":
219
SharePoint Workflows 3. Developing a SharePoint Designer 2010 workflow is basically a series of Conditions and Actions. Click on the Condition drop-down and choose If current item field equals value:
4. Click on the text "Step 1" and rename it. Click on the action Start Approval Workflow task.., and then click on Move Up in the workflow ribbon. Your screen should look as follows:
5. Click on the field link and you will get a drop-down choice, choose Proposal Type. Click on the value link and you will get a drop-down list of choices – choose External.
220
Chapter 7
6. Click immediately above Start Approval to place your cursor there. From the Action drop-down, choose Log to History List:
7. Click on the this message link in the log to history list action. Type External Proposal Type requires approval as the message. Click immediately below the Start Approval Workflow" action to place your cursor there. The workflow should look as follows:
8. Click on the Else If Branch icon in the workflow ribbon. From the Action drop-down, choose Log to History List. Click on the this message link in the Log To History List action. Type Internal Proposal Type automatically approved as the message.
221
SharePoint Workflows 9. Immediately click below this newest log to history action. From the Action menu, choose Set Workflow Status. If the workflow status does not show Approved, then click on the status and set the choice to Approved. The workflow should now look as follows:
10. In the ribbon, click on Check for Errors. After some time you should see a message box that states The workflow contains no errors. Click on OK. 11. In the ribbon, click on Save. After the workflow is saved, click on Publish Globally. 12. Go back to the Workflows link in the left-hand Navigation section. Highlight the External Proposal Approval workflow:
13. Now click on the Associate to List icon and select Proposals:
222
Chapter 7
14. The Add a Workflow screen will open in the browser. For whatever bizarre reason, the Content Type does not default to Proposal! Change the Content Type to Proposal. Name the workflow my External Approval. Click on Next:
15. See the previous recipe for filling out the Association Form. Click on Save.
How it works... We can now test your workflow: 1. Choose a proposal of type Internal. Start the my External Workflow. Note the workflow ends right away with a status of approved. From the proposal library, click on the Approved link. Note the workflow history was written as expected.
2. Choose a proposal of type External. Start the my External Workflow. From the proposal library, click on the In Progress link. Note the workflow history was written as expected with the message External Proposal Type requires approval. Also note a task has been assigned. Feel free to complete the task in order to finish the workflow. Copying and modifying an existing out-of-the-box workflow is an excellent way to maximize the reuse of, say, the approval workflow and minimize the development time of a custom approval workflow. 223
SharePoint Workflows
Using Visio 2010 to create workflows Visio 2010 now includes a SharePoint Workflow template, allowing the ability to design your workflow visually before you implement that workflow with SharePoint Designer 2010. After designing the workflow, you can directly import it into SharePoint Designer for implementation / modification. You can then even export the workflow back to Visio to see / confirm the updates. This round trip between the tools Visio and SharePoint Designer is important so that you can visually walk through the workflow with your user, make modifications to the diagram, and rapidly prototype / implement the functionality. That is, the overall time from initial design of a workflow to the final product is now substantially reduced! Please keep in mind the goal of this recipe is to walk you through the round trip process. The goal is not to develop an overly complex workflow. This workflow will make a simple decision based on the proposal amount as to whether Finance needs to review it or not. We will simply write to the history log to demonstrate the result.
How to do it... In this recipe, we will create a simple workflow using Visio 2010: 1. Open Visio 2010. In the Template Categories section, click on Flowchart. Under Choose a Template, select Microsoft SharePoint Workflow. On the right-hand side, click on the Create button. 2. A workflow has a beginning and an end! Note the panel with SharePoint Workflow Terminators. Drag a Start shape to the left side of the drawing surface and a Terminate shape to the right:
224
Chapter 7
3. Click on the stencil for SharePoint Workflow Conditions. Drag a Compare Data Sources shape near the center of the drawing area:
4. Click on the SharePoint Workflow Actions stencil. Take a moment to view the extensive list of possible actions! In the right-hand column, five shapes down you will see Log to History List. Drag multiple Log shapes to the drawing surface—one to the left of the Compare shape, and two to the right (one over the other):
225
SharePoint Workflows 5. If you know Visio, you can use the "smart connectors" or drag connectors to connect the shapes together into a flowchart. Label the shapes appropriately to note the start of the workflow, and the decision that will be taken based upon the Proposal Amount. When you are done the diagram should look as follows:
6. Save your diagram as ProposalAmountWorkflow. 7. However, the actual Visio Diagram (VSD) format is not sufficient for SharePoint Designer. We need to export the diagram in Visio Workflow Interchange (VWI) format. In the Process tab of the ribbon, click on Export. Save the file as ProposalAmountWorkflow:
Using SharePoint Designer 2010 to implement Visio 2010 workflows In this recipe, we will implement the Visio 2010 workflow created in the previous recipe, and we will accomplish this by using SharePoint Designer 2010.
How to do it... Now we will import, implement, and enhance the workflow in SharePoint Designer 2010: 1. Open SharePoint Designer 2010 to the Chapter 7 URL. In the Navigation section, click on Workflows.
226
Chapter 7
2. In the ribbon, click on the Import from Visio button. On the dialog that pops up, browse to the ProposalAmountWorkflow.vwi file. Click on Next. 3. In the Import Workflow from Visio Drawing dialog, provide a workflow name such as Proposal Amount Approval, and run this as a List Workflow against the proposals list. Click on Finish:
4. The workflow edit screen will open. Fill in all of the Log to History list messages appropriately. Change the title box of the workflow. 5. We will use a variable to hold the dollar limit that will trigger an approval. In the ribbon, click on Local Variables. On the Edit Variable dialog, provide the Name ApprovalLimit and Type as Number:
6. Place your cursor at the top of the workflow (above the text Proposal Amount Approval Started). From the Actions ribbon, select Set Workflow Variable. Click on workflow variable and choose Variable: ApprovalLimit. Click on value and enter 5000.
227
SharePoint Workflows 7. For the value this test value, click on the first value and click on the fx button. Choose Current Item and Proposal Amount and click on OK:
8. Click on this test and choose is greater than. Click on the second value and click on the fx button. Choose Data source as Workflow Variables and Parameters and choose Field from source as Variable: Approval Limit:
9. Your workflow should now look as follows:
228
Chapter 7
10. In the ribbon, click on Workflow Settings. In the Settings section of the screen, select the Show workflow visualization on status page checkbox. 11. In the ribbon, click on Check for Errors | Save | Publish. 12. In the ribbon, click on the Export to Visio button, and name the updated file ProposalAmountWorkflow_updated.
How it works... It is now time to test our workflow! Note that we have already associated this workflow directly with the Proposals list with SharePoint Designer. So the workflow is ready to go: 1. Navigate to the Chapter 7 URL and the Proposals library. Ensure that you have one proposal available that is for $5,000 or less, and one proposal that is for more than $5,000. 2. Select the proposal that is for $5,000 or less, and run the Proposal Amount Approval workflow. Start the workflow by clicking on the Start button when prompted. The workflow will finish immediately. 3. In the Proposals library, click on the Completed link for the workflow you just ran. First of all note the awesome new "workflow visualization" capabilities of SharePoint 2010! This is accomplished courtesy of Visio Services, but note this is not simply a Visio diagram of your workflow. Look carefully at the green check marks – it actually visually shows the path through the workflow and the path through the compare shape (for example, proposal automatically approved)!
4. Note further down the workflow status page that our History Log entries appear as expected for this proposal:
229
SharePoint Workflows 5. Now run the workflow again for a proposal that is over $5,000. Go to the workflow details when the workflow completes. Note the Visio diagram depicts the path to "Finance" and the Workflow History appears as expected:
Congratulations! As you can see, a workflow can rapidly be designed in Visio 2010 and quickly implemented and tested using SharePoint Designer 2010. This is a mere scratch on the surface of developing workflows using these tools. The possibilities are nearly limitless – keeping in mind that to date I have not yet had to use Visual Studio 2010 to develop a custom workflow. Visio and SharePoint Designer have so far been up to the challenge of creating the custom workflow scenarios I have so far encountered in SharePoint 2010.
There's more... We are able to work seamlessly back and forth between Visio 2010 and SharePoint Designer 2010. Note that during the implementation of the above SharePoint Designer workflow, it was enhanced by adding a "Set Workflow Variable" step. This means the original diagram you presented to the user is now out of date. Or perhaps some documentation you created for the workflow is out-of-date. In the last step before we tested the workflow, we had already exported the updated Visio Workflow Interchange (VWI) file. Open a new (blank) Microsoft SharePoint Workflow in Visio 2010. In the ribbon on the Process tab, click on the Import button:
230
Chapter 7
Browse to the file you had previously created, ProposalAmountWorkflow_updated.vwi and note our updated diagram – similar to what you have seen in the workflow visualization, now appears in Visio:
So let us say now we are satisfied that the logic works for testing the proposal amount, and you are ready to start assigning actual tasks to the Finance department. Go ahead and use Visio to complete the workflow visually. Export the updated diagram and re-import it back to SharePoint Designer. Everything you had previously implemented is preserved, and you can focus on the implementation of the new elements.
Developing workflows in Visual Studio 2010 In this recipe, we are going to develop a very similar Proposal Amount Approval workflow, but this time using Visual Studio 2010 and the Windows Workflow Foundation. This certainly requires a developer to do, but I hope you find during this exercise that it is overall not radically different or more difficult that its Visio / SharePoint Designer counterpart. For added enjoyment, will add an Association Form that is an ASPX page – for you to be able to set the amount of the Approval Limit at the time you associate the workflow to the Proposal Library. This provides some configurable flexibility in the workflow – meaning the limit can be different for different Proposal libraries, and also not having to physically change the workflow code if you need to modify the proposal limit.
231
SharePoint Workflows
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 Sequential Worfklow. In my case, I have named my project VSProposalAmountWorkflow:
3. On the SharePoint Customization Wizard screen, type the Chapter 7 URL in the box What local site do you want to use for debugging?. Deploy as a FARM solution will be selected. Click on Next. 4. Enter VSProposalAmountWorkflow for the name of the workflow and select List Workflow. Click on Next:
232
Chapter 7
5. Important: On the screen Select the lists you will use when debugging, CLEAR the checkbox Yes, associate this workflow…. We wish to manually associate the workflow with the Proposals list in order to trigger our custom Association Form. Click on Finish.
How to do it... First, we will create the Association Form for our workflow. This form will accept the Proposal Limit that we will use in the workflow to compare against the Proposal Amount to determine if an approval is required or not: 1. In the Visual Studio 2010 Solution Explorer, right-click on Workflow1 and choose Add | New Item. Select Workflow Association Form from the Installed Templates and name the form ProposalAmountAssocForm.aspx. Click on Add. 2. Unfortunately, an application (ASPX) page in SharePoint 2010 does not have a designer. Find the PlaceHolderMain and just above the buttons add the following code to create a label and button to collect the Proposal Limit:
3. Right-click ProposalAmountAssocForm.aspx and choose View Code. Find the GetAssociationData method. Replace return string.Empty with the following code: return txtProposalApprovalLimit.Text;
233
SharePoint Workflows 4. Now we will create our workflow to compare the Proposal Amount against the Proposal Limit and write out the result as appropriate to the History Log . In the Solution Explorer, double-click on Workflow1 to open the workflow designer. The Toolbox will now offer "shapes" very similar to Visio Stencils, and creating this workflow will not be unlike the exercise we did for Visio 2010. 5. In the Toolbox, Windows Workflow Foundation 3.0 section, drag an IfElse shape just under the onWorkflowActivated1 shape. 6. In the Toolbox, SharePoint Workflow section, drag three LogToHistoryListActivity shapes to the diagram – one in each of the IfElse branches and one just above the IfElse (and below the onWorkflowActivated1 shape). 7. In the workflow designer, click on ifElseBranchActivity1. In the properties window, select Declarative Rule Condition for Condition. Expand the condition node, click into ConditionName, and then click on the ellipsis button to open the editor:
8. Click on New. Enter the following code. The AssociationData is the Proposal Approval Limit entered on the Association Form: System.Convert.ToDouble(this.workflowProperties.AssociationData) > System.Convert.ToDouble(this.workflowProperties.Item["Proposal Amount"])
234
Chapter 7
9. In the workflow designer, right-click on LogToHistoryListActivity1 and select Generate Handlers. In the code for the generated method, add: logToHistoryListActivity1.HistoryDescription = "VS Proposal Amount Workflow Started";
10. Right-click anywhere in the code and select View Designer. In the workflow designer, right-click on LogToHistoryListActivity2 (in the IfElseBranchActivity1) and select Generate Handlers. In the code for the generated method, add: logToHistoryListActivity2.HistoryDescription = "Proposal automatically approved";
11. Right-click anywhere in the code and select View Designer. In the workflow designer, right-click on LogToHistoryListActivity3 and select Generate Handlers. In the code for the generated method, add: logToHistoryListActivity3.HistoryDescription = "Finance will need to approve this proposal";
12. When you are done, your workflow designer should look as follows:
235
SharePoint Workflows
How it works... Let us test our new Visual Studio Proposal Approval workflow! 1. Press F5 in Visual Studio 2010. This will build, package, and deploy the solution to the Chapter 7 URL and open Internet Explorer. 2. Navigate to the Proposals library. From the ribbon Library tab, click on the Workflow Settings and choose Add a Workflow:
3. Select the Workflow as VSProposalAmountWorkflow, and provide the Name VS Proposal Amount Workflow. Click on Next:
4. The workflow Association Form you created will now appear! Enter a limit to test (in my case 4500) and click on Associate Workflow:
236
Chapter 7
5. Go to the Proposals library. Ensure that you have one proposal available that is $4,500 or less, and one proposal that is more than $4,500 (or whatever limit you had set in the previous step). 6. For the proposal that is for less than $4,500, start the VS Proposal Amount Approval workflow. The workflow will end immediately. Click on the Completed link to view the workflow status page and note the entries in the Workflow History:
7. For the proposal that is for more than $4,500, start the VS Proposal Amount Approval workflow. The workflow will end immediately. Click on the Completed link to view the workflow status page and note the entries in the Workflow History:
Congratulations on creating your Visual Studio 2010 Sequential Workflow! I trust that through this chapter you now know all of the possible workflow development possibilities that exist, and are able to choose the most appropriate one for your needs.
237
8
Web Content Management The typical developer tasks involved in a publishing site are: ff
Branding with Master Pages and CSS and deploying a Branding solution
ff
Creating and deploying custom publishing page layouts
ff
Deploying custom Content Types, Lists, and Libraries
ff
Custom web parts and SharePoint data queries
ff
Client-side development using Client Object Model, jQuery / JavaScript, and RESTful data services
In this chapter, we will cover: ff
Creating Publishing Pages
ff
Modifying Navigation settings
ff
Creating and using Page Layouts
ff
SharePoint 2010 Branding
In this chapter, let us get comfortable with WCM and publishing sites. The tools that we will be using in this chapter will be the settings in the browser as well as SharePoint Designer 2010.
Introduction In this chapter, I will provide a non-developer overview of an entire other side of SharePoint 2010, and that is an integrated Web Content Management (WCM) system. In the old days, SharePoint 2003 was an entirely separate product from the then Microsoft Content Management Server (MCMS) 2002. The products came together in Microsoft Office SharePoint Server 2007, and have evolved nicely in SharePoint 2010!
Web Content Management The SharePoint 2010 template for web content management is the Publishing Site. To be fair, an all out developer's view of SharePoint 2010 WCM would be an entire book in itself, with topics such as, how to take the out-of-the-box publishing template and turn this into the graphical vision that a Designer would create (called a composite) using Adobe tools (PSD file). If you wish to view an example that I have worked on, go to http://www.lethbridge.ca and see the City of Lethbridge, which is near Calgary, Alberta in Western Canada. Literally, we received composites from a Designer depicting what all the pages on the public site should look like, and our job was to take the out-of-the-box Adventure Works publishing site and turn it into the end result.
Creating Publishing Pages In this recipe, we will create a new publishing site, and get familiar with creating new web pages. In the world of Web Content Management, web pages are created and edited by content authors and then must be published by web masters before the page actually becomes visible to the public. In-between is a special publishing approval workflow (not like the out-of-the-box approval workflow that we saw back in Chapter 7, Web Content Management) that kicks off to notify the approver (for example, the web master) and allows him/her to accept or reject the request to publish the page.
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 correct web application is selected. Enter Chapter 8 for the title and Chapter8 in the textbox for the URL. 3. In the Template Selection section, choose the Publishing tab and select the Publishing Portal template, as shown in the following screenshot:
4. Enter administrator for the Primary Site Collection Administrator. 5. Leave all the others at their respective default settings. Scroll to the bottom and click OK.
240
Chapter 8
6. When the Top Level Site Successfully Created screen appears, click on the link provided. Bookmark the site to your favorites. The publishing site appears as follows:
Note that I will refer to this site in this chapter as the Chapter 8 URL for creating Visual Studio 2010 projects and/or SharePoint Designer 2010 later. For example, in my case, this URL is http://intranet. theopenhighway.net/sites/Chapter8.
7. You will need to add yourself to the Approvers group. Scroll down to the bottom of the home page and select the link Add users to the Approvers and Members groups, as shown in the following screenshot:
8. On the People and Groups page that appears, click on the Approvers group. On the People and Groups – Approvers page, select the new drop-down menu and choose Add Users. 241
Web Content Management 9. In the Grant Permissions pop-up, enter Administrator and click OK. The following screen should appear:
How to do it... In this recipe, we will look behind the scenes of a publishing site and then create new web pages in the Press Releases site: 1. Navigate back to the home page, that is, the Chapter 8 URL 2. From the Site Actions menu, select View All Site Content. Take a moment to review the important Document Libraries created and their purposes, as shown in the following screenshot:
The most important of these is the Pages library. The overall navigation of a public website will follow the structure of the publishing site hierarchy. Each publishing site is an area of the website, for example, a typical public website might have an area for About Us, Contact Us, Press Releases (or News), Products, Services, and so on. Each area of the site will have one or more web pages. In SharePoint 2010, each area of the website is a Publishing site, and the web pages are all stored in the Pages library. 242
Chapter 8
1. In order to create some new web pages for the Press Release site, navigate to the home page, that is, the Chapter 8 URL 2. Click on the Press Releases link on the left-hand side navigation. This will take you to the home page of the Press Releases sub site. 3. From the Site Actions menu, select New Page. In the New Page dialog, enter Q1 Results and click Create. Enter some content in the Page Content area, as shown in the following screenshot. Note the powerful full editing ribbon that appears. As an example, I used the Markup Styles drop-down to select style Callout 1:
4. Place your cursor in the Page Content area of the page. In the Editing Tools section of the ribbon, on the Insert tab, choose Picture | From Computer. Browse to an image of your choice and ensure that Upload to is set to Images, as shown in the following screenshot:
5. You will get an additional screen that lets you set detailed metadata for your image. Enter data as you wish and click Check in in the Edit ribbon. Very conveniently, you have not only uploaded an image to the Images library, but also embedded the image into the web page at the same time. 243
Web Content Management 6. In the Editing Tools section of the ribbon, on the Format Text tab, click Save and Close 7. The Q1 Results page is currently checked out to the content creator. This means it is locked for editing by only the author. So, we now need to get this draft checked in, published, and approved, including reviewing the publishing workflow. Click on the Page tab in the ribbon and click on the Check In icon. Fill in the check in comments and click Continue. 8. Remember that if this is a public-facing website, the checked in page is not visible to the public, until we have completed the approval. 9. Click on the Publish tab in the ribbon. Your page should appear similar to the following screenshot:
10. Click on the Submit icon. You will be starting the publishing approval workflow. The workflow initiation form shows, and we see that it is very similar to the approval workflow of the previous chapter. Fill in some details and click Start:
244
Chapter 8
11. Notice that you did not specify the Assigned To person. Automatically, this is assigned to anyone in the Approvers group, which is why you needed to assign yourself to this group in the Getting Started section. 12. Note that the page is now showing with the status Waiting for Approval. Normally, it is not the author (you, in this example) that also approves the page for publication. So, please pretend your role has now changed to the web master! 13. On the Q1 Results page, now as the web master (the Approver), go to the Publish tab of the ribbon:
14. When published, the page does not have to appear immediately! It can actually be scheduled for a future date. This allows you to put in the announcement regarding the Quarter 1 financial results ahead of time, and it will only appear to the public on the specified date. Similarly, you can have control of when the web page no longer appears on the site. For example, if the web page was advertising a sale from the 1st to the 15th of February, you could schedule the sale information to appear only during that period of time.
245
Web Content Management 15. Look at the schedule screen by clicking on the Schedule icon. Click Cancel when you are done, as shown in the following screenshot:
16. On the Publish tab of the ribbon, click on Approve. On the Approve dialog, enter some comments and click Continue. Fill in some task details and click Approve:
Congratulations! You have successfully created, submitted, and approved a page for publication!
246
Chapter 8
Modifying navigation settings From the home page of the Chapter 8 URL, click on Press Releases. How do we navigate back to our Q1 Results page? That's a good question, considering there is no link in the navigation for the page! The out-of-the-box navigation is configured only to show the sites for navigation purposes—in this case, the Press Releases site. Typically, you will also want to display the Pages in the pages library as links in the navigation. In this recipe, we will take control of our navigation settings!
How to do it... In this recipe, we will modify the navigation settings to show web pages as links, and to add our own navigation to the Microsoft site: 1. From the home page of the Chapter 8 URL, click on Press Releases. 2. Click on Site Actions | Site Settings. From the Look and Feel section, choose Navigation. In the Current Navigation section, choose the option Display the same navigation items as the parent site and select the Show Pages checkbox:
3. Note that the Q1 Results page now appears as a link under Press Releases, as shown in the following screenshot. 4. Note that the Folder icon can be clicked to display where you are in the website hierarchy. Now, use this aid to go back to the home page (Chapter 8) in my case:
247
Web Content Management 5. From the home page of the website, choose Site Actions | Site Settings. Under the Look and Feel section, choose Navigation. In the Navigation, Editing, and Sorting section, select Current Navigation node, and then click on Add Link. Put in a title of Microsoft and a URL of http://www.microsoft.com and click OK. Click on the Microsoft link, and use the Move up function to move it above Press Releases. Your screen should look similar to the following screenshot when you are done:
6. Click OK when finished. 7. Navigate to the home page and the Press Releases site. Note the consistent navigation that comes from a combination of dynamically created sites and pages, as well as your own inserted static links (for example, Microsoft). Congratulations on taking control of the navigation in a Publishing site!
Creating and Using Page Layouts When you created the Q1 Results page in the Press Releases site, you filled in the Title and Page Content on what is known as a Publishing Page Layout called the Article Page. This is the most generic type of page layout for SharePoint 2010 WCM. However, just like a web form, you can extend the Article Page Layout by adding additional fields! This task is accomplished by using SharePoint Designer 2010. In this recipe, we want to add a Proposals section to our website, where we can provide a web page that gives an overview and more information about a particular proposal, and then a link to the proposal itself. When filling out the web page, similar metadata should be specified, such as the proposal type, client, and amount. In order to accomplish this, we will be creating a custom Publishing Page Layout for our proposals. Since everything in SharePoint is based on a content type, you should perhaps not be surprised that, when we go to create our own custom page layout, we will start by defining a content type! It will inherit from the Article Publishing Layout. Then we use SharePoint designer to lay out the fields on the web page, very much like dragging controls from the tool box onto the design surface of an ASPX page. 248
Chapter 8
Getting ready When you examined the Document Libraries available on the publishing site, you may have noticed that our Proposals document library was not there. The feature staple we had in place was only for the team site definition, and therefore did not activate the features automatically for the publishing site definition. We are going to get ready by activating the site collection features, creating a Proposals sub site, and then activating the Proposal Library feature on the new sub site. 1. Navigate to the home page, that is, the Chapter 8 URL. Go to Site Actions | Site Settings. From the Site Collection Administration section select Site Collection Features. 2. Activate the feature Proposal Library Schema. Activating this feature assumes you have completed Chapter 2, SharePoint Development with Visual Studio . If you have not, then skip this step. 3. From the Site Actions menu, select New Site. From the Create screen, leave the default of Publishing Site with Workflow. Enter the title as Proposals and the URL name as proposals. 4. You will be taken to the home page of the Proposals site, and note that Proposals has appeared on the left-hand side navigation. 5. From Site Actions | Site Settings, choose Navigation from under the Look and Feel section. 6. In the Current Navigation section, choose Display the same navigation items as the parent site and select the Show pages checkbox. 7. From Site Actions | Site Settings, choose Manage Site Features from the Site Actions section. 8. Activate the Proposal Library feature. 9. If you have not completed Chapter 2, then this feature will not exist. Instead, you can create a new document library called Proposal Library. 10. From Site Actions | View all site content, go to the Proposals document library. Create and/or upload a selection of proposal documents. Excellent! We are now ready to create our own custom page layout for a proposal.
How to do it... By activating the Proposal Library Schema, we already have the required site columns. We will now create a Proposals Content Type appropriate for use as a page layout: 1. Navigate to the home page, that is, the Chapter 8 URL. 2. From Site Actions | Site Settings, choose Site Content Types under Galleries. 249
Web Content Management 3. Click the Create link and enter the name Proposal Page Layout. In the Select parent content type from drop-down, choose Page Layout Content Types. In the Parent Content Type drop-down, choose Article Page. 4. In the Group section, select New Group, enter Packt Content Types, and click OK. 5. On the Site Content Type Information screen, scroll down towards the bottom and select Add from existing site columns. 6. On the Select Columns screen, select Packt Publishing Columns, then select Proposal Amount, Proposal Client, and Proposal Type, and click OK. 7. We are now ready to create our page layout using SharePoint Designer. Open the Chapter 8 URL in SharePoint Designer 2010. In the Navigation section, click on Page Layouts. 8. From the Page Layouts ribbon, select New Page Layout. From the New dialog, select content type group as Packt Content Types, content type name as Proposal Page Layout, URL name as ProposalPageLayout, and Title as Proposal Page Layout and click OK. 9. The ProposalPageLayout.aspx page will automatically open for editing. Notice the Toolbox pane on the left. If the Toolbox is not visible, go to the View tab of the ribbon, click on the Task Panes drop-down, and select Toolbox. Scroll to the bottom to see the Page Fields and the Content Fields sections, as shown in the following screenshot:
10. With the cursor on the PlaceHolderMain, press Enter to create a blank line. From the toolbox, you can drag-and-drop the content field Page Content to the bottom of the PlaceHolderMain. 250
Chapter 8
11. Place your cursor at the top of the PlaceHolderMain. From the Insert tab of the ribbon, insert a 2x6 table. In the first column of the table, type Title:, Byline:, Article Date:, Proposal Type:, Proposal Client:, and Proposal Amount:. 12. From the Page Fields section on the toolbox, drag the Title field to column 2, row 1 of the table. 13. From the Content Fields section on the toolbox, drag the appropriate fields to column 2 of the table. The PlaceHolderMain section of your page layout should now look similar to the following screenshot:
14. Save the file. 15. On the left-hand side of SharePoint Designer, click on Page Layouts. Highlight ProposalPageLayout.aspx. From the ribbon, select Check In. On the Check In screen, select Publish a major version and click OK. 16. You will be prompted with The document requires approval. Do you want to view or modify its approval status?. Just click on Yes. 17. A browser window will open. In the Approval Status: Pending section, use the drop-down menu on ProposalPageLayout and select Approve/Reject, as shown in the following screenshot:
18. On the Approve/Reject screen dialog, select Approved and click OK. 251
Web Content Management
How it works... We are now ready to put our new page layout to use! Carry out the following steps to do so: 1. Navigate to the Proposals site. Select Site Actions | New Page. On the New Page dialog, enter the name Acme Proposal and click Create. You will notice that the Page Layout is still the default Article Page, but you can change the page layout on demand to any of the many out-of-the-box page layouts or (of course) to our newly created one. 2. From the Page tab in the ribbon, click on the Page Layouts drop-down. You can explore the many available out-of-the-box layouts and scroll down to see Proposal Page Layout. Select Proposal Page Layout:
3. You will now see the page layout in Edit mode—where all of the fields appear for editing, based on their type; for example, calendar selection for dates and a drop-down selection for Proposal Type, as shown in the following screenshot. Enter some information for your proposal:
252
Chapter 8
4. Place your cursor in the Page Content area, below the text you have already entered. We are going to insert a link to a proposal in the document library. From the Editing Tools Insert tab, select the Link drop-down from the menu and insert the link From SharePoint. The Select an Asset dialog will come up. Navigate to the Proposals library and select an appropriate Proposal:
5. You can modify the text of the link (I changed it from the document name to the word here). You can also use the Link Tools Format tab in the ribbon to change the properties of the link as desired. 253
Web Content Management 6. On the Page tab of the ribbon, click on Save and Close. Note that you will now see the view as if it were from the public site. Clicking on the here link will open the proposal document, as shown in the following screenshot:
7. Notice that a link in the left-hand side navigation of your proposal is missing. Note that the link will not appear until the page is fully published. 8. Publish the page following the same procedure that we used for our sample Article Page—Q1 Results in Press Releases. Check in the page and submit for approval. Approve the page. Note that the left-hand side navigation now shows the link to your new page, as shown in the following screenshot:
Congratulations for creating a new Proposals section for your Publishing site, along with creating and using a custom page layout for Proposals!
SharePoint 2010 Branding Branding a SharePoint 2010 site means, for me, taking the out-of-the-box Publishing site and changing it visually, as per the Graphic Designer's composite vision. There is a mix of developer and designer skills that are required to make this happen, which certainly makes it difficult to find an overall good SharePoint Branding person. I would highly recommend that, in practice, we should team up two people to accomplish the branding of a SharePoint site. The first one is the web developer, the second one is someone highly skilled with HTML and CSS.
254
Chapter 8
The following skills will be involved in this exercise: ff
HTML and CSS, as well as cutting graphics.
ff
Creating master pages and page layouts
ff
XSLT to transform data or search queries to HTML output
ff
Programming with the Client Object Model and REST
ff
Web scripting via JavaScript and/or jQuery
As you can see, this is mostly about the frontend of web development, and generally has very little to do with SharePoint at all. The tasks and tools would be similar regardless of the Content Management System that you are using.
How to do it... For this final recipe, I will show you the places to go within Site Settings and SharePoint Designer to accomplish the key SharePoint branding tasks, and then afterwards direct you to the key SharePoint 2010 resources: 1. Navigate to the home page, that is, the Chapter 8 URL. From the Site Actions menu, select View All Site Content. Please recall from the earlier chapters the key libraries for placing your branding assets including images, CSS, and XSLT:
2. If you need to add JavaScript (.js) files, then in the Style Library, create a Scripts folder and place your custom .js files there. Feel free to refer and use your JavaScript files, for example, in your master pages. 3. Navigate to the home page, that is, the Chapter 8 URL. Go to Site Actions | Site Settings. Select Master Page from under the Look and Feel section. 255
Web Content Management 4. Note that the out-of-the-box publishing master page is called nightandday.master. Let us say that you have created a new master page called Packt.master, and you can choose to change it here and also apply to all sub-sites as well. Also, if you have created a CSS file that may override OOTB CSS or may extend it, you can specify it here as well:
5. Open the Chapter 8 URL in SharePoint Designer 2010. In the Navigation section, click on Master pages. Here is a description of the master pages you see: Default.master: Do not use this for SharePoint 2010. This was the master page for SharePoint 2007 and is retained for backwards compatibility purposes. Minimal.master: This page is used by Search Center, and hence you will actually need to consider this for branding. This master page often gets overlooked initially. Nightandday.master: The out-of-the-box publishing master page for the Adventure Works site. V4.master: The new master page for SharePoint 2010. This master page applies to non-publishing sites (for example, team sites) and also to system pages, such as Site Settings. For system pages, this replaces the old application.master. 256
Chapter 8
6. For your site, you will surely need to create a new master page. You would create it in this master page gallery. However, it is not recommended to modify the out-of-the-box ones at all, nor to copy and modify these. Rather, a much better set of starter master pages is provided on Codeplex. See the There's more section for more information. 7. Of course, you may be creating one or more page layouts as well. 8. You may be asked to customize the Publishing Approval workflow. Go to workflows in SharePoint designer and you can copy and modify the Publishing Approval workflow. Thanks for taking some time to introduce yourself to the entirely different world of Web Content Management / Publishing in SharePoint 2010. Certainly, everything is there for you to create a very professional looking public facing website in SharePoint 2010! The best compliment you can receive is that your website does not look like a SharePoint site!
There's more... Resources are your key to successful branding! There is a lot of great information that is available to you. The current recognized expert in the branding community is Randy Drisgill, a fellow SharePoint MVP. Find his blog at http://blog.drisgill.com/. Randy provides very useful starter master pages for SharePoint 2010 on CodePlex at http://startermasterpages.codeplex.com/
If you need a more comprehensive overview of the CSS that is used by SharePoint, see the SharePoint CSS chart at http://sharepointexperience.com/csschart/csschart.html
257
Index Symbols .NET Client Object Model working with 155-161 _selectedColor variable 99 _textColor property 94 _vit_bin virtual directory 155
A Active Directory 8 Adobe tools (PSD file) 240 alternative software 9 AmazingVisualWebPartUserControl class 92 ApplyChanges method 101 ASP.NET web application 48 ASPX page 132 Association Form 213 ATOM 172
B branding SharePoint 2010 254-257 Business Data Connectivity (BCD) 194 Business Data Connectivity Services (BCS) 194 Business Data List Web Part used, for creating Publishers Search 203-207
C CAB (compressed) format 48 CAML (Collaborative Application Markup Language) 146
CAML query 160 Category attribute 93, 96 Central Administration about 57 solution status, viewing 61 chevron 133 Client.svc 155 CodePlex about 257 URL 33 composite 240 computer’s BIOS settings 9 connected Web Parts creating 104-115 Contact Content Type 47 content authors 240 Content Type Gallery 46 Content Types about 44, 61, 194 creating 61, 62 document libraries, creating 65-67 exploring 44-47 Proposal Content Type, implementing 62 solution, deploying 64, 65 Content Type XML file 63 CreateChildControls method 82, 87, 149 CreateHyperLinks method 167 custom Editor Parts creating 97-104 custom Web Part properties creating 91-94 Editor Parts, creating 97-104 working 94-96
D Data Definition Language 44 Data Form Web Part using, with SQL Server 181-187 using, with WCF data 188-193 Data Service 172 data, Sharepoint retrieving, LINQ to SharePoint used 146-151 retrieving, list data service used 151-154 developer tasks, for publishing site 239 document libraries about 43 creating, Content Types used 65-67
E ECMAScript 161 EditorPartCollection method 102 Elements.xml 57 Event Receivers 44 Extensible Stylesheet Language Transformation. See XSLT External Content Type about 194 testing 201-203
F Feature Receivers about 44, 68 activating 68 deactivating 68 On Activate 68 On Deactivate 68 Solution, deploying 69 features exploring 48, 49 Feature Staplers about 44, 74, 76 testing 76 feature.xml file 57
G gadgets 77 GUID Generator 54
260
GUIDGEN tools 54 GUIDs generating 54
H HTMLTextWriter object 82 Hyper V 8 Hyper-V role 10
I Imtech Get SPMetal Definition Extension 147 InfoPath List Forms, creating with 135-142 Information Worker virtual machine 8 Initial configuration tasks screen 11 InitializeComponent() statement 168 Initiation Form 214 Inline Edit 142 Inline Edit mode enabling 142, 143 installation Microsoft Office 2010 Professional 27 recommended developer tools 32 SharePoint Designer 2010 30 SharePoint Server 2010 20 SQL Server 2008 R2 15 Visio Premium 2010 29 Visual Studio 2010 30 Windows Server 2008 R2 10 IPrettyColor interface 115 ISO image 11
L Libraries 171 LINQ 146 LINQ to SharePoint used, for retrieving data 146-151 list data service used, for retrieving SharePoint data 151-154 List Event Receivers about 70 features 70 List Forms creating, SharePoint Designer used 132-135 creating, with InfoPath 135-142
lists 43, 171 lists web service 161 List View Web Part 78, 79 Local intranet zone 41
M Manifest tab 58 methods, SPItemEventReceiver class ItemAdded 70 ItemAdding 70 ItemDeleted 70 ItemDeleting 70 ItemUpdated 70 ItemUpdating 70 Microsoft Content Management Server (MCMS) 2002 239 Microsoft Office 2010 Professional installing 27, 28 Microsoft Office SharePoint Server 2007 239 Microsoft Silverlight installing 26, 27 Microsoft Virtualization 10 Modification Form 214 MSI (windows installer) files 47
N navigation settings modifying, in publishing site 247, 248
O oData 180 OnPreRender method 94 OOTBApproval 212 Open Highway URL 24, 34 Oracle Virtual Box about 10 URL 10 out-of-the-box workflows about 210, 217 Association Form 213 configuring 211-213 copy, creating 218
Initiation Form 214 Modification Form 214 modifying 219-223 Task Edit Form 216 testing 223 using 210
P Packaging Designer about 58 exploring 58, 59 Page Layouts creating 248-254 using 248-254 Password1 11 Personalizable attribute 93, 96 PowerShell automation 8 PowerShell commands 57 preferred software 9 Press Releases site 242 PrettyColors 91 productivity tool 147 Proposal Library feature stapling 75 ProposalLibraryFeatureReceiver 75 Proposal Content Type about 64 creating 249-251 Proposals.cs file 149 ProposalSiteColumns XML, typing 55 ProposalSiteColumns.xml 57 publish and subscribe method 105 Publishers Search creating, Business Data List Web Part used 203-207 publishing pages creating 240-246 Publishing Portal template 240 publishing site about 240 creating 240 developer tasks 239 navigation settings, modifying 247, 248
261
R recommended developer tools installing 32, 33 recurring pattern 121 Remote Desktop (RDP) 12 RenderContents method 82 RESTful interface 172 REST Services 181 reusable workflow creating 218, 219 Rich Internet Applications (RIA) 161 Roles node 12
S Sandboxed Solutions 33 Server Manager 12 Service Contract 105 SetTextColor method 94 SharePoint about 8 Content Type 44 document library 43 features, exploring 47 lists 43 .NET Client Object Model, working with 155-161 Silverlight Client Object Model, working with 161-170 Site Columns 44 Site Columns, creating 49-53 Solutions 48 Solutions, exploring 48 SharePoint 2003 239 SharePoint 2010 about 239 branding 254-257 external content types 194-201 external content types, testing 201-203 lists 194-201 SharePoint Connections 148 SharePoint Designer 27 SharePoint Designer 2010 about 117, 171, 210 capabilities 119-121 exploring 118-121 262
Inline Edit mode, enabling 142, 143 installing 30 List Forms, creating with InfoPath 135-142 recurring pattern 121 used, for creating List Forms 132-135 used, for implementing Visio 2010 workflow 226 Visio 2010 workflow, implementing 227-229 Visio 2010 workflow, importing 227 working with, XSLT List View Web Part 122-131 SharePoint developer tools installing 33 SharePoint development 8 SharePoint Limited Web Part Manager 104 SharePoint LINQ development 147 SharePoint MVP Waldek Mastykarz 147 SharePoint Server 2010 configuring 20-26 downloading 20 installing 20-26 Web Parts 77 Web Parts, exploring 78-81 SharePoint Solutions Feature, activating 60 Feature, deploying 60 packaging 57-59 status, in Central Administration 61 summary points 57 SharePoint workflows about 209 out-of-the-box workflows, using 210 workflow, creating using Visio 2010 224 Silverlight Client Object Model working with 161-170 SilverlightClientOM module 164 Silverlight Web Part 166 site collection creating 45 creating, steps 240, 241 site collection features, Web Parts 86 Site Columns about 44 creating 49-52 exploring 44-47 Feature, verifying 56
Site Column types about 56 boolean 57 choice 56 currency 57 datetime 57 integer 56 note 56 text 56 Solution Explorer 147 Solutions about 48 exploring 48, 49 SP2010ProposalLibrary 61 SP2010ProposalLibrary Visual Studio Solution about 71 deploying 72, 73 SP2010WebPart 81 SPItemEventReceiver class about 70 methods 70 Splash.hta 22 SPMetal.exe 146 SQL 8 SQL-like syntax 146 SQL Server configuration, modifying 173-175 Data Form Web Part, using with 181-187 Mixed Authentication, using 173-175 setting up 173-175 SQL Server 2008 R2 configuring 15-20 installing 15-20 SQL Server sample databases downloading 172, 173 installing 172, 173 starter master pages about 257 URL 257 SynchChanges method 101 system pages 256
T Task Edit Form 216
V virtual environment selecting 9, 10 Virtual Hard Drives (VHDs) 9 Visio 27 Visio 2010 about 224 SharePoint Workflow template 224 used, for creating workflow 224-226 Visio 2010 workflow demo 228 implementing, SharePoint Designer 2010 used 226 importing, in SharePoint Designer 2010 226 testing 229 workflow visualization 231 working 229, 230 Visio Diagram (VSD) format 226 Visio Premium 2010 installing 29, 30 Visio Workflow Interchange (VWI) format 226 Visual Studio 8 Visual Studio 2010 installing 30, 31 used, for creating Web Parts 81-84 used, for deploying Web Parts 81-84 workflows, developing 231, 232 Visual Studio 2010 workflow Association Form, creating 233 developing 231-234 testing 236, 237 VSProposalAmountWorkflow 232 Visual Studio project creating 50 Feature, adding 52 GUIDs, generating 54 image, adding to feature 53 Proposal Library Feature 53 ProposalSiteColumns 52 Visual Studio solution creating 175-180 Visual Web Parts creating 87-89 working 90
263
VMware Workstation about 10 URL 10 VSProposalAmountWorkflow 232
W WCF data Data Form Web Part, using with 188-193 WCF Data Service creating 175-180 web application advantages 34 setting up 33-39 WebBrowsable attribute 93, 96 Web Content Management (WCM) about 239 navigation settings, modifying in publishing site 247, 248 Page Layouts, creating 248-254 Page Layouts, using 248-254 publishing pages, creating 240-246 WebControls namespace 77 WebDescription attribute 93, 96 WebDisplayName attribute 93, 96 web masters 240 web pages 240 webpart file 83 Web Part Gallery 86 WebPartLINQProposals 147 WebPartLINQProposals.cs file 149 Web Parts about 77, 147, 181 connected Web Parts, creating 104
264
creating, Visual Studio 2010 used 81-84 custom properties, creating 91 deploying, Visual Studio 2010 used 81-84 disappearing 85 exploring, in SharePoint 2010 78-81 features 86 site collection features 86 Visual Web Parts, creating 87 Web Part gallery 86 WebPartUsingRenderContents 83 widgets 77 Windows 7 64-bit version 8 Windows Communication Foundation (WCF) 105, 172 Windows Server 2008 R2 server about 8 configuring 10-14 installing 10-14 Windows Shutdown Event Tracker 14 workflow creating, Visio 2010 used 224-226 developing, in Visual Studio 2010 231, 232
X XAML (eXtensible Application Markup Language) 161 XML typing, in ProposalSiteColumns 55 XML language 172 XSLT 122 XSLT List View Web Part about 122, 181 working with 122-131
Thank you for buying
Microsoft SharePoint 2010 Development Cookbook
About Packt Publishing
Packt, pronounced 'packed', published its first book "Mastering phpMyAdmin for Effective MySQL Management" in April 2004 and subsequently continued to specialize in publishing highly focused books on specific technologies and solutions. Our books and publications share the experiences of your fellow IT professionals in adapting and customizing today's systems, applications, and frameworks. Our solution-based books give you the knowledge and power to customize the software and technologies you're using to get the job done. Packt books are more specific and less general than the IT books you have seen in the past. Our unique business model allows us to bring you more focused information, giving you more of what you need to know, and less of what you don't. Packt is a modern, yet unique publishing company, which focuses on producing quality, cutting-edge books for communities of developers, administrators, and newbies alike. For more information, please visit our website: www.PacktPub.com.
About Packt Enterprise
In 2010, Packt launched two new brands, Packt Enterprise and Packt Open Source, in order to continue its focus on specialization. This book is part of the Packt Enterprise brand, home to books published on enterprise software – software created by major vendors, including (but not limited to) IBM, Microsoft and Oracle, often for use in other corporations. Its titles will offer information relevant to a range of users of this software, including administrators, developers, architects, and end users.
Writing for Packt
We welcome all inquiries from people who are interested in authoring. Book proposals should be sent to [email protected]. If your book idea is still at an early stage and you would like to discuss it first before writing a formal book proposal, contact us; one of our commissioning editors will get in touch with you. We're not just looking for published authors; if you have strong technical skills but no writing experience, our experienced editors can help you develop a writing career, or simply get some additional reward for your expertise.
Microsoft SharePoint 2010 Development with Visual Studio 2010: Expert Cookbook ISBN: 978-1-84968-458-3
Paperback: 296 pages
Develop, debug, and deploy business solutions for Microsoft SharePoint applications using Microsoft Visual Studio 2010. 1. Create applications using the latest client object model and create custom web services for your SharePoint environment with this book and ebook. 2. Full of illustrations, diagrams and key points for debugging and deploying your solutions securely to the SharePoint environment. 3. Recipes with step-by-step instructions with detailed explanation on how each recipe works and working code examples.
Microsoft SharePoint 2010 End User Guide: Business Performance Enhancement ISBN: 978-1-84968-066-0
Paperback: 424 pages
Taking the basics to the business with no-coding solutions for the SharePoint 2010 1. Designed to offer applicable, no-coding solutions to dramatically enhance the performance of your business 2. Excel at SharePoint intranet functionality to have the most impact on you and your team 3. Drastically enhance your End user SharePoint functionality experience 4. Gain real value from applying out of the box SharePoint collaboration tools
Please check www.PacktPub.com for information on our titles
Microsoft SharePoint 2010 Power User Cookbook ISBN: 978-1-84968-288-6
Paperback: 344 pages
Over 70 advanced recipes for expert End Users to unlock and apply the value of SharePoint 1. Discover how to apply SharePoint far beyond basic functionality 2. Explore the Business Intelligence capabilities of SharePoint with KPIs and custom dashboards 3. Take a deep dive into document management, data integration, electronic forms, and workflow scenarios 4. Join the dots by building three composite "no
code" applications
Microsoft SharePoint 2010 Administration Cookbook ISBN: 978-1-84968-108-7
Paperback: 288 pages
Over 90 simple but incredibly effective recipes to administer your SharePoint applications 1. Solutions to the most common problems encountered while administering SharePoint in book and eBook formats 2. Upgrade, configure, secure, and back up your SharePoint applications with ease 3. Packed with many recipes for improving collaboration and content management with SharePoint 4. Part of Packt's Cookbook series: Each recipe is a carefully organized sequence of instructions to complete the task as efficiently as possible .
Please check www.PacktPub.com for information on our titles