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

Chapter 9.  Programming Web Parts

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

9.1.UnderstandingWebParts

WebpartsarebasedonASP.NETwebcontrols.Infact,the

WebPartclassinheritsfromSystem.Web.UI.Control.Thatmeansmost

oftheprogrammingissuesofcomposition,lifetime,state,and

serverversusclient-sideprocessingarethesame.Incase

you'renotfamiliarwiththoseconcepts,here'sabriefsynopsis:



Composition

WebpartsaremadeupofothercomponentsmainlyASP.NET

webcontrols,HTMLcontrols,literalstrings,andclient-side

scripts.ComponentsareassembledinaControlscollection

andthenrenderedintoHTMLthatissentbacktotheclient.



Lifetime

Awebpartinstanceiscreatedontheserverinresponseto

arequestfromaclient.Thatinstancerunscode,responds

toevents,renderstheresponse,andthenisdestroyedsoon

aftertheresponseissentbacktotheclient.Thenext

requestcreatesanewinstancewhichisinturndestroyed,

andsoon.



State

Thepropertiesofwebcontrolsarepreservedbeyondthis

lifetimebymeansofabuilt-inViewStateobject.ViewState

savessettingsbymeansofhiddenHTMLcontrolsrendered

withthewebpart.Thewebpartloadsthesevaluesshortly

afteritisinitializedwithLoadViewStateandsavesanychanges



backjustbeforeitisrenderedusingSaveViewState.



Server/ClientCode

Thewebpartclassrunsontheserverandthatcodeonly

executeswhenthepageispostedbacktotheserverby

meansofacommandbuttonorsomeotherpostback

control.YoucanalsoincludeJavaScriptthatrunsonthe

clientthosescriptsrespondtoeventsonthewebpart

withoutreturningtotheserver.Thatismoreefficientand

improvesperformanceinmanycases.

Figure9-1illustratestheseconceptsintermsofthelifecycleof

awebpartontheserverandhowthatispresentedonthe

client.



animal9-1.Keyeventsinthelifecycleofaweb

part



9.1.1.ExtendingASP.NET

Theprevioussectiondescribedhigh-levelconceptsthatare

constantforwebpartsandASP.NETcustomcontrols,butweb

partsextendtheASP.NETControlclasstoallowmembersto

modify,save,andconnectwebpartproperties,asdescribed

here:



Modify

Memberscansetpropertiesofwebpartsbychoosing

ModifySharedWebPartorModifyMyWebPartfromthe

webpartmenuandthenenteringtheirchangesonthe

propertiestaskpane.



Save

Webpartpropertiescanbesavedtothecontentdatabase.

Thatallowsmemberstomodifythepersonalorsharedview

ofapageandhavethosechangespersistthenexttime

theyviewthepage.



Connect

Memberscanconnectapropertyfromonewebparttoa

propertyonanotherwebpart.ThiscreatesaLego-block

typeapproachtobuildingwebpartpages.

TheSharePointdocumentationcallswebpartsdesignablethat



is,authorizedmemberscanchangetheirappearanceand

functionfromwithinthebrowserasshowninFigure9-2.



animal9-2.Designingawebpartinthebrowser



UnderASP.NETthosechangescanbemadeonlybyeditinga

control'sHTML,andthereisnobuilt-inwaytosavesettingsor

connectparts.TheSharePointWebPartandWebPartZoneclasses

providetheinfrastructureforthosefeatures.



9.1.2.UsingWebParts

Thatsaid,notallwebpartsaredesignable.Thenavigationbar

andQuickLaunchareasonthedefaultSharePointhomepages

areexamplesofnondesignableNavBarwebparts.Whetherornot

awebpartisdesignabledependsonwhereitisplacedona

page:

Webpartsinsidewebpartzonesaredesignableandcanbe

changedbymembers.TheSharePointdocumentationcalls



thesedynamicwebparts.

Webpartsoutsideofwebpartzonescan'tbemodifiedby

members.SharePointcallsthesestaticwebparts.

InChapter8,Ishowedyouhowtoimportdynamicwebparts

intoawebpartzoneonapage.Toaddastaticwebpart,edit

the.aspxpageinFrontPagetoregisterthewebpartassembly

andincludeanelementforthewebpart.Forexample,the

followinglineregisterssampleassemblyusedthroughoutthis

chapter:



<%@RegisterTagPrefix="Ch09"Namespace="Ch09Samples"Asse

Version=1.0.0.0,Culture=neutral,PublicKeyToken=fb6919fe5



Alltheattributesofthe@Registerdirectivematchthosedefined

forthewebpartsintheSafeControlelementinWeb.config,with

theexceptionofTagPrefix.TheTagPrefixattributedefinesthe

prefixyou'llusetoqualifythewebpartelementonthepage.

Forexample,thefollowingelementaddsWebpart1tothepage:








Propertiesofthewebpartareincludedasattributesinthe

element.Inthiscase,thetextattributesetstheTextcustom

propertyandthetitleattributesetsthewebpart'sbuilt-inTitle

property.Figure9-3showstheresult.



animal9-3.Settingastaticwebpart'sproperties



Inthiscontext,thetermsstaticanddynamicaremisleading.

Nondesignable(static)webpartscanacceptentriesanddisplay

resultsdynamicallythesamewaythatdesignablepartscan

(Figure9-4).



animal9-4.Isthisinteractivepartstaticor

dynamic?



SeetheStaticParts.aspxsampleforexamplesofincludingweb

partsoutsideofwebpartzones.



9.1.3.ProgrammingTasks

InASP.NETyoucancreatethreetypesofcustomcontrols:user

controls,compositecontrols,andrenderedcontrols.Because

SharePointdoesn'tdirectlysupportusercontrols(.ascx),all

webpartsareeithermadeupofotherwebcontrols(composite

controls)orrendereddirectlyasHTML(renderedcontrols).In

mostcases,webpartsuseacombinationofthetwotechniques,



sothat'swhatIshowinmyexamples.

Table9-1summarizesthemajortasksIcoverinthischapter

andprovidesaguidetosomeofthekeymembers,clauses,

attributes,andinterfacesusedtocompletethetask.

Table9-1.Webpartprogrammingtasks

Task



Summary



Createuser AddASP.NETcontrolstotheControlscollection;

interface

thenrenderthosecontrolsandadditionalHTMLto

anoutputobjectinRenderWebPart.



Keymembers

Controls

CreateChildControls

RenderControls

RenderControl

RenderWebPart



Add

JavaScript

andHTML



WritecodetoimportandmodifyHTMLcontrolIDs

tousetheSharePoint-generatednames.



ClassResourcePath

IsClientScriptBlockRegistered

RegisterClientScriptBlock

ReplaceTokens

UniqueID



Handle

child

control

events



Hookupserver-sideeventhandlingforASP.NET

controlsintheControlscollection.



Create

properties



Addpropertyprocedurestoawebpartandspecify

attributesthattellSharePointhowtodisplaythem

inthepropertytaskpaneandwhetherornotto

savetheirvalues.



AddHandler

WithEvents(clause)

Handles(clause)



Browsable(attribute)

Category(attribute)

DefaultValue(attribute)

ElementName(attribute)

SaveProperties

ShouldSerialize

WebPartStorage(attribute)

XmlElement(attribute)

XmlRoot(attribute)



Addmenus Additemstothewebpartdrop-downmenuthat

respondtoserverorclientevents.



CreateWebPartMenu

MenuItem

MenuItems



Customize

property

taskpane



Changethedisplayofawebpart'spropertiesinthe ApplyChanges

propertytaskpaneandcontrolhowthewebpartis

CancelChanges

updatedfromthosesettings.

CustomPropertyToolPart

GetToolParts

ParentToolPane

RenderToolPart

WebPartToolPart



Makeweb Implementinterfaceinthewebpartclassto

parts

providedatatootherwebpartsorconsumedata

connectable fromotherwebparts.



ICellProvider

ICellConsumer

IRowProvider

IRowConsumer

IListProvider

IListConsumer

IFilterProvider

IFilterConsumer

IParametersInProvider

IParametersInConsumer

IParametersOutProvider

IParametersOutConsumer



Youcanfindreferenceinformationforthesekeywordsinthe

SharePointSDKorintheVisualStudioHelptheSharePointSDK

omitsitemsthataren'tpartoftheirnamespace.Forinstance,it

doesn'tcovertheRenderControlmethodbecausethatispartof

the.NETFramework.



9.2.CreatingWebPartAppearance

ThecoreofthewebparttemplatecodeistheRenderWebPart

method.Thismethodiscalledjustbeforethecontrolis

disposedanditdeterminestheappearanceofthepartonthe

page.

Tocreatethisappearance,youwriteHTMLtotheoutputobject.

Forexample,thefollowingcodedisplaysasimpletable

containinginformationaboutthecurrentuser'sidentity:



'Requiresthislineatclasslevel

'ImportsSystem.Security.Principal

ProtectedOverridesSubRenderWebPart_

(ByValoutputAsSystem.Web.UI.HtmlTextWriter)

'GettheUseridentity.

DimuserAsIPrincipal=Me.Context.User

'Writetabletooutput

Withoutput

.Write("")

.Write("Authenticated")

.Write(user.Identity.IsAuthenticated())

.Write("Username")

.Write(user.Identity.Name())

.Write("Authenticationtype
.Write(user.Identity.AuthenticationType())

.Write("Codeisimpersonating
.Write(WindowsIdentity.GetCurrent().Name)

.Write(context.Request.UserLanguages(0))

.Write("Requesthost:

.Write(context.Request.UserHostName)

.Write("RequestIP:")

.Write(context.Request.UserHostAddress)

.Write("")

EndWith

EndSub



Atruntime,theprecedingwebpartdisplaysuserinformationin

atwo-columntable,asshowninFigure9-5.



animal9-5.RenderingUserInfowebpartat

runtime(unauthenticated)



HTMLtablesareausefulwaytocontrolthelayoutofwebparts,

butembeddingallthosetable,row,anditemtagsincode

resultsincodethatishardtodebug,update,andlocalize.The

onlywaytoseetheresultofyourHTMListoruntheproject,

andit'seasytomakeerrorsinthosestringliterals.

Fortunately,there'sabetterway.InsteadofembeddingHTML

literalsincode,createyourtablesasHTMfilesstoredas

resources,thenloadthoseandmodifythosefilesatruntime.

Thisapproachuses.NET'spowerfulstringfunctionsto

substitutevaluesfromcodeintothetable.Toseehowthis

works:

1. Createanew.HTMfileinyourwebpartproject.

2. Setthefile'sBuildActionpropertytoEmbeddedResource.

3. EdittheHTMpagewithVisualStudio'sdesigntoolsto

createthetable,addheadings,scripts,orcontrolsas



needed.Useliteralplaceholders(forexample,:{0})for

itemsyouwillreplacefromcode.

4. Createaproceduretoloadtheresourcebyfilename.

5. Createaproceduretofillinthetablevariablesusingthe

Stringobject'sFormatorWritemethods.

6. WritetheresulttotheoutputobjectintheRenderWebPart

event.

Figure9-6showsauserinformationtablecreatedinVisual

Studiodesignmodethathassevenplaceholdersforvaluesto

befilledinfromcode.

Thefollowingutilityprocedureloadstheresourcefromthe

assemblyandreturnsitsHTMLasastring.Resourcenamesare

case-sensitive,sobesuretocorrectlycapitalizethefilename

whencallingthisprocedure:

'Requiresthislineatclasslevel:

'ImportsSystem.Reflection

FriendFunctionGetHtml(ByValfNameAsString)AsString



animal9-6.CreatingawebparttableinVisual

Studiodesignmode



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

Chapter 9.  Programming Web Parts

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

×