Tải bản đầy đủ - 0 (trang)
Chapter 8.  Creating Web Parts

Chapter 8.  Creating Web Parts

Tải bản đầy đủ - 0trang

8.1.PreparingtoDevelop

DevelopingawebpartrequiresaccesstotheSharePointDLL,

whichrunsonlyonWindows2003.Therefore,youmustbe

runningWindows2003tododevelopment.Thereareacouple

waystodothisonyourdevelopmentmachine:

UpgradetoWindows2003.

UseRemoteDesktoptoaccessaserverrunningWindows

2003anddoyourdevelopmentthere.

UseMicrosoftVirtualPCtorunWindows2003within

WindowsXPonyourdesktop.

Themainadvantagesanddisadvantagesofeachapproachare

summarizedinTable8-1.

Table8-1.Possiblewebpartdevelopmentapproaches

Approach Advantage



Disadvantage



Upgrade



Bestperformancefordevelopment.



Changingyourdesktop

OSisdisruptive.



Remote

Desktop



Servercanbesharedwithotherdevelopers/testers.



Requiresanadditional

physicalserver.



VirtualPC



Containedonsingledesktop,youcancreate/change

serverconfigurationswithoutaffectingothers.



Performanceis

reduced.



Whicheverapproachyouuse,thereareafewcautionstokeep

inmind.Don'tdeveloponaproductionserver.Doing



developmentrequirestemporarilychangingsecuritysettings

thatmightopenavenuesforattackandrunninguntestedweb

parts(oranycomponent)onanin-serviceserverisnevera

goodidea.Softwarerequirementsandlicensingissuesarethe

sameforphysicalorvirtualPCs.

Thefollowingsectionsexplainhowtousethesedifferent

approachesandhowtoconfiguretheserverfordevelopment.



8.1.1.UsingRemoteDesktop

TouseRemoteDesktoptoaccessadevelopmentserveryou

musthaveanaccountonthatserverandtheservermusthave

remoteaccessenabled.ToenableRemoteDesktopaccessto

theserver:

1. Fromtheserver,chooseControlPanel

Remote.



System



2. SelectAllowuserstoconnectremotelytothiscomputerand

chooseSelectRemoteUsers.

3. Addyouruseraccountandtheaccountsofotherdevelopers

thatwillhaveaccess.ChooseOKtwicetoclosethedialogs.

Then,torunRemoteDesktopfromWindowsXPProfessional:

1. FromtheStartmenu,chooseAllPrograms Accessories

Communications RemoteDesktopConnection.

2. SelecttheservernameandchooseConnect.Remote

Desktopconnectstotheserveranddisplaysthestandard

desktopsign-ondialog.



8.1.2.UsingVirtualPC



TouseVirtualPCtocreateaWindows2003development

environmentforwebparts:

1. InstallVirtualPConyourWindowsXPProfessionaldesktop.

2. InVirtualPC,chooseFile NewVirtualMachineWizard.

Thewizardwalksyouthroughthecreationprocess.Forweb

partdevelopmentyouwillwanttoallocateatleast512MB

ofRAMforthevirtualmachine.

3. StartthenewvirtualmachineandinstallWindows2003.

Thistakesquiteawhile,butitcanruninthebackground

whileyouperformothertasks.

4. ConfigureWindows2003asanApplicationServer.Select

EnableASP.NET,butdon'tselectFrontPage2002Server

Extensionssincetheyaren'tcompatiblewithSharePoint.

5. InstallWindowsSharePointServicesfrom

http://www.microsoft.com/downloads.Thedownloadfile

nameisSTSV2.EXE.Fordevelopmentpurposesitisusually

besttoselecttheTypicalInstallation(WMSDE)option

ratherthanServerFarm(SQLServer).

TheVirtualPCwindowcapturesyourkeyboardandmouse

movementswhileithasfocus.VirtualPCusestheright-handAlt

keyashostkeytoreleasecontrolandswitchbacktothehost

operatingsystem.Table8-2listssomeusefulkeycombinations

forVirtualPC.

Table8-2.VirtualPCkeycombinations

Key



Useto



Hostkey

(rightAlt

key)



Releasevirtualmachine'scontrolofmousepointerandkeyboard.(Useto

movemouseoutofVirtualPCwindowandbacktodesktop.)



Host

key+Delete



SendAlt+Ctrl+Deletetovirtualmachine.



Host+Enter



Switchbetweenfull-screenandwindoweddisplay.



Hostkey+P



Pause/resumevirtualmachine.



Hostkey+R



Resetvirtualmachine.



Hostkey+F4 Closevirtualmachine.

Host

key+down

arrow



Minimizevirtualmachine.



8.1.3.ConfiguringtheServerforDevelopment

RegardlessofhowyourunWindows2003,youmustinstallthe

developmenttoolswithinthatWindows2003serverandchange

somesettingsbeforeyoucandevelopwebparts.

Toinstallthedevelopmenttoolsandconfiguretheserver:

1. InstallVisualStudio.NET2003.Youcancreatewebparts

usingVisualBasic.NETorVisualC#.

2. InstalltheWebPartTemplatesfrom

http://www.microsoft.com/downloads.Thedownloadfile

nameisWebPartTemplatesforVSNetSample2.exe.

3. Optionally,installFrontPage2003.FrontPagemakesit

easiertocreateandmodifytestwebpartpagesin

SharePoint.YoucannoteditSharePointsitesfromVisual

Studio2003.

4. InWindowsExplorer,createarootfolder,suchas



C:\WebParts,foryourwebpartprojects.Creatingthis

foldermakesiteasiertouserequiredcommand-linetools.

5. Copyvsvars32.batfromC:\ProgramFiles\MicrosoftVisual

Studio.NET2003\Common7\ToolstoC:\WebParts.You'll

usevsvars32.battoaccessthecommand-linetools.

6. Adda\binfoldertotheC:\InetPub\wwwrootfolder.Thatis

thelocationwhereyouwillwritewebpartDLLsduring

development.

7. OpentheWeb.configfilefromC:\InetPub\wwwrootand

changethetrustlevelanddebugsettingsasshowninthis

snippet:



...



...











ThewebparttemplatesarewrittentoworkwithVisualStudio.NET

2003.TheydonotworkwithearlierorbetaversionsofVisualStudio.



WhileyouhaveWeb.configopen,takealookattheSafeControls

settingsaswell.You'llneedtoaddaSafeControlelementfor

eachnewwebpartprojectyoucreatelateron.



8.2.CreatingaWebPartProject

Beforeyoucanstartwritingcodeforawebpart,youneedto

setafewthingsupsothatyoucandebugandtestthe

componentfromwithinSharePoint:

1. CreateatestpageinSharePoint.

2. Createandconfigureanewproject.

3. Buildandsigntheassembly;thenextractthetoken.

4. RegisterthewebpartWeb.config.

5. Addthewebparttothetestpagetoverifythateverything

works.

Thefollowingsectionsdescribethesetasksinmoredetail.



8.2.1.CreatingaTestPage

Sincewebpartprojectsareclasslibraries,theyrequirea

contextwithinwhichtorun.Itisagoodideatocreatea

documentlibraryofwebpartpagesonyourdevelopmentserver

fordebuggingand/ortestingpurposes.Usingadocument

libraryhelpsorganizethetestpagesandmakesiteasierto

create/modifythem.

Tocreateatestwebpartpagelibrary:

1. FromSharePointonthedevelopmentserver,chooseCreate

DocumentLibrary.SharePointdisplaystheNew

DocumentLibrarypage.

2. EnterthenameTestPages,selecttheWebPartPage



documenttemplate,andchooseCreate.SharePointcreates

anewdocumentlibrary.

3. ChooseNewDocumenttocreateanew,emptywebpart

pagenamedTest1.

4. Writedowntheaddressofthenewpage.You'llusethat

addresswhenconfiguringtheproject.



8.2.2.ConfiguringaNewProject

TocreateandconfigureanewwebpartprojectinVisualStudio:

1. FromVisualStudio,chooseFile NewProject,selectthe

WebPartLibrarytemplatefromtheVisualBasic.NETor

VisualC#projecttype,andchooseOK.VisualStudio

createsanewwebpartproject.

2. ChooseProject

Debugging.



Properties



ConfigurationProperties



3. SelectStartURLandentertheaddressofthetestpageyou

createdintheprecedingsection.Youcanusethelocalhost

domain,forexamplehttp://localhost/Test

Pages/Test1.aspx.

4. SelectEnableASP.NETdebugging.

5. ChooseConfigurationProperties



Build.



6. EntertheOutputpathC:\InetPub\wwwroot\binandchoose

OK.(Youcreatedthe\binfolderinthesection"Configuring

theServerforDevelopment"earlierinthechapter.)

7. ChooseFile



SaveAlltosavetheprojectsettings.



8.2.3.BuildingandSigningtheAssembly

Sinceyouhaven'twrittenanycodeyet,thisstepmightseem

outofplace.However,SharePointrequiresthatassembliesbe

signedwithstrongnamesbeforeyoucanrun,test,anddebug

them.Youneedtosetupsigningusingthe.NETStrongName

utility(sn.exe);buildtheassemblyonce;thenextractthe

strongnametokenbeforeyoucanregisterthewebpartwith

SharePoint.Tosignandbuildtheassembly:

1. FromtheserverStartmenu,chooseAllPrograms

Accessories CommandPrompt.Windowsopens

commandpromptwindow.

2. Entercd\WebPartstochangetotheWebPartsfolderyou

createdintheearliersection"ConfiguringtheServerfor

Development"andrunvsvars32.bat.

3. Entersn-k"key.snk"tocreateastrongnamekeytousefor

signingtheassembly.

4. FromVisualStudio,openAssemblyInfo.vbor

AssemblyInfo.csandaddanAssemblyKeyFileattribute

referencingthekeyfile.InVisualBasicitwouldlooklike

this:





5. ChooseBuild BuildSolution.VisualStudiobuildsand

signsthewebpartassembly.

6. Returntothecommandpromptandrunsn.exetoextract

thetokenfromthesignedassembly.Rememberthatyou

changedthebuildpath,sothecommandlinewouldbe

somethinglike:



sn-Tc:\InetPub\wwwroot\bin\WebPartLibrary1.dll



7. Recordthepublickeytokenreturnedbysn.exeforuse

registeringthewebpartnext.



8.2.4.RegisteringtheWebPart

Youmustregisterwebpartassembliesintheserver's

Web.configfiletotellSharePointthattheassemblyissafeto

load.Toregisterthewebpart:

1. Fromtheserver's\InetPub\wwwrootfolder,open

Web.config.

2. AddaSafeControlelementtotheSafeControlssection.The

valuesforeachattributecomefromthelocationsinTable83.

3. SaveWeb.config.

ThefollowingelementshowsatypicalSafeControlelement.Each

projectwillhaveitsownuniquesettings.Table8-3describes

theattributesettingsandwhereyoufindthem.




Version=1.0.0.0,Culture=neutral,

PublicKeyToken=b03f5f7f11d50a3a"

Namespace="WebPartLibrary1"

TypeName="*"Safe="True"/>

...





Table8-3.SafeControlattributes

Attribute



Usedto



Settingscomefrom/notes



Assembly



Describethewebpart

assembly.



Theassemblyfilename,minusthe.DLL

extension.



Version



Identifytheversion.



Culture



Identifytheculture.



PublicKeyToken



Uniquelyidentifythe

assembly.



Namespace



Providetherootnamespace Projectrootnamespace(top-levelnamein

forthewebparts.

SolutionExplorer).



TypeName



Includeoneoralltypesfrom Theclassnameofthewebpartor*forall

theproject.

classesintheproject.



Safe



Flagthewebpartassafeor

SettoFalsetodisableawebpart.

unsafe.



Assembly:AssemblyVersionattribute.Projectsmust



haveastaticversionnumber.

Assembly:AssemblyCultureattributeorneutralif



nonespecified.



Outputfromsn.exe-T.



8.2.5.AddingtheWebParttoaPage

Ifyou'vecompletedtheprecedingtaskscorrectly,youshould

nowbeabletoaddthewebparttoapage,setabreakpoint,

andstepthroughthecodeindebugmodetoverifythat

everythingworks.It'sagoodideatodothischeckbefore

addingcodetotheproject,sincedebuggingcodeand

configurationproblemsatthesametimecanbeveryhard.To

addthewebparttoatestpage:

1. LoadtheWebPartprojectinVisualStudioandseta



breakpointontheoutput.WritelineintheRenderWebPart

procedure.

2. ChooseDebug StartorpressF5.VisualStudiobuildsthe

assemblyanddisplaystheTest1.aspxpageinthebrowser.

3. FromtheTest1pageinSharePoint,chooseModifyShared

Page AddWebParts Import.SharePointdisplaysthe

Importtaskpane.

4. ChooseBrowse,selecttheWebPart1.dwpfilefromtheweb

partprojectfolder,andchooseUpload.SharePointaddsthe

webparttothetaskpane.

5. Dragthewebpartfromthetaskpanetoawebpartzoneas

showninFigure8-1.ControlswitchestoVisualStudioat

thebreakpoint.

6. ClearthebreakpointinVisualStudioandpressF5to

continue.ControlreturnstothebrowserandSharePoint

displaythewebpartonthepage.

SharePointsavesthechangestoTest1.aspx,sothewebpartis

includedonthepagethenexttimeyouruntheproject.Tosee

howthatworks,stopdebuggingandchangethe_defaultText

constantasshownhere:

PrivateConst_defaultTextAsString="Newteststring"



PressF5toruntheprojectandthenewstringappearsinthe

control(Figure8-2).

Youdon'thavetoruntheprojecttoseethechange.Just

rebuilditandrefreshthepageinthebrowser.



animal8-1.Addingawebparttoatestpage



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 8.  Creating Web Parts

Tải bản đầy đủ ngay(0 tr)

×