Tải bản đầy đủ - 0 (trang)
Chapter 26. Introduction to Web Parts

Chapter 26. Introduction to Web Parts

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

WebPartBasics

WebPartsarespecialcontrolsthataredesignedtoprovidethe

userwithdiscreteunitsoffunctionalitythatcanbeplacedona

pageinvirtuallyanylocation.Adiscreteunitoffunctionality

essentiallymeansthattheWebPartsaredesignedtoperform

specifictaskssuchasdisplayinganinbox,providingatasklist,

displayingthecurrentweather,andsoon.WebPartsarenot

entireapplicationsencapsulatedinacontrol.ThesuiteofWeb

Parttoolsallowsthedevelopertoquicklyandeasilycreate

pages(calledWebPartPages)thathostWebParts.Suchpages

canallowuserstocontrolthelayoutbydragginganddropping

WebPartstomovethemintothelocationthattheuser

chooses.UserscanalsocontrolWebPartproperties;theycan

minimizeorevencloseWebPartsjustastheywouldmanipulate

Windowsontheirdesktop.Allofthisfunctionalityisvirtually

freeforthedeveloperutilizingtheWebPartssuiteofcontrols

andASP.NET2.0.

TherearemanyreasonstouseWebParts.Ifyouwantto

provideyouruserswithfunctionality,butyouwantyourusers

tobeabletochoosewhatdataispresentedtothem,andhow

thatdataispresentedtothem,WebPartswilldefinitelyprovide

youwithahugeboostinproductivity,timetomarket,and

applicationfunctionality.

WebPartsmakeuseofthepersonalizationprovidertostore

personalizationdata.WhenaWebPartisaddedtoapage,it

containsbothshareddataandpersonalizationdata.Thismeans

thatacontrolcanhaveasetofpropertiesthatareshared

amongallusers.WhenauserchoosestocustomizethatWeb

Part,hispersonalizationdataoverridestheshareddata,

creatinguser-specificsettings.Forexample,youcouldcreatea

WeatherWebPartthathasasharedsettingofZipCodethat

defaultstotheZIPcodeofthewebsite'sheadquarters.When

userschoosetocustomizethatWebPartwiththeirownZIP



code,theycreateauser-specificsettingthatoverridesthe

shareddefault.

Figure26.1showsaconceptualmock-upofwhatasampleWeb

PartPagemightlooklike.Thepagehasbeendividedintozones

inwhichWebPartscanreside.ThepageinFigure26.1hasWeb

Partsfordisplayingnews,weather,ato-dolist,theuser'sinbox,

andasitenavigationcontrol.AfullyfunctioningWebPartPage

containingtheseWebPartswouldallowtheusertochoose

whichpartswerevisible,wherethosepartssatonthepage,

andeventhingslikewhetherthepartshoulddisplayaheader

oraborder.IftheWebParthadcustomproperties(suchasthe

ZIPcodeforlocalweather),theusercouldalsochooseto

supplythatinformation.



Figure26.1.AWebPartPageconceptual

diagram.



[Viewfullsizeimage]



Severalcontrolsandclassesprovidethecoreframeworkfor

WebParts.Table26.1containsalistofthekeycomponent

controlsrequiredtomaketheWebPartsfunctionalitypossible.

Table26.1.WebPartControls

Control



Description



WebPartManager



TheWebPartManagerisaUI-lesscomponentthatresides

onaWebFormandmanagesallWebPartsonthat

page.EveryWebPartPagehasoneandonlyone

WebPartManager.



WebPartZone



AspecialtypeofcontainercontrolthatcontainsWeb

PartswithinaZoneTemplate.Pagesaretypicallydivided

intozonessuchasaheader,footer,center,left,and

right.



EditorZone



AcontainercontrolthatcontainsWebPartsthatenable

userstoeditandpersonalizeWebPartsonapage.



CatalogZone



AcontainercontrolthatcontainsCatalogPartcontrols.

UsethiszonetoprovideuserswithalistofWebParts

thattheycanaddtoapagethatmightnotbeonthe

pagebydefault.



Additionalcontrolsareusedinconjunctionwiththeoneslisted

inTable26.1,buttheonesinTable26.1arethecontrolsyou

shouldbeconcernedwithatthetoplevel.

ThekeytoworkingwithWebPartsisinknowingwhattheycan

andcannotdo.Everytimeyouaddaserverorusercontrolinto

aZoneTemplatewithinaWebPartZone,thatcontrolisencapsulated

withinaGenericWebPartcontrol.Beforeyoustartcodingyourown

WebPartsandworkingwiththem,youshouldknowhowthis

classworks,becauseitandtheWebPartclassformpartofthe

foundationoftheWebPartsframework.TheGenericWebPartclass

isgeneratedatruntimetoallowusercontrolsandothernon-



WebPartcontrolstohaveaccesstoWebPartfunctionality.

Table26.2and26.3showsomeofthecommonpropertiesand

methodsoftheWebPartclass,theclassfromwhichallWebParts

(includingGenericWebPart)inherit.

Table26.2.CommonWebPartProperties

Property



Method



AllowClose



IndicateswhethertheusercanclosetheWebPart.

WhenaWebPartisclosed,itsassociatedcontrolbaris

alsohiddenfromthepageinthedefaultdisplaymode.



AllowConnect



Indicateswhetherthepartcanbeconnectedtoother

parts(connectedWebPartsarecoveredlaterinthis

chapter).



AllowEdit



Indicateswhethertheusercaneditthepropertiesof

theWebPart.



AllowHide



Indicateswhethertheusercanhidethepart.



AllowMinimize



IndicateswhethertheusercanminimizetheWebPart.



AllowZoneChange



Indicateswhethertheusercanmovethepartbetween

zones.Somepartsrequireaminimumamountofroom

todisplayandshouldn'tbeallowedtobemovedintoa

smallerzone.



CatalogIconImageUrl GetsorsetstheiconusedtorepresenttheWebPart



withinacatalogofWebParts.

ChromeState



GetsorsetswhetheraWebPartisminimizedor

normal.



ChromeType



GetsorsetsthetypeofborderthatsurroundstheWeb

Part.



ConnectErrorMessage Messagedisplayedtousersifafailureoccurswhen



attemptingtoconnecttheWebParttoanotherpart.

Description



GetsadescriptionoftheWebPartthatwillbedisplayed



incatalogsandtooltips.

DisplayTitle



ThetitletextdisplayedinthetitlebaroftheWebPart.



ExportMode



IndicatestheportionoftheWebPart'spropertiesthat

canbeexported.



HasSharedData



IndicateswhethertheWebParthasshared

personalizationdata.



HasUserData



IndicateswhethertheWebParthasuser-specific

personalizationdataassociatedwithit.



HelpMode



IndicatesthetypeofhelpUIdisplayedfortheWebPart.



HelpUrl



Thepagetoopenwhenauserrequestshelpforthe

part.



Hidden



Indicateswhetherthepartishidden.



IsClosed



IndicateswhethertheWebPartisclosed.



IsShared



IndicateswhethertheWebPartisshared.



Subtitle



(ReadOnly)AstringaddedwiththeTitlepropertythat

indicatesthefulltitleoftheWebPart.



Title



ThetitleoftheWebPart.



TitleIconImageUrl



TheURLindicatingtheWebPart'siconinthetitlebar.



Verbs



Thecollectionofcustomverbsassociatedwiththepart.



Zone



GetsthezoneinwhichtheWebPartcurrentlyresides.



ZoneIndex



GetstherelativepositionwithinthezoneoftheWeb

Partwithinitscurrentzone.



Table26.3.Part-SpecificControlMethods

Method



Description



CreateEditorParts



Createsinstancesofcustomeditorpartsthatcanbe

usedtoedittheWebPartineditmode.



SetPersonalizationDirty Setsaflagthatindicatesthatthedatahaschangedfor



theWebPartandneedstobeupdatedintheunderlying

personalizationstore.







UsingaPersonalizationProvider

Usingthepersonalizationproviderisactuallyprettyeasy.Allof

thecodethatcommunicatesdirectlywiththeprovideris

containedwithintheWebPartssetofcontrolsandclasses.This

meansthattheonlyworkyouneedtodoistoconfigurethe

personalizationdatabaseandmodifytheWeb.configfileto

indicatetheappropriateproviderconnectionstring.

Creatingthepersonalizationdatabaseisactuallydoneby

creatingtheApplicationServicesdatabaseusingthe

instructionsinChapter25.

OpenaVisualStudio2005CommandPromptwindowandtype

aspnet_regsqlonthecommandline.Youwillbepresentedwith

theASP.NETSQLServerConfigurationWizard.Thiswizardwill

promptyouforthelocationofaSQLServerinstanceaswellas

thecredentialsneeded.Youcanalsochoosewhetheryouwant

tocreatetheApplicationServicesinformationinanew

databaseorconfigureanexistingone.Whenyouhave

completedthiswizard,youwillhavecreatedanApplication

Servicesdatabasethathoststhedata,metadata,andstored

proceduresrequiredtosupportthemembership,roles,profile,

andpersonalizationproviders.

AfteryouhavecreatedyourApplicationServicesdatabaseand

you'veverifiedthatitisavailableandreadytobeaccessed,you

needtomodifyyourwebapplication'sWeb.configfiletopointthe

personalizationprovideratthislocation.AsampleWeb.config

configuredforpersonalizationisshowninListing26.1.



Listing26.1.APersonalization-Enabled

Web.configFile



[Viewfullwidth]










connectionString="database=ASPNET_AppServices;server=localhost;

Trusted_Connection=true;"/>












connectionStringName="AppSvcsConnection"

type="System.Web.UI.WebControls.WebParts.SqlPersonalizationProvider"/>

















ThisWeb.configfileindicatesthatthe

System.Web.UI.WebControls.WebParts.SqlPersonalizationProviderwillbe



usedasthepersonalizationprovider,anditwillusethe

databaseindicatedbytheconnectionstringnamed

AppSvcsConnection.

Runanemptydefault.aspxinanapplicationwiththeWeb.config

filefromListing26.1andseeifitworks.Ifnoruntimeerrors

occurwhiletryingtoloadthedefaultpage,youcanassume

thatapersonalizationconnectionwasmadetothedatabase

andyoucancontinueontothenextsectiontocreateyourfirst

WebPartPage.Ifyoudohaveerrors,thereisusuallyenough

informationintheerrormessagetoindicatewhatwentwrong.

Makesuretochangethedatabaseandserveroptionsinyour

connectionstringtomatchtheinformationyouprovidedwhen

youcreatedtheApplicationServicesdatabaseusingthe

aspnet_regsqlwizard.



BuildingYourFirstWebPartPage

Thestepsinthissectionwalkyouthroughtheprocessof

creatingyourfirstWebPartPage.Atfirstitcanseemvery

overwhelmingastherearealotofnewcontrolstouseandalot

ofnewterminology.AfteryouhavecompletedtheWebPart

Page,youarestronglyencouragedtoplaywithit,modifyit,

andexperimentwithitbeforecontinuingontothenextsection

sothatyoucanfamiliarizeyourselfwiththebehaviorand

functionalityofWebPartswithinASP.NET2.0.Ratherthanhave

youexaminethecompletedsolution,thissectionisdesignedto

walkyouthroughalloftheindividualstepsrequiredincreating

aWebPartPagesothatyoucangainathoroughunderstanding

oftheprocessandcanreusethatprocessinyourown

applications.Usethefollowingwalk-throughtocreateyourfirst

webpartpage:



1. CreateanewASP.NETwebapplicationcalledFirstWebPartPage.Whenyou

modifytheWeb.configsothatitpointstothepersonalizationprovidercr

section.YournewWeb.configshouldlookalotliketheoneshownin



2. Youwillwanttodivideyourpageupintozones.Azoneisacontainerf

usedtodividecontentareasofdifferingsizesandpurposes.Common

sidebars,centralcontentzones,footers,andoccasionallyright-justifie

default.aspxandcreateathree-columntableinbetweenthedefault

Viewmenu(whenlookingatthedesignerview)hasbothNon-VisualC

thatyoucanseeeverythingthat'sgoingoninbothsourceviewandde



3. OpenyourToolboxandexpandtheWebPartsgroup.Dragthe

Toolboxontoyourwebpage(thisworksineitherdesignorHTMLview

columntablecreatedinstep2.RenamethecomponenttowpManager

plumbingnecessarytoconvertastandardpageofstaticcontrolsintoa



4. DragaWebPartZonefromtheToolboxintotheleftmosttablecellinthefir

createdearlier.CallthiscontrolzoneSideBar.SettheHeaderTextpropertyt



5. DraganotherWebPartZonecontrolfromtheToolboxintothemiddlecolum

controlzoneMain.SettheHeaderTextpropertyto"MainZone".



6. AtthispointyoushouldhaveaWebPartManagerfollowedbyathree-colum

shouldcontainthezoneSideBarcontrolandthemiddlecolumnshouldco

thedesignview,dragatreeViewcontrolanddropitintheboxframedb

toaddrandomnodesandformatitasyouseefit.Theimportantthing

switchtosourceview,youwillseethattheTReeViewisnowcontainedw

insidethezoneSideBarcontrol.Atruntime,thetreeViewcontrolwillautom

controlofaGenericWebPart,givingitaccesstoallofthefunctionalitypro

engine.



7. Youmightnoticethatinthedesignview,thetreeViewcontrolisinsidea

"Untitled"withtheWebPartmenudown-arrowicon.Thisisbecauseth

unlabeledGenericWebPart.Tofixthis,youcanaddtitle="Tree"tothe

warningmessageaboutitinthesourceview,butyoucanignoreitbec

thedesignview,"Untitled"willhavebeenreplacedwith"TRee"



8. NowdragthreedifferentlabelsintothezoneMainzonecontrol.Don'two

with
tagsthefactthattheyarecontainedwithinaWebPartZone

appearwithintheirownframes.CallthemlblOne,lblTwo,and

whatevertextyouliketothem.SettheTitlepropertyonthemusingt

it,youcanright-clickzoneSideBarandzoneMain,chooseAutoFormat,and

colorfulthanthedefaultzonecolors.Figure26.2showsascreenshoto

stageofthewalkthrough.



Figure26.2.VisualStudio2005Designer,building

[Viewfullsizeimage]



9. Whenyourunyourapplicationnow,youshouldseefourdifferentWeb

themhasadrop-downmenuthatappearswhenyouclickthedown-ar

"Minimize"linkanda"Close"link.Ifthisisn'tthecase,gobackoverth

sureyoudidn'tmissanythingbeforecontinuing.



WebPartPageCaveats



AsyouplaywiththeWebPartPage,youmightendupclickingthe

andyoudon'thavesomefacilityonthepagetoswitchtheWebPa

youwillneverseethatWebPartagain.Thepersonalizationprovid

closedstateofthatWebPart,andtheonlywaytogetitbackisto

modesothatyoucaneditthepropertiesoftheclosedWebPartto

lotofdevelopersfamiliarwithSharePointoftentakeitforgranted

switchtoeditmodeexistsbydefault.Asyou'llseeinthiswalkthro

controlthatallowsyourpagetoswitchintoandoutofeditmode.

controlcanbeusedonasmanypagesinasmanyapplicationsas



10. Atthispoint,younowhaveafunctioningWebPartPagethatisdisplay

multipleWebPartZones.Theproblemnowisthatyoudon'thaveany



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

Chapter 26. Introduction to Web Parts

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

×