Best Practices Todd C Bleeker Chief Software Architect Mindsharp OFC311 Agenda Poll of attendees expertise Define web parts ABCs of web parts Standard SharePoint development lifecycle General web part best practices ID: 158384
Download Presentation The PPT/PDF document "SharePoint Web Part Development" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
Slide1Slide2
SharePoint Web Part DevelopmentBest Practices
Todd C. Bleeker
Chief Software Architect
Mindsharp
OFC311Slide3
AgendaPoll of attendees expertiseDefine web parts: ABCs of web partsStandard SharePoint development lifecycle
General web part best practicesSlide4
Poll: Your ExperienceSlide5
ABCs of Web PartsAppearance
CSS
HTML DOM
Behavior
JavaScript
AJAX
Connections
Content
SharePoint content database
Corporate LOB systems
ExternalSlide6
Standard Development LifecycleSlide7
Standard Development Lifecycle
Plumbing
PackagingSlide8
Choose a library type:Blank libraryClass libraryWeb control libraryVSeWSS librarySTSDEV (Class) library
Other community (
CodePlex
) libraries
Start
with a well-named VS.NET Library
Plumbing
01Slide9
Choose a "Good" NameMeaningfulUnique on the InternetCompanyProject.Contents.PurposeUsed as default:
Solution name
Project name
Folder name
Default assembly name
Default namespace nameSlide10
Start with a Class LibraryA Class Library:Works in all environments, today and tomorrowCan be used consistently for all projects
Supports both
XCopy
and WSP CAB deployment
VSeWSS
1.3 brings significant improvements
Adopt VS.NET 10 for SharePoint dev ASAP
Around the clock housekeeping required:
Add reference to
System.Web
and WSS, if needed
Rename class (auto-
refactor
code)Add required class directives and constructsDo not forget to scope added classesSlide11
Use Consistent Naming ConversionIn the Project Root or Foo folder:
Web Part Class:
Foo
Part
.cs
wpcatalog
folder:
*.
webpart
File:
Foo
Part
.webpart
TEMPLATE\CONTROLTEMPLATES\Custom\ folder:
User Controls:
FooPart
Control
.ascxSlide12
General Project OrganizationUncheck Create directory for solutionProject folders only one level deepSolution project shells for asset projectsAllows for mix and match
Good for source management
wpcatalog folder for *.
webpart
files
wpresources
folder for external resources
script/image/etc folders for embedded resourcesSlide13
.NET Web Part vs. WSS Web Part.NET Web Part
Runs on any website
Future of Web Part development
No cross-page connections
No connecting Web Parts that are not in zones
No client-side connections
SharePoint Web Part
Only runs on WSS sites
Primarily available for backward compatibility
Includes cross-page connections
Allows connecting Web Parts that are not in zones
Supports client-side connectionsSlide14
Inherit from .NET Web PartA .NET Web Part:Works in all environments, today and tomorrow
Used consistently for all Web Part projects
Works in all ASP.NET projects, not just SharePoint
Housekeeping required:
Derive from
System.Web.UI.WebControls.WebParts.WebPartSlide15
CreateChildControlsUse CreateChildControls for UI structureInstantiateInitialize
wIre
-up
Insert (Add)
Initially output
DateTime.Now.ToString
()
Never use Render
Never use
RenderControl
Rarely use
RenderContentsSlide16
Operations should dictate deployment locationWhile GAC rhymes with Flack, Hack, Sack, Smack, Whack, the Web Part must be signed so that they can choose that optionSign the assembly using VS.NETDo not include a password on your SNK filesCompiling will embed a Public Key Token
Sign
or Strong Name the assembly
Plumbing
02Slide17
The GAC Is not CrapFirst place the .NET Framework looksPre-checked for tamperingCan run multiple Version/Culture/PublicKeyToken versions of the same assembly
Always participates in CAS
Always runs under Full Trust (pros and cons)
Cached: Runs a shadow copy of the assembly (No DLL hell)
Application Pool Recycle required to changeSlide18
BIN rhymes with WINConfigured to run under WSS_Minimal TrustNo need to recycle the Application Pool if the assembly is deployed to the bin
Fastest iterative approach
Code
Compile
Refresh
If your signed assembly runs in the BIN,
it will likely run in the GAC,
the opposite is not trueSlide19
Setup Get Public Key OptionTools > External Tools… > Add
Title:
Get &Public Key
VS.NET 2005 Command:
C:\Program Files\
Microsoft Visual Studio 8\SDK\v2.0\Bin\sn.exe
VS.NET 2008 Command:
C:\Program Files\
Microsoft SDKs\Windows\v6.0A\Bin\sn.exe
Arguments:
-Tp "$(TargetPath)"
Select
User Output Window
checkbox
Click the
OK
button to save
Ensure project has focus before runningSlide20
Signing Best PracticesMove SNK to Properties folderInspect/Alter AssemblyInfo ClassChevy Chase Look to eliminate dynamic versioning: Version 1.0.*
Set assembly directive (Yikes!):
System.Security.AllowPartiallyTrustedCallers
()Slide21
SNK Management OptionsDeveloperEach developer has their own keyEmbed the key in VS.NET for development
Delay Signing
Project
Each project has their own key
Do not use development keys in production
All code runs thru gatekeeper for deployment
Setup a half dozen permutations representing common CAS levels that developers can assignSlide22
In addition to the class, *.webpart is requiredUse 12 folder structure to organize projectExposes Web Part to browser user interfaceType and importErrorMessage
required
Title not required
AllowClose
to False
CatalogIconImageUrl
is great polish
Assembly on five lines, Properties on one line
Set
values in the required XML files
Plumbing
03Slide23
Use 12 Hive to Organize ProjectObjectiveA place for everything and everything in its place
Easier to deploy (both
XCopy
and CAB)
Anticipate everyone's placement of
project assets
Supports the creation of large,
complex solutions
Interfaces with community toolsSlide24
XCopy deploy using one of the following:Post-build eventsTargets fileSDK deployment filesUse MakeCab
for creating WSP CAB
Manifest.xml
WSP.ddf
SafeControl
entry in
web.config
required for Web Part assembly
Strike
<Ctrl-Shift-B> to build the solution
Plumbing
04Slide25
CAB Project vs. MakeCab.exeCAB
VS.NET Project Type
Assets from projects can be tagged for inclusion
Can only be used for Web Part projects
Only outputs CAB
No predefined limit
MakeCab.exe
Command line tool
Assets must be identified by name
Used for all projects, including Web Parts
Outputs CAB or WSP
Defaults to 360KSlide26
Post Build vs. TargetsPost Build
Developer environment
Simple: Nine commands
Easy to modify on the fly
Defined in the project file
May need to REM out
before check-in
Targets
Build environment
Complex implementation
Requires planning
Defined in its own file
Rarely modifiedSlide27
XCopy CommandsFor developers, simple commands::: Change directory to the root of the project
cd
"$(
ProjectDir
)"
:: Recycle the application pool
%
systemroot
%\system32\iisapp.vbs /a "
SharePointAppPool
" /r
:: Copy all files from the project's 12 folder to the 12 Hive
xcopy "12" "%
CommonProgramFiles
%\Microsoft Shared\web server extensions\12\" /ys
:: Copy all files from the project's 80 folder to the Web Application directory
xcopy "80" "C:\Inetpub\wwwroot\wss\VirtualDirectories\[80]\" /ysSlide28
XCopy CommandsContinued::: Copy DLLs to the BIN
xcopy "$(TargetDir)*.dll" "C:\Inetpub\wwwroot\wss\VirtualDirectories\[80]\bin\" /ys
:: Install Force DLLs to the GAC (VS.NET 2005)
"%
ProgramFiles
%\Microsoft Visual Studio 8\SDK\v2.0\Bin\
GacUtil.exe" /
nologo
/if "$(
TargetPath
)"
:: Install Force DLLs to the GAC (VS.NET 2008)
"%
ProgramFiles
%\Microsoft SDKs\Windows\v6.0A\Bin\
GacUtil.exe“ /
nologo
/if "$(
TargetPath
)"
:: Create a WSP CAB
MakeCAB
/f "WSP.DDF"Slide29
Install WSPBuilderInstall WSPBuilder into your environment, TODAYSlide30
Plumb the Web Part with a bare bones initial solution (output DateTime for example)New Up the Web PartWeb Application wpcatalog (Solution) vs. Site Collection Web Part Gallery (Solution/Feature)Install/Activate feature
Add the web part to a test page
Slap
the results into SharePoint
Plumbing
05Slide31
Two schools of thought on overriding methodsPage = Proxy MethodsPart = Direct Methods
Update
CreateChildControls
()
Add
OnInit
()
Add
OnLoad
()
Add
OnPreRender
()
Add RenderContents()
Sharpen
the logic and rendering
Sharpen the Logic and Rendering
06Slide32
Web Part Life CycleSlide33
OnInitUse to initialize objects that would live forthe duration of the life cycleSetup connection stringsPage is not yet available
Check for
IsPostback
and
IsCallback
Redirect may force code to
OnPreRenderSlide34
OnLoadQuery the database (asynchronously is ideal)Load DatasetsUse ClientScriptManager to inject external and embedded CSS and JavaScript
Check for
IsPostback
and
IsCallback
Again, redirect may force code to
OnPreRenderSlide35
CreateChildControlsCreate Web Part UI structure as Server ControlFour "Eye"s:Instantiate
Initialize
wIre
-up
Insert (Add)
Create
Visual Web Parts
by moving the UI to a
User Control and use
Page.LoadControl
This method may be called out of sequence using EnsureChildControls()Slide36
User Control vs. Server Control
Factor
User Control
Server Control
Documented in WSS SDK?
Great Intellisense?
WYSIWYG Editing?
Manipulate programmatically?
Organize project using 12 Hive?
Easy to consume in Web Part?
Slide37
User Control vs. Server Control
Factor
User Control
Server Control
Easy for the junior dev?
Can be debugged?
FindControl
unnecessary?
In Custom folder?
More than one can be used/reused?
VS 2008 leverages OOB
csproj
/
vbproj
?
Slide38
Visual Web PartsWhenever possible, move your user interface to a user controlUser Control's code beside and designer classes are compiled into the Web Part's DLLCreate strongly typed variable to the User Control within the Web Part
Create strongly typed variable to the Web Part
within the User ControlSlide39
Add VS.NET Web Item TemplatesAdd the following to your *.csproj file:Add the following to your *.
vbproj
file:
<
ProjectTypeGuids
>{349c5851-65df-11da-9384-00065b846f21};
{
fae04ec0-301f-11d3-bf4b-00c04f79efbc
}</
ProjectTypeGuids
>
<
ProjectTypeGuids
>{349c5851-65df-11da-9384-00065b846f21};
{
f184b08f-c81c-45f6-a57f-5abd9991f28f
}</
ProjectTypeGuids
>Slide40
OnPreRenderLast Opportunity to influence the View State that will be sent to the clientMove OnInit and OnLoad
code to this
event when the
code may be run unnecessarilySlide41
RenderContentsOnly use RenderContents to update user interface for programmatically set propertiesThe base class essentially calls:
EnsureChildControls
RenderChildrenSlide42
Similar to User Access SecurityThis is a matter of TRUSTMost attacks come from withinFor Web Part CAS details, seehttp://tinyurl.com/SharePointCAS
Secure
the assembly using CAS
Secure
the Web Part using CAS
07Slide43
CAS IS NOT HARD
CAS IS NOT HARD
CAS IS NOT HARD
CAS IS NOT HARD
CAS IS NOT HARD
CAS IS NOT HARD
CAS IS NOT HARD
Code Access SecuritySlide44
Code Access SecurityUse CAS, it is not hard, just misunderstoodTest Web Parts using Anonymous and Readers
Add to or create a custom CAS policy;
consider having half a dozen permutations
Deploy CAS using a WSP CABSlide45
Code Access SecurityUse .NET Framework 2.0 Configuration Wizard to generate:SecurityClass
Condition
Permission
Construct
NamedPermissionSet
CodeGroup
Understand the purpose of the
IPermission
SharePointPermissionSlide46
Use community tools like WSPBuilder to generate the Manifest.xml and WSP.ddfALWAYS use a WSP Solution CAB for deployment into productionFor packaging details, see other talks this week
Supply
a Solution deployment Manifest.xml
Packaging
Specify
files to include in a Solution CAB
Store
/Deploy the Solution CAB
08
09
10Slide47
Solution DeploymentAdd a Packaging Project for enterprise projectsFeatureManifest
assumes …\12\TEMPLATE\FEATURE as its root
and gets some files from Feature.xml
SiteDefinitionManifest
assumes …\12\TEMPLATE\
SiteTemplates
as its root
Maximize use of the
RootFiles
tag rather than
TemplateFilesSlide48
Solution DeploymentUtilize the DwpFiles tag for *.
webpart
files
Avoid Web Part Features*
Must be activated by end users on decentralized Site Collections rather than centrally on Web Applications
Orphaned in Web Part Gallery on deactivation
Only way to "group" Web Part in Add dialog
Only way to permission Web Parts
*This is a minority opinionSlide49
Use Web Part PropertiesState Management and PersonalizationFinite Presentation/ValidationString
Integer
DateTime
(but not calendar)
Boolean
Color
Enumeration
Property Builders
Use CategoriesSlide50
Use Editor PartsValidate User InputAbstraction LayerCustom User Interface PresentationPassword
Calendar
Dependant Lists
Data from outside SharePointSlide51
Use Web Part ConnectionsCustom InterfaceIWebPartTableIWebPartRow*
IWebPartCell
IWebPartFilter
Give each connection a unique ID, do not use the default ID called "Default"
Leverage Transformers
*Most TransformableSlide52
Test, Test, Test Web PartsAnonymous and reader usersCode Access Security (CAS)Test connectionsCheck out the details for how to test in these articles:
msdn.microsoft.com/en-us/library/ms916830.aspx
www.21apps.com/agile/
beginners-guide-to-test-driven-web-part-development/Slide53
Other ConsiderationsUse Properties to avoid hard coded valuesUse Web Part Verbs = Embedded functionalityWeb Part Cache - Who doesn’t love cacheCan substantially improve performance
Use for non-volatile, frequently accessed, finite data that can easily fit into memory
Call EnsureChildControls() before manipulating child controls
Customization (shared) vs. Personalization (individual)Slide54
Other ConsiderationsHTMLEncode everything that the user enters when you render it out to prevent script/SQL injection hacksDo not build your entire application in a single Web PartDo build solutions that can be added to SharePoint nearly anywhereSlide55
Want More? Get your SharePoint project OnPath™
with
Mindsharp’s
unique educational approach
http://www.Mindsharp.com/?top=ONPATH
Get Todd’s SharePoint v3 (2007) Developer Training:
http://www.Mindsharp.com/?top=TRAINING
Get Todd’s SharePoint Developer book:
http://www.amazon.com/dp/1584505001Slide56
question & answerSlide57
www.microsoft.com/teched
Sessions On-Demand & Community
http://microsoft.com/technet
Resources for IT Professionals
http://microsoft.com/msdn
Resources for Developers
www.microsoft.com/learning
Microsoft Certification and Training
R
esources
www.microsoft.com/learning
Microsoft Certification & Training Resources
Resources
Required Slide
Speakers,
TechEd 2009 is not producing
a DVD. Please announce that
attendees can
access session
recordings at TechEd Online. Slide58
Track ResourcesSpin the Wheel: Attend SharePoint breakout sessions Mon-Thurs and collect the picture of the day. Come by the booth for a chance to spin the SharePoint wheel. Collect all 4 pictures and enter to win a Microsoft Arc Mouse,
drawing 11:30am
on Friday,
game cards at the booth.
Product Info
http
://www.microsoft.com/SharePoint
Dev Resources
SharePoint MSDN Web Site:
http://msdn.microsoft.com/sharepoint
SharePoint Developer Resources:
http://mssharepointdeveloper.com/
Required Slide
Track PMs
will supply the content for this slide,
which will be inserted during
the final scrub.
SharePoint Conference 2009
www.mssharepointconference.com
ITPro Resources
SharePoint Tech Center:
http://technet.microsoft.com/en-us/office/sharepointserver/
SharePoint Best Practices:
http://technet.microsoft.com/en-us/office/sharepointserver/bb736746.aspx
Slide59
Attend an Interactive Theater Session and enter to win a Microsoft ARC Mouse
Tuesday’s Picture is:
Walk of Fame Star
Attend any SharePoint Breakout Session day 1 – 4 and check the last slide for a daily picture.
Come to the TLC yellow area, SharePoint booths OFC 4 & 5 to spin the wheel for a chance to win a prize. The wheel only spins when the SharePoint spotlight is flashing. One spin per person.
Collect all four daily SharePoint pictures and enter to win a Microsoft ARC Mouse. Game cards can be picked up at the booth.
Drawing for Mice on Friday at the wheel at 11:30AM.
Collect the SharePoint Session Picture of the Day Slide60Slide61
Complete an evaluation on
CommNet
and enter to win!Slide62
©
2009 Microsoft
Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.
The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation.
MICROSOFT
MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.