Hands-On Lab

Visual Studio 2010 SharePoint Tools
Lab version: 1.0.0 Last updated: 5/4/20104/14/20103/4/20102/2/2010

Page 1

CONTENTS
Field Code Changed

OVERVIEW ................................ ................................ ................................ ................................ ............. 3
Field Code Changed

EXERCISE 1: CREATING A SHAREPOINT 2010 PROJECT ................................ ................................ .. 6

Task 1 Navigating the new Site Collection................................ ................................ ...................... 6 Task 2 Creating a New SharePoint Project ................................ ................................ ..................... 7 Task 3 Adding a new Feature................................ ................................ ................................ ....... 11 Task 4 Adding Images to Your Project................................ ................................ .................. 141413
EXERCISE 2: FEATURE EVENT RECEIVER................................ ................................ ........................ 18

Field Code Changed Field Code Changed Field Code Changed Field Code Changed Field Code Changed

Task 1 Adding a Feature Event Receiver ................................ ................................ .............. 191918 Task 2 Adding Functionality to the Event Receiver................................ ................................ ....... 20
EXERCISE 3: DEPLOYING AND DEBUGGING SHAREPOINT PROJECTS................................ ......... 23

Field Code Changed Field Code Changed Field Code Changed

Task 1 Configuring and Deploying a SharePoint Project................................. .............................. 23 Task 2 Debugging SharePoint Feature Using Visual Studio 2010................................ ........... 303029
EXERCISE 4: CREATING, DEPLOYING AND TESTING WEB PARTS ................................ ........ 333331

Field Code Changed Field Code Changed Field Code Changed

Task 1 Adding a new Web Part................................ ................................ ............................ 333331 Exercise 4: Verification................................ ................................ ................................ ........... 393937
EXERCISE 5: CREATING A VISUAL WEB PART WITH AJAX BEHAVIOR ................................ . 424240

Field Code Changed Field Code Changed Field Code Changed

Task 1 Adding a Visual Web Part ................................ ................................ .......................... 424240 Task 2 Adding Markup to the Web Part................................ ................................ ............... 464644 Task 3 Implementing the Web Part ................................ ................................ ...................... 505048 Exercise 5: Verification................................ ................................ ................................ ........... 535351
SUMMARY ................................ ................................ ................................ ................................ .... 565654

Field Code Changed Field Code Changed Field Code Changed Field Code Changed Field Code Changed

Page 2

OverviewOverview
In this lab you willstart using the Visual Studio 2010 SharePointDevelopers Tools. This will give you a chance to become familiar with the standard project structure used by SharePoint Developers Tools. You will go through the steps of creating and testing a project that contains a Feature, aFeature Receiver and a Web Part. Along the way you will learn to configure the SharePoint project sdeployment options as well debug a SharePointproject using Visual Studio 2010 by single-stepping through the code in your solution.

Objectives
In this Hands-On Lab, you will learn how to: y Create a brand new SharePoint project using the templates included in the SharePoint Developers Tools Create and code a Feature Event Receiver in order to react to SharePoint feature activation and deactivation. Configure, deploy, test and debug a SharePoint project using Visual Studio 2010 SharePoint developers Tools Create, modify and test SharePoint Web Parts using Visual Studio 2010. Create, modify and test SharePoint Ajax-enabled Visual Web Parts using Visual Studio 2010.

y

y

y y

Exercises
This Hands-On Lab is comprised by the following exercises: y y y y y Creating a SharePoint 2010 ProjectCreating a SharePoint 2010 Project Creating a Feature Event ReceiverCreating a Feature Event Receiver Deploying and Debugging SharePoint Projects Deploying and Debugging SharePoint Projects Creating, Deploying and Testing Web PartsCreating, Deploying and Testing Web Parts Creating a Visual Web Part with AJAX BehaviorCreating a Visual Web Part with AJAX Behavior

Estimated time to complete this lab: 45 minutes.

Page 3

System Requirements
You must have the following items to complete this lab: y y y y Microsoft Visual Studio 2010 Beta 2 Internet Information Server 7.0 Microsoft SharePoint Server 2010 Beta Microsoft SharePoint Server 2010 Beta Developer Tools Note: You can follow theSet up the Development Environment for SharePoint Serverarticle in order to get instruction to install SharePoint Server appropiatelly.

Setup
All the requisites for this lab are verified using theConfiguration Wizard. To make sure that everything is correctly configured, follow these steps. Note: To perform the setup steps you need to run the scripts in a command window with administrator privileges.

1. Run the Configuration Wizard for the Training Kit if you have not done it previously. To do this, run the CheckDependencies.cmd script located under the Setup folder of this lab. Install any pre-requisites that are missing (rescanning if necessary) and complete the wizard . Note: The Configuration Wizard will setup a new blank site collection at the locati n o http://localhost/sites/SharePointToolsLab. This is the site you will use to test and debug the code you are going to write with the Visual Studio 2010 SharePoint Tools.If you want to change the site collection location, modify the SetupSiteCollection.ps1in the Setup\scripts\tasks folder of this lab.

Comment [ZN1]: Put your computer name here NOT localhost Comment [ZN2]: Your URL will most likely not have this Comment [ZN3]: Don¶t bother the script won¶t work anyway. It¶s easier to just create your own blank site on your own.

Starting Materials
This Hands-On Lab includes the following starting materials. y Each exercise is accompanied by a starting solution you can find in the Begin folder of each exercise. Some code sections are missing from these solutions, which will be completed through each exercise. Therefore the starting solutions will not work if you run them directly.

Page 4

y

Inside each exercise you will also find anEnd folder containing the resulting solution you should obtain after completing the exercises. You can use this solution as a guide if you need additional help working through the exercises. Each exercise contains a Visual Basic and a C# version; Inside the End/Begin solution folder you will find two folders: VB, containing the Visual Basic version of the exercise, and C#, containing the C# version of it.

y

Next Step
Exercise 1: Using HTML Code Snippets in Visual Studio 2010 Exercise 1: Using HTML Code Snippets in Visual Studio 2010

Page 5

Exerc se 1: Creat ng a SharePo nt 2010 ProjectExerc se 1: Creat ng a SharePo nt 2010 Project
I t e f rst exerc se y create a e ty r ect a f c s t e as ects f t e s a St S areP t T s t at are c acr ss a r ects create t t s t set. st f y r rk v ve c a g g t e r ert es f t e r ect a r ert es f t e r ect's a feat re .

I t s task y zar a cat

ver fy t at a e

ty S areP

t S te

ect

as creae t

s gt e

f g rat

.

av gate t t e t - eve s te at 1. La c t e I ter et Ex rer a htt //localhost/sites/ Share o i tToolsLa Y s serve t at t e e y -create s te s a a k s te. T s s t e s te y se t est a t e g t e r ect y eve t r g t t s e t re a exerc se.

Page 6

CB D C B D R B E P P F 



!  & 

F EE PI CB EI H D 

! '

D

B C EE PI CB SB R D CG F FH P A @ 9 GB F EC BD C B 432 6 3 324 1 4 6 0 50

" 

## &   



%$ 

P G E D P PD 

0  

0 1 1 0) 

  #%% ' (    # # " !  

Task 1

avigati g the ew Site Collectio

¥  ¢ ¨  §§ ¢ ¦ ¤ ¦ ¥ ¤ ¤ ¤ ¤ ¢ ¥ § ¥ ¢  ¡ ¤ 

¤ © ¡ ¤ ¢ ©¤ ©   ¤ © ¡ ¤ ¢ ©¤ © ¡   ¢   ¡ §¤   ¢ ¤ © § § ¤  ¤ ¨¨¤ ¡ §¤¤   ¢¤ ¡ §¤¤ ¢¡ ¡¢ ¦  £ © ¤ © © ¨   ¢ ¢ ¡   ¡   ¤ ¥ ¤   §§¢¦ ¥¤ P H PD H EQ 87 P

2010

Figure 112 SharePoint Blank Site Collection Note:If you haven t already done so, run the Configuration Wizard for the Labto create the new site collection that will be used to test and debug the code you will be writing in this lab. Remember to change the site URL if you modified it in the setup scripts. Task 2 Creating a Ne

In this task, you will use the templates included in Visual Studio 2010 Beta 2 to create an Empty SharePoint project. 1. Open Microsoft Visual Studio 2010 from Start | All Programs | Microsoft Visual Studio 2010 | Microsoft Visual Studio 2010. 2. On the File menu, point to Ne , and click Project. 3. In the Ne Project dialog box make sure that .NET Frame ork 3.5is selectedandselect either Visual C# or Visual Basic, then selectSharePoint 2010 in the installed Templates listand theEmpty SharePoint Project type. You may set the location to the Source\Ex01CreatingSharePointProject\begin (choosing the folder that matches the language of your preference) which is the provided folderfor this lab. Note: .Net Framework 4.0 is currently not supported by SharePoint 2010

4. Change the Name to ContosoWebParts and click OK.

Page 7

V

U

T

SharePoint Project

V

re

t r ject ( #)

d

a ` c ba` YX

Fig re 223 New Empty S

W

Page 8

re

t r ject (V )

Comment [

get er demos!!!

Page 9

—™ ie i —h g–—™e – ™ –ed ™ ˜ —™ ˜ —– ˜ •”

ggef —™ ˜

izar r ts y f r a ca e gg g s te e ter 5. Whe the Share o i t C sto i zatio htt //localhost/sites/Share o i tToolsLa a cha ge the tr st eve t e y as a far s t a the c ck F sh .

‚ ˆ ‰ ‡

„€ “  „ „ ƒ ˆ ‡ ƒ† … „  „  ƒ 

ˆ …ˆ ’ € ‚ €y

x

u

u t w

r

‡ˆ ‡

i h q pih gf v u t ‡„ ˆ

Fig re 334 New Empty S

…ˆ ˆ  ‡ ƒ „ ‘

s

e

4 ]: Make

re r ed

d t r

r

W z rd

Note Sa xe s t has certa restr ct s s ch as e g a e t access f esyste eve r g e y e t.The e y e t f S f es s t a e a sa xs t s ce y r r ect c ta a ser c tr y ee t create a far s t F. r re f r at Sa xe s t s ease v s t htt / / s . cr s ft.c /e s/ agaz e/ee335711.as x

r ect has een create y should e a le to observe t has four nodes 6. Once the ne Pro erties, Refere ces, Feat res and Package. While the first t o nodes are standard on all isual Studio rojects, the Features node and the Package node are unique to rojects create ith the isual Studio 2010 SharePoint Tools .

‚ ‚ s {u u u y{ s yy w| v{ | u{ usuy xwu { u v s xu zwu su z su y x sy v €u ww us y wy  ~ } u s { w u ut v s z x z su y y { u wt sx sy t wy

Page 10

Œ

’

‹



‡

‡

Š… ‰ˆ

| sy { x suy xwu v utvs su su y { u s y x sy su w wy € sy u | xu u s { u w| v s y xv s w| v sy su y x wu v uts r

lo 

‡

pno l o n Ž

Fig re 445 S re t ust m z t

†… „ ƒ

’

q ponm lk j ‘ 



‘

structure ( #)

structure (V )

In this task, you ill add a ne Feature to your roject

hich is a core ele ent to all SharePoint roject.

1. Add a ne feature to the roject. To do this, right click on theFeat res node and select the Feat re option.

Page 11

° °¯

ª

®

«

©

ª

­

© ¨

§

¬

©

§

Task 3

i g a ew Feat re

¤

¢  ¡ £  

Fig re667 S re t r ject s ut

›

™— ˜ š —

Fig re556 S re t r ject s ut

— – ™˜—– •” “   Ÿ ¢¡ Ÿ ž œ ®

¦ ¦¥

Fig re 778 Add New Fe ture ( #)

Fig re 889 Add New Fe ture (V )

Page 12

Â

ÆÃ

ÅÅÇ Ã ÃÄ Á

À¿

»

¾

½ ¼ »

¹

º

¸

·

2.

ena e the recently created feature to a in. To do this, ir ghtclick on the node for the default feature added na ed Feat re1and click Re a e. ena e this feature to Mai .

³

² µ

¸

± ´

5 ]: Just eed to rename t e automat ally topmost node and t rename .feature and . emplate.xml Comment [

Note If you are following the lab using the # version, there is currently a bug that won t allow you to rena e the feature if you have a # sy bol in the path. (for exa ple \C#\) E As a workaround, copy your solution to another folder and you willthen be able to rena e the feature.

3. Open the Mai feature in the feature designer. s e the feature designer to change the feature s Title, escri tio and Sco eusing the following values

Description: My very first roject si g th Vis al St e Scope: Site Save yo r cha ges

Fig re 9910 Fe ture Des g er

Page 13

Ø Ú

Ø

Ù Ø

×

Ö

Ü

Ô

Title C sto

e Parts io 2010 Tools

Ê

Ë Ì

Ê

Ñ

Ê Î

É

Ð

Õ

Í

Û

Ó Ò

Í

ß Þ

Ê

Ð

Ï

È

Ý Û

Note AScope setting of e results in site-level activation of the feature while aScope setting of Site results in activation at the site collection level. The change of the feature's Scope setting to Site is required due to the fact that Web Parts deploy ent requires a feature which activates at site collection scope in order to properly deploy Web Part de scription files. Task 4 i g I ages to Yo r P roject

In this task, you will add a few images into your project so they are deployed inside the SharePoint Images folder. To do this, proceed as follows: and choose the 1. In the Solution Explorer, rightclick the Co toso e P arts project, point to SharePoi t "I ages" Ma e Fol ercommand to add an Images mapped folder to your project.

Fig re 101011 Add S re t Im ges M pped F der ( #)

Page 14

í íì

ã

ë

ê

ø

é

÷ô

í

í

â

ò

ïï

á

è

ò

î

ö õôó òñ

ç æ

é

à

å åä ð

Fig re 111112 Add S re t Im ges M pped F der (V )
¡  

2. You will now see that there is an I ages irectory inside your project. Also, you will find a child folder inside it, with the same name as the project Co toso e P arts.
¦ ¥ ¤ ¢

Fig re 121213 S re t Im ges F der ( #) 
 ©    § ©¨

Page 15

£

ý

û

û

ÿ þýü ûú

ù

Fig re 131314 S re t Im ges F der (V )
$ #  "!   

There is also a Packaging Explorer that you will probably see on the left -hand side as well. OTE: y images are from a project with a different name but otherwise it is identical to the lab project. Note SharePoint Tools helps to ensure best practices with SharePoint development. When adding image files to your project,you should not add them directly inside the Images folder. Instead, add them to the inner directory in this case named toso e Partsto avoid file Co name conflicts with the imagedeployed by SharePoint in theImages directory.
0 ) ( ' & %

3. Next, you will add the images to the site s images folder. To do this, right-click on the Co toso e P artsfolder under the I ages folder, point to / Existi g Ite . In the Add Existing Item dialog, browse toSo rce\ ssets folder and select all three GIF files in the folder. FeatureIcon.gif SiteIcon.gif WebPartIcon.gif. Page 16
4 1 6 65 5 4 7 3 2 1

4. The first GIF file that you will put to use is the Feat reIco .gifby modifying the Image rl property of the Mai feature. To do this, a. Open the Mai feature in the feature designer and make sure it is the active window. b. Press F4to openthe Properties Window. Page 17
Y X W V W

H

re

t Im ges F der (V )

U

TI

S R IQ

HP

Fig re 151516 Im ges dded t t e S
P I H G H

9

re

t Im ges F der ( #)

F

E@

D C @B

9A

Fig re 141415 Im ges dded t t e S
A @ 9 8 9

Exerc se 2: Feature Event Rece verExerc se 2: Feature Event Rece ver
In the previous exercise, you learned how to modify the project properties and features properties using visual designers and property sheets.

Page 18

q

pi

Note The Image
h

g

Fig re 161617 Fe ture Im ge Ur
f d f

L is relative to the I agesmappedfolder.

e

d

cb

a

`

c.

pdate the I age Url property with an

L pointing to the Feat reIco .gifimage.

In this exercise, you willadd some code. Over the next few steps, you are going to add a feature receiver so you can write code against t SharePoint object model that willbe automatically executed during he feature activation and feature deactivation .
t u  t

Task 1

In this task, you will an event receiver class to your feature in order to react to the event generated with configuring your SharePoint site collection features. 1. Open icrosoft isual Studio 2010 fromStart | ll Progra s | Microsoft Vis al St Microsoft Vis al St io 2010 .
€ … y ‚ „ ƒ ‚ €  € v €  x w

Fig re 171718 Add Eve t Rece ver ( #)
‘ ‰ ˆ

Page 19

”

3. In the Solution Explorer, rightclick on the ain feature node, and chooseAdd Eve t Receiver, toadd an event receiver to the selected feature.
‡ †

•

”

•

•”

•

“’

2. Open the solution fileCo toso e Parts.sl located under the So rce\Ex02Feat reEve tReceiver\ egi \(choosing the folder that matches the language of your preference.)Alternatively, you may continue working with the solution obtained after completing the previous exercise
‚ „ ‚ …

”

”

•

s sr

i g a Feat re Eve t Receiver

io 2010 |

6 ]: I suggest t s pat as t s t e one I ave tested and t s a natural one for maintaining t e flow of your lecture Comment [

Fig re 181819 Add Eve t Rece ver (V )
™ ˜ — –

Task 2 Addi g Functionality to the Event Receiver In this task, you will implement theFeatureActivated and Feature eactivatingmethods to change the Title and Image L of the top -level site. 1. Implement the FeatureActivatedmethod, to do this, proceed as follows: Note efore changingtheTitle property, your code should track its original value so that it can be restored upon feature deactivation .
i h e gf d

a. In the Solution Explorer, double -click on the Main.EventReceiver.cs (C#) class fileunder the Main Feature node. In , click on the Main feature and press F7 to open theCode View
k j

Page 20

Figure 191920 M .Eve tRece ver.csf e ( #)
p om m n n ml

b. Locate the definition of theFeatureActivated method Note The definition is the first comment inside the MainEventReceiver class.
q

c. Replace the commented definition with the following code: (Code Snippet - SharePoint Tools Lab FeatureActivated Properties CSharp) C# publicoverridevoidFeatureActivated(SPFeatureReceiverProperties properties) { SPSitesiteCollection = properties.Feature.ParentasSPSite; if (siteCollection != null) { // save top site's original Title and SiteLogoUrl SPWeb site = siteCollection.RootWeb; site.Properties["OriginalTitle"] = site.Title; site.Properties.Update(); // update the Title and SiteIconUrl site.Title = "VS 2010 SPT Rocks"; site.SiteLogoUrl = "_layouts/images/ ContosoWebParts/SiteIcon.gif"; site.Update(); }

Comment [ 7 ]: Change this to your project name or get urned!

Page 21

y

z

S ACES I
y

xv

u

u sr

Comment [

8 ]: WA CH HE A H!!

wv u

t

u

sr

F

}

(Code Snippet - SharePoint Tools Lab FeatureActivated Properties VB) Visual Basic
PublicOverridesSubFeatureActivated(ByVal properties AsSPFeatureReceiverProperties) DimsiteCollection = TryCast(properties.Feature.Parent, SPSite) IfsiteCollectionIsNotNothingThen ' save top site's original Title and SiteLogoUrl Dim site = siteCollection.RootWeb site.Properties("OriginalTitle") = site.Title site.Properties.Update() ' update the Title and SiteIconUrl site.Title = "VS 2010 SPT Rocks" site.SiteLogoUrl = "_layouts/images/ContosoWebParts/SiteIcon.gif" site.Update() EndIf EndSub

Comment [ZN9]: Chan e this to your project name or et burne !
‚ 

Note: The code above first obtains SPWeb reference to the top-level from the SPSite to get the Title s property current value. It stores the value as a name/value pair inside the SPWeb.Properties collection and then Modifies it to the new value VS 2010 SPT ocks . Finally, it changes the SiteLogoUrlproperty to point to SiteIcon.gif inside the Images folder.
{

Note:You should also be able to see that there are several method stubs inside the class definition that are commented out. There is also a GUID attribute that has been applied to the receiver class to give a unique identifier. Do not remove the GUID f om the class because it will r be used behind the scenes by the SPT during the packaging process.

2. Implement FeatureDeactivating so that your code restores the original Title property value and changes the SiteLogoUrl property value back to an empty string. (Code Snippet - SharePoint Tool Lab Feat re eactivatin Pro ertie CShar ) C#
publicoverridevoidFeatureDeactivating(SPFeatureReceiverProperties properties) { SPSitesiteCollection = properties.Feature.Parent asSPSite;
€ | €  } | ~

Page 22



if (siteCollection != null) { // restore top site's original Title and SiteLogoUrl SPWeb site = siteCollection.RootWeb; site.Title = site.Properties["OriginalTitle"]; site.SiteLogoUrl = string.Empty; site.Update(); } }

Visual Basic
PublicOverridesSubFeatureDeactivating(ByVal properties AsSPFeatureReceiverProperties) DimsiteCollection = TryCast(properties.Feature.Parent, SPSite) IfsiteCollectionIsNotNothingThen ' restore top site's original Title and SiteLogoUrl Dim site = siteCollection.RootWeb site.Title = site.Properties("OriginalTitle") site.SiteLogoUrl = String.Empty site.Update() EndIf EndSub

Exercise 3: Depl yi g a d Deb ggi g S are i t r ectsExercise 3: Depl yi g a d Deb ggi g S are i t r ects
In this exercise, you will test the work done so far and see how your project behaves when tested inside a SharePoint site. Also, you will debug your code using Visual Studio 2010 debugger. Task 1 Configuring and Deploying a SharePoint Project. In this task, you will configure the project properties previous to deploy the SharePoint project to the SharePoint Server.

Page 23

ˆ

ƒ

(Code Snippet - SharePoint Tool Lab Feat re eactivatin Pro ertie
‡ † „ ƒ

…

B)

| 1. Open icrosoft isual Studio 2010 fromStart | All Progra s | Microsoft Visual Studio 2010 Microsoft Visual Studio 2010 . 2. Open the solution fileContoso e Parts.sln located under the Source\Ex03\ ConfiguringAndDe u gging egin\(choosing the folder that matches the language of your preference.)Alternatively, you may continue working with thesolution obtained after completing the previous exercise . 3. Right-click on the ContosoWebParts project node in the Solution Explorer and click Properties . 4. Navigate to the SharePoint tab to see the project deployment options. 5. Note that there are two text boxe that allow you to add command s -line instructions which will execute either just before and directly after the SPT deploy steps are processed. You are not going to add anything to either of the two top text boxes. 6. Find the combo box control with the capti Active Deployment Configuration and change the on selected item from Default toNo Activation.
   ‹ Œ ‰

Figure 202021 S re t r ject r pert es
’ ‘  ‘  “ ’‘  Ž

Š

Page 24

7. Inside the Edit Configurationslist box, select theNo Activation configuration and click t he View button to see its deployment configuration steps. 8. Click OK to close the iew Deployment Configuration dialog. Save all your work and close the page which shows the project properties .
”

Figure 212122 No Act v t on Dep oyment Conf gur t on
• – • — • – •

9. Now it's time to run the Deploy command. First, make sure the Output Window is visible so you can see how the things progress during the execution of the Deploy command. Then right -click on the ContosoWebParts project in Solution Explorer nd run the project Deploy command. a

Page 25

Figure 222223 Dep oy S re oint Project (C#)
› š™ ž ˜ œ

Figure 232324 Dep oy S rePoint Project (C#)

steps that 10. Examine the Output Window after the Deploy command has completed. erify the provided output to the Output windows.

Page 26

Ÿ

Figure 242425 Successfu Dep oy Output window
   

11. At this point, the solution package for the Contoso e P artsproject has been deployed on the local SharePoint. Let's test out your work by trying to activate the feature you defined inside the ContosoWebParts project. a. Open Internet Explorer, and browseto the test site at htt //localhost/sites/SharePointToolsLa .
¥ ¤£ ¢

Page 27

¡

b. Click Site Actions - Site Settings to navigate to the Site Settings page.

c. Inside the Site Collection Administration section of theSite Settings page, click on Go to top level site settings then click on the Site collection features link to navigate to the Site Collection Administration > Features page.

Page 28

d. Locate the feature you have been working on with a title of ContosoWebParts. You should also be able to see the feature's custom feature icon.

12. Activate the Contoso Web Parts feature. If you return to the site's home page you should be able to verify that the code inside the FeatureActivated event handler executed and changed the site's title and its site icon.

Page 29

¨

§¦

Figure 252526 SharePoint Site Collection A

ini tration

Figure 262627 S rePoint Fe ture Activ ted
ª ª ª© ®­

13. Navigate back to the Site Collection Administration for Features page, and deactivate the Contoso e Parts feature so that you can test the code in theFeatureDeactivatingevent handler. Return to the site's home page and verify that the site title has been restored to its original value and that the site icon has been changed back to the default site icon for SharePoint sites.
¬ «

Figure 272728 S rePoint Fe ture De ctiv ted
® ® ®

Task 2 De u gging SharePoint Feature U sing Visual Studio 2010 enter in debug mode so that you can single step through In this task, you will use isual Studio 2010 to the code while it's executing inside the context of the test site. 1. Open the source Main Event Receiver in Code View by pressing F7 with the Main Feature selected, and add a breakpoint toFeatureActivated. Page 30
° ¯

Figure 282829 Fe tureActiv ted Bre kpoint (C#)
± ² ± ² ± ²

Figure 292930 Fe tureActiv ted Bre kpoint (VB)

2. Start the project in debug mode by run ning De u g \ Start De u gging menu command or pressing the equivalent shortcut key which isF5.
³ ³

Page 31

Click OK at this dialog 3. After running the Start Debugging command wait until the isual Studio debugger has launched the Internet Explorer and navigated to the test site. 4. Within the test site, navigate to theSite Collection Administration > Features page and activate the Contoso e Parts feature. Note At this point, isual Studio should come into focus,and break at the line where you set the breakpoint. If this does not occur,try deactivating and reactivatingthe feature again.
· ¸ ¶ µ ´

Comment [ 0 ]: Just repeat step ³c´ above figure 26 just like you did before
½¼ »

Figure 303031 De ugging Fe tureActiv ted (C#)
º º ¹

Page 32

Figure 313132 De ugging Fe tureActiv ted (VB )
¿ ¿ ¾

5. Press the F11 key to single-step through the remaining lines of code. You should be able to hit uishes control back to the Internet F11 repeatedly until the isual Studio debugger relinq Explorer. 6. Return to isual Studio and stop the debugger by running the u g \ Sto De u gging menu De command or by pressing the equivalent sh ortcut key which isShift+F5. 6.7. Delete the breakpoint you set
 à  À Á

Exerc se 4: Creat ng, e loy ng an Test ng We PartsExerc se 4: Creat ng, e loy ng an Test ng We Parts
In this exercise, you will add a customWeb Part to your project. Task 1 Adding a new We Part In this task, you willadd a Web Part to your project . 1. Open icrosoft isual Studio 2010 fromStart | All Programs | Microsoft Visual Studio 2010 | Microsoft Visual Studio 2010 .
Å Æ Ä

Page 33

2. Open the solution fileContosoWe Parts.sln located under the Source\Ex04We P arts\ egin\(choosing the folder that matches the languag of your e preference.)Alternatively, you may continue working with the solution obtained after completing the previous exercise. 3. In the Solution Explorer, rightclick on the ContosoWe P artsproject, point to Add and select New Item 4. Select the We Part project item template and give it a name ofHelloWe Part.
É É È Ç Ç Ç

Figure 323233 New We Part item (C#)
Ê

Page 34

Figure 333334 New We Part item (VB)
Ë

5. Inspect the SharePoint Project Itemnode for the Web Part namedHelloWe Part. You should be able to verify that it contains threeSharePoint Project Itemfiles named Elements.xml, . HelloWe P art.csand HelloWe P art.we art
Ì ÍÌ Ì Ì

Page 35

Figure 343435 Inspecting He oWe Part e ement(C#)
Î Ð Ï Ñ ÎÎ ÐÐ

Figure 353536 Inspecting He oWe Part e ement (VB)

- Elements.xml contains the definition of the elements that form the web part
ÔÓ

- HelloWe P art.we
Ó

Ò

Note

artis an xml file containing metadata that describes the webpart Page 36

- HelloWebPart.csorHelloWebPart.vb contains the code required to implement the web part s functionality.

6. In the Solution Explorer, double-click on the HelloWebPart. ebpartfile to open it, and perform the following changes: a. Find the XML element for the Title property and change its value to:The "Hello" Web Part. b. Find the XML element for the Description property and change its value to:A most compelling Web Part. c. Add the following properties after the recently modified decription property.
Ø × Ù Ø ×× Õ

(Co e Sni XML

Comment [ZN11]: Chan e this to your project name Comment [ZN12]: Chan e this to your project name
Ú

7. In the Solution Explorer, double-click on the Elements.xmlfile to open it. 8. Modify the URL attribute of theFileXML element, to ensure that the web part name is unique. To do this,addthe text value of "ContosoWebParts_" to the beginning of the URL property value. XML
<?xmlversion="1.0" encoding="utf-8"?> <Elementsxmlns="http://schemas.microsoft.com/sharepoint/" > <ModuleName="HelloWebPart" List="113" Url="_catalogs/wp"> <FilePath="HelloWebPart\HelloWebPart.webpart" Url="ContosoWebParts_HelloWebPart.webpart" Type="GhostableInLibrary"> <PropertyName="Group" Value="Custom" /> </File>

Comment [ZN13]: Or your project name

9. Change the value for the Group property to "Contoso Web Parts". XML
<?xmlversion="1.0" encoding="utf-8"?> <Elementsxmlns="http://schemas.microsoft.com/sharepoint/" > <ModuleName="HelloWebPart" List="113" Url="_catalogs/wp">

Page 37

Ú

<propertyname="ChromeType" type="chrometype">TitleAndBorder</property> <propertyname="CatalogIconImageUrl" type="string">_layouts/images/ContosoWebParts/WebPartIcon.gif</property> <propertyname="TitleIconImageUrl" type="string">_layouts/images/ContosoWebParts/WebPartIcon.gif</property>

Ö

et - SharePoint Tool Lab Hello ebPart Pro ertie )

<FilePath="HelloWebPart\HelloWebPart.webpart" Url="ContosoWebParts_HelloWebPart.webpart" Type="GhostableInLibrary"> <PropertyName="Group" Value="Contoso Web Parts" /> </File>

Finally, open the source file named HelloWebPart.cs (C#) or HelloWebPart.vb (VB), and replace the class definition with the following code.
Ü ÝÝ áá Þ â Ý á ÜÜ àà

(Co e Sni C#

[ToolboxItemAttribute(false)] public class HelloWebPart : WebPart { publicHelloWebPart() { } protectedLabeloutputLabel; protectedoverridevoidCreateChildControls() { outputLabel = newLabel(); outputLabel.Text = "Hello Web Part"; Controls.Add(outputLabel); } protectedoverridevoidRenderContents(HtmlTextWriter writer) { base.RenderContents(writer); } }

Visual Basic
<ToolboxItemAttribute(False)> _ PublicClassHelloWebPart InheritsWebPart PublicSubNew() EndSub ProtectedoutputLabelAs Label ProtectedOverridesSubCreateChildControls()

Page 38

ã

(Co e Sni

Û ß

et - SharePoint Tool Lab Hello ebPartCla

CShar )

et - SharePoint Tool Lab Hello ebPartCla

B)

outputLabel = New Label() outputLabel.Text = "Hello Web Part" Controls.Add(outputLabel) EndSub ProtectedOverridesSubRenderContents(ByVal writer AsSystem.Web.UI.HtmlTextWriter) MyBase.RenderContents(writer) EndSub EndClass

10. Press CTRL+SHIFT+B to build the solution Exercise 4: Verification 1. Run theRight click on your project in Solution Explorer and c lickDeploycommand which will retract the previously deployed solutionand will deploy the updated solution package. 2. Open Internet Explorer, and browse to http://localhost/sites/SharePointToolsLab . Follow these steps to go through the activation process. a. Click Site Actions \ Site Settings to navigate to the Site Settings page. b. Inside the Site Collection Administration section of the Site Settings page, click on the Site collection features link to navigate to the Site Collection Administration > Features page.
å æ ä

c. Locate the Contoso Web Partsand activate it. Note:If it was already active, then deactivate first and then activate it. The key point here is that feature activation is what provisions the .webpart file into the Web Part Gallery which will allow you to test your work.

Comment [ZN1 ]: This is totally wron when I ran it. ctivate the feature by the name you use in e ercise 3.
è ç

3. Add a test instance of the Web Part you have just created to a Web Part Page.To do this: a. Navigate to the home pagehttp://localhost/sites/SharePointToolsLab . The ribbon at the top of the page should have a tab titledPage.

b. Click on the Page tab and then select the command from the Edit Page button that takes you into the mode for adding, modifying and deleting Web Parts from the page.

Page 39

Figure 363637 T e Edit Page button
é

c. Click on the Add a Web Part link ormake sure the Left Web Part zone is selected (indicated by a different blue color in the left zone and use the contextual Page Tools ) ribbon tab. d. Click on the Insert tab on the ribbon and click on theWe Part button.
ê

Figure 373738 Insert a new Web Part

Note At this point you should see the new SharePoint 2010 I for adding new Web Parts to a page. You should be able tobrowse through the standard Web Part Categories such as Lists and Libraries, Authoring and Content Rollup. You should also
ì ë

Page 40

be able to see a new custom category named Contoso Web Parts which you created when you edited the Group property value inside the elements.xml file.

e. Select the Contoso We Partscategory in the left-hand section. In the right-hand section, click on your web part, namedThe "Hello" We Part
î

f.

Make sure the drop-down box with the Add We Part toname,has the Leftvalue, and click the Add button to add the Web Part instance to the page .

Figure 383839 Se ect a new Web Part to add
ï

4. At this point, you have gone through all the required steps to create, deploy and test a Web Part. The test instance of your Web Part should look like the following screenshot .

Figure 393940

Page 41

í

í

Web Part in erte in Ho e a e
ô ó ò ð

Click on Stop Editing to see the Web Part go live and you are done NOTE: I haven t tested Exercise 5 and my notes end here. If you want to do the last exercise be aware it may take a while to do and you will probably need to cut some of the other d emos short to fit it in.

Exercise 5: reati g a Vis al eb art wit AJAX Be avi rExercise 5: reati g a Vis al eb art wit AJAX Be avi r
In this exercise, you will add a second Web Part using the Visual Web Part template.This template, allows you to create the UI for a Web Part using an ASP.NET User Control and the Visual Studio User Control Designer. You will also use the UpdatePanel control from ASP.NET AJAX to give your Web Part a Web 2.0 user experience eliminating postbacks. Task 1 Adding a Visual Web Part In this task, you will use the Visual Web Part template to create a new SharePoint Project Item in the project. 1. Open Microsoft Visual Studio 2010 from Start | All Programs | Microsoft Visual Studio 2010 | Microsoft Visual Studio 2010. 2. Open the solution file ContosoWebParts.sln located under the Source\Ex05AjaxVisualWebParts\begin\(choosing the folder that matches the language of your preference.)Alternatively, you may continue working with the solution obtained after completing the previous exercise. 3. Add a new Web Part to the ContosoWebParts project named ListInspector. To do this,
õ

a. Right-click on the ContoWebParts project in Solution Explorer and select Add \ Ne Item.

b. Select the Visual Web Part project item template and give it a na of ListInspector. me

ñ

Formatted: pp Body Text Indent, Indent: Left: 0" Formatted: pp Body Text, Outline numbered + Level: 1 + Aligned at: 0" + Indent at: 0"

Page 42

Figure 404041 Adding a new Visual Web Part (C#)

Page 43

Figure 414142 Adding a new Visual Web Part (VB)

4. Inspect the SharePoint Project Itemnode for the Web Part named ListInspector. erify that it contains the SharePoint Project Item files named Elements.xml, ListInspector.cs, ListInspector.webpart, ListInspector serControl.ascx and ListInspector serControl.ascx.cs .
÷ ÷

Figure 424243

Page 44

ö

Visual Web Part node structure(C#)

Figure 434344 Visual Web Part node structure (VB)

Note The structure of the isual Web Part is similar to the Web Part. Additionally, it includes a user control (ListIns ectorUserContro.ascx which allows the developer to create a rich I. )
û ú ø

5. Open the Web Part Description file named ListIns ector.we P art and examine the ML , content inside. You should see the ML already contains two property elements for the Title property and the Description property. 6. Replace the <data> element of the Web Part Description with the following content . (Code Snippet - S arePoint Tools Lab ListInspector Description ) XML <?xmlversion="1.0" encoding="utf-8"?> <webParts> <webPartxmlns="http://schemas.microsoft.com/WebPart/v3"> <metaData> <typename="ContosoWebParts.ListInspector.ListInspector, $SharePoint.Project.AssemblyFullName$" /> <importErrorMessage>$Resources:core,ImportErrorMessage;</ importErrorMessage> </metaData> <data> <properties> <propertyname="Title" type="string">ListInspector</property> Page 45
þ ý ü ÿ

ÿ

ù

 

<propertyname="Description" type="string">Web Part which shows all the lists in the current site and allows you to get several of its property values</property> <propertyname="ChromeType" type="chrometype">TitleAndBorder</property> <propertyname="CatalogIconImageUrl" type="string">_layouts/images/ContosoWebParts/WebPartIcon.gif</ property> <propertyname="TitleIconImageUrl" type="string">_layouts/images/ContosoWebParts/WebPartIcon.gif</ property> </properties> </data> </webPart> </webParts>

7. Open the Elements.xml and Modify the URL attribute of File element to ensure that it is unique. Add "ContosoWebPart_" to the beginning of the URL property value. 8. Change the value for the Group property to "Contoso Web Parts". Elements.xml should look as follows: XML
<?xmlversion="1.0" encoding="utf-8"?> <Elementsxmlns="http://schemas.microsoft.com/sharepoint/" > <ModuleName="ListInspector" List="113" Url="_catalogs/wp"> <FilePath="ListInspector\ListInspector.webpart" Url="ContosoWebParts_ListInspector.webpart" Type="GhostableInLibrary" > <PropertyName="Group" Value="Contoso Web Parts" /> </File> </Module> </Elements>

Task 2 Adding Markup to the Web Part In this task you will add the markup necessary to create the elements of the WebPart. 1. Add reference to System.Web.Extensions.To do this: a. In the Solution Explorer, right-click on the ContosoWebPartsproject, and choose Add Reference. b. In the .NET tab, search for the System.Web.Extensions component and click OK Note: This reference is required because developing the new Visual Web Part will involve the UpdatePanel control from ASP.NET AJAX.

Page 46

. 2. In the Solution Explorer, rightclick on the ListIns ectorUserControlascx file and choose iew Designer to open the s er Control in Design mode. Note The designer should be empty at first as no controls or TML text has been added.

3. From the AJAX Extensions section of the Toolbox, d and drop the U d atePanel control onto rag the user control designer. Note You can enable the Toolbox from theView\Tool o x menu

Figure 444445 Ajax Extensions Toolbox

s 4. In the ottom Left of the Designer, Select Source, to witch the s er Control back to code view.

Figure 454546 Switc ing to Source View

Page 47

¢

¦

¥ 

¨

¡

£

©

¤ § 

Note:Note that the User Control designer now contains a reference to the System.Web.Extensions.This is because you added the UpdatePanel control.

ASP.NET
... Inherits="ContosoWebParts.ListInspector.ListInspectorUserControl" %> <asp:UpdatePanelID="UpdatePanel1" runat="server"> </asp:UpdatePanel>

5. Inside the UpdatePanel Element, add a ContentTemplate as shown in the following code block. (Co e Sni ASP.NET
<asp:UpdatePanelID="UpdatePanel1" runat="server"> <ContentTemplate> <tablestyle="width: 100%; border-style: solid; border-color: #CCCCCC; borderwidth: 1px;"> <tr> <tdstyle="width: 180px; vertical-align: top;"> <asp:ListBoxID="lstLists" runat="server" Width="100%" Rows="10" AutoPostBack="true" OnSelectedIndexChanged="lslLists_SelectedIndexChanged"></ asp:ListBox> </td> <tdstyle="width: auto; vertical-align: top;"> <tablestyle="width: 100%;"> <tr> <tdstyle="width: 132px;"> Title </td> <tdstyle="width: auto;"> <asp:LabelID="lblListTitle" runat="server"></asp:Label> </td> </tr> <tr> <td> ID: </td> <td> <asp:LabelID="lblListID" runat="server"></asp:Label> </td> </tr> <tr> <td>

et - SharePoint Tool Lab Li tIn ectorWebPartContentTe

Page 48      

late)

Document Library: </td> <td> <asp:LabelID="lblListIsDocumentLibrary" runat="server"></asp:Label> </td> </tr> <tr> <td> Hidden: </td> <td> <asp:LabelID="lblListIsHidden" runat="server"></asp:Label> </td> </tr> <tr> <td> Item Count: </td> <tdstyle="margin-left: 40px"> <asp:LabelID="lblListItemCount" runat="server"></asp:Label> </td> </tr> <tr> <td> URL: </td> <tdstyle="margin-left: 40px"> <asp:HyperLinkID="lnkListUrl" runat="server" Target="_blank" /> </td> </tr> </table> </td> </tr> </table> </ContentTemplate> </asp:UpdatePanel>

6. Switch the User Control back into Design view and verify that you can see the table layout .

Page 49

Figure 464647 ListInspector Visual Web Part table layout Task 3 Implementing the We Part In this task, you will add the code needed to implement the web part s functionality. 1. In the Solution Explorer,right-click on ListInspectorUserControl.ascx ndchoose iew Code (F7) a to open its code behind. 2. Add a the following namespace directive: C# usingMicrosoft.SharePoint;

Visual asic ImportsMicrosoft.SharePoint

3. Replace the default class definition with the following: (Code Snippet - S arePoint Tools Lab ListInspectorUserControl Class Definition CS arp ) C# publicpartialclassListInspectorUserControl : UserControl { protectedGuidselectedListId = Guid.Empty; protectedboolupdateListProperties = false; }

Page 50     

Visual Basic
PartialPublicClassListInspectorUserControl InheritsUserControl ProtectedselectedListIdAsGuid = Guid.Empty ProtectedupdateListPropertiesAsBoolean = False EndClass

4. Add a method named lslLists_SelectedIndexChanged (Co e Sni C#
protectedvoidlslLists_SelectedIndexChanged(object sender, EventArgs e) { selectedListId = newGuid(lstLists.SelectedValue); updateListProperties = true; }

et - SharePoint Tool Lab Selecte In exChan e

etho CShar )

Visual Basic
ProtectedSublslLists_SelectedIndexChanged(ByVal sender AsObject, ByVal e AsEventArgs) HandleslstLists.SelectedIndexChanged selectedListId = NewGuid(lstLists.SelectedValue) updateListProperties = True EndSub

Note:TheListInspectorWeb Partwill not work until you add this method implementation This is . because the pre-provided table layout text you pasted,contains a list box named lstLists containing an attribute which attaches it to an event handler named lslLists_SelectedIndexChanged .

5. Add an overridden implementation of theOnPreRender method (Co e Sni C# et - SharePoint Tool Lab OnPre en er etho CShar )

Page 51

6

(Co e Sni

et - SharePoint Tool Lab Selecte In exChan e

etho

B)

%

(Co e Sni

et - SharePoint Tool Lab Li tIn ector

erControl Cla

'

$ "" & 1

8

0& )

51 4

7

A

"#

& &

1 1

7 @

!"

"

" ( 3 9

!! '' 22 88

efinition B)

& 1 7

protected override voidOnPreRender(EventArgs e) { if ((lstLists.SelectedIndex> -1) && (!updateListProperties)) { selectedListId = newGuid(lstLists.SelectedValue); } lstLists.Items.Clear(); SPWeb site = SPContext.Current.Web; foreach (SPList list insite.Lists) { ListItemlistItem = newListItem(list.Title, list.ID.ToString()); lstLists.Items.Add(listItem); } if (selectedListId != Guid.Empty) { lstLists.Items.FindByValue(selectedListId.ToString()).Selected = true; } if (updateListProperties) { SPList list = SPContext.Current.Web.Lists[selectedListId]; lblListTitle.Text = list.Title; lblListID.Text = list.ID.ToString().ToUpper(); lblListIsDocumentLibrary.Text = (list isSPDocumentLibrary).ToString(); lblListIsHidden.Text = list.Hidden.ToString(); lblListItemCount.Text = list.ItemCount.ToString(); lnkListUrl.Text = list.DefaultViewUrl; lnkListUrl.NavigateUrl = list.DefaultViewUrl; } }

Visual Basic
Protected Overrides Sub OnPreRender(ByVal e As System.EventArgs) If (lstLists.SelectedIndex> -1) AndAlso Not updateListProperties Then selectedListId = New Guid(lstLists.SelectedValue) End If lstLists.Items.Clear() Dim site = SPContext.Current.Web For Each list As SPList In site.Lists Dim listItem = New ListItem(list.Title, list.ID.ToString()) lstLists.Items.Add(listItem) Next

Page 52

G

(Co e Sni

et - SharePoint Tool Lab OnPre en er

etho

B

F

B E

D

CC

B

B)

If Not selectedListId = Guid.Empty Then lstLists.Items.FindByValue(selectedListId.ToString()).Selected = True End If If updateListProperties Then Dim list = SPContext.Current.Web.Lists(selectedListId) lblListTitle.Text = list.Title lblListID.Text = list.ID.ToString().ToUpper() lblListIsDocumentLibrary.Text = (TypeOf list Is SPDocumentLibrary).ToString() lblListIsHidden.Text = list.Hidden.ToString() lblListItemCount.Text = list.ItemCount.ToString() lnkListUrl.Text = list.DefaultViewUrl lnkListUrl.NavigateUrl = list.DefaultViewUrl End If End Sub

Note: The Code above clears the items from the lstLists control and then add a new list item for each SPList item in the current site. When adding ListItem instances to the ListBox control, it uses the list title as the ListItemText and the list's identifying GUID as the ListItem Value If the UpdateListProperties field contains a value of true, then it will update all the Label controls on the right-hand side of the table layout to display p roperties of the selected list.

6. Press CTRL+SHIFT+B to build the Solution Exercise 5: Verification 1. Run the Deploy command which will retract the previously deployed solution and will deploy the updated solution package. 2. Open Internet Explorer, and browse to http://localhost/sites/SharePointToolsLab . Follow these steps to go through the activation process. a. Click Site Actions \ Site Settings to navigate to the Site Settings page. b. Inside the Site Collection Administration section of the Site Settings page, click on the Site collection features link to navigate to the Site Collection Administration > Features page. c. Locate the Contoso Web Parts and activate it. Note: If it was already active, then deactivate first and then activate it. The key point here is that feature activation is what provisions the .webpart file into the Web Part Gallery which will allow you to test your work. Page 53

3. Add a test instance of the Web Part you have just created to a Web Part Page. To do this:

b. Click on the Page tab and then select the command from theEdit Page button that takes you into the mode for adding, modifying and deleting Web Parts from the page.

Figure 474748 T e Edit Page button

c. Click on the Add a Web Part link or make sure the Left Web Part zone is selected (indicated by a different blue color in the left zone) and use the contextual Page Tools ribbon tab. d. Click on the Insert tab on the ribbon and click on theWe Part button.

Figure 484849 Page 54

H

a.

Navigate to the home page http://localhost/sites/SharePointToolsLa . The ribbon at the top of the page should have a tab title Page. d

P

I

Insert a new Web Part

e. Select the Contoso We Partscategory in the left-hand section. In the right-hand section, click on your web part, namedListInspector

Figure 494950 Select a new Web Part to add

4. At this point, you have gone through all the required steps to create, deploy and test a Web Part. The test instance of your Web Part should look like the following screenshot .

Page 55

R

f.

Make sure the drop-down box with the Add We Part toname,has the Leftvalue, and click the Add button to add the Web Part instance to the page.

Q

Figure 505051 Web Part in erte in Ho e a e

S mmary
In this Lab you created your first SharePoint project using Visual Studio 2010 and the SharePoint Developers Tools. You have added your first Feature and added a SharePoint mapped folder to the project. Among other tasks you implemented a Feature Event Receiver, a SharePoint Web Part and a SharePoint Visual Web Part which included basic Ajax capabiliti es. You also learned how to configure a SharePoint project to deploy it to a SharePoint Server installation, and went through the necessary steps to test and debug your developedproject.

W V U

T

S

Page 56

Sign up to vote on this title
UsefulNot useful