Tải bản đầy đủ - 0 (trang)
Chapter 22. Implementing Custom Embedded Functions

Chapter 22. Implementing Custom Embedded Functions

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

AddingEmbeddedCode

Togetabetterunderstandingofhowembeddedcustomcodeis

usedinareport,reportdeveloperscanassumeallofthecode

placedinthecodewindowgetscompiledintoamake-believe

classcalledCode.Youcanaddpropertiesandmethodstothe

make-believeCodeclass,andcallclassmembersfrom

expressionsinthereport,whichhastheclassdefined.

Embeddedcodeiscompiledintoareport'sintermediateformat

andgetsexecutedasneededwhenthereportisrendered.

ReportDesignerprovidesasimpletextareatoalloweditingof

theembeddedcode.Toaccessthecodeeditor,completethe

followingsteps:

UsetheReport,ReportPropertiesmenu(iftheReportmenu

isnotavailable,clickwithinthereportdesignarea).

Alternatively,right-clickontheareasurroundingthe

report'sbodyandselectthePropertiesmenu.

ClicktheCodetabintheReportPropertiesdialogbox.

YoushouldseeawindowsimilartoFigure22.1andcantype

thecodeintheCustomcodearea.



Figure22.1.Codeeditor



Thecodeeditorisbasicallyamultilinetextbox,anditdoesnot

provideanyproductivityassistance,suchasIntellisenseor

debugging.Youhavetobeextremelycarefulwhileusingthis

codeeditor.Forexample,onlyonelevelof"undo"actionis

allowed,ascomparedtoVisualStudio'sinfiniteundo.

Forallofitsdifficulties,embeddedcodeprovidesseveralkey

benefitsforadeveloper,includingthefollowing:

Amoreelegantapproach(ascomparedtoexpressions)to

medium-complexitycodingscenarios

Asinglerepositoryforfunctionsandmethodsthatcanbe

reusedbymultipleitemswithinasinglereport,asopposed



tocomplexcopy-and-pasteexpressions

Directaccesstotheexceptionhandlingfunctionalityof

VB.NET

Everydeveloperknowsfunctionreuseisbeneficialovercopyand-pasteprogramming.Takethefollowingfictitiousexample.

Supposetwodeveloperswereassignedtheparallel

developmentofasinglereport.Onedeveloperusedembedded

code,whereastheotheroneusedsimpleexpressions.Oneof

theinitialgoalswastohighlightnegativevaluesinred.Later,

thisgoalchangedtoamorecomplexrequirement,suchas

color-codingnumericranges.Thedeveloperwhoused

embeddedcodecouldadapttothechangeinrequirements

quickly,andwouldmakehismanagerhappy,probablygettinga

bonusintheprocess.

EmbeddedfunctionsmustbewritteninVB.NET.Ifyouprefer

C#,youwouldhavetodevelopacustomassembly.Thistopicis

coveredinChapter23,"HowtoCreateandCallaCustom

AssemblyfromaReport."

Thefollowingstepsaddthefunctionusedinthepreceding

narrative:

1. OpenthereportpropertiesbyeitherclickingtheReport,

ReportPropertiesmenu,orright-clickingonthearea

surroundingthereport'sbodyandselectingProperties.

2. IntheReportPropertiesdialogbox,clicktheCodetaband

enterthefollowing-function:

FunctionHighlight(valueAsInteger)AsString



Ifvalue<0



return"Red"

Else

return"Black"

EndIf

EndFunction



3. DragaTextboxfromtheToolboxtothereportandplacethe

followingcodeintheBackgroundColorproperty:

=Code.Highlight(me.value)



4. Place-1(minusone)intheValueproperty.

5. OpenthereportinPreviewmodetoseethetextboxwitha

redbackground.







DebuggingEmbeddedCode

SSRSdoesnotprovideanyfacilitiestostepthroughthe

embeddedcode,and,thus,youhavetwooptions:Youcan

eitherdebugcodeinVisualStudio.NETorusesomepreVisual

Basictricksfordebugging.Thefirsttrickistolabelcodelines.

Thisisbeneficialtolocatebothcompile-timeandruntime

errors.Thefollowingcodefragmentshowshowtolabelcode

lines.Italsohaserrorsthathavebeenintentionallyplacedfor

demonstrationpurposes.

FunctionAdd(nAsInteger)

1:i=i+n

2:returni

EndFunction



Whenyoubuildareportwiththecodesnippetortrytopreview

thereportthatcallsthiscode,SSRSreportstwoissues(one

warningandoneerror):

WarningThereisanerroronline0ofthecustomcode:

[BC42021]Functionwithoutan'As'clause;returntypeofObject

assumed.Warningsareonlydisplayedifatleastoneerroris



found.

ErrorThereisanerroronline1ofthecustomcode:

[BC30451]Name'i'isnotdeclared.Onlythefirsterroris

displayed.

Withasmallcodefragmentsuchastheprecedingexample,



findingerrorsmightnotbeanissue.Foracodefragmentthat

hasasignificantnumberoflines,locatingtheonewithanerror

canbeaburden.



Note

Keepinmindthatlabelscanonlybepresentinside

offunctionsorsubroutinesandcanrepeatinsideof

differentfunctions.



Tip

Toproperlydeterminelinenumbers,deliberatelyadd

anerrorandpreviewthereport.TheSSRSerror

indicatesthelinenumber.



Tip

Toavoidlaboriouseffortsofnumberingand

renumberingoflines,youshouldonlylabelkey

expressionsorthefirstlineoffunctions.

Alternatively,youcanuselabelingtonarrowdowna

linewithanerror.



Thesecondtrickistolocatealinethatcausesruntimeerrorsby

usingatrY-CATCHblock:



FunctionDivByZero()



DimxAsInteger

Try'Setupstructurederrorhandling.

3:x=x/0

CatchexAsException



Returnex.ToString()&vbCrLf&"ExceptionatLine:"

EndTry

EndFunction



TheresultofthecalltothefunctionDivByZero()is



System.OverflowException:Arithmeticoperationresultedinano

atReportExprHostImpl.CustomCodeProxy.DivByZero()

ExceptionatLine:3



NotethatfunctionDivByZero()usestheundocumentedfunction

Erltoreturnalinenumberforthelineofcodethatproduced

theerror.Erlreallyreturnsalabelnumber(inthepreceding

code,itis3).

Whenyoudonotimplementerrorhandling,andthenmakea

calltoafunctionwithintheValuepropertyofareportitem,the

reportitemshows"#Error"asaresult.



Dependingontheprecisionofareturnvalueprovidedfroma

function,otherpotentialresultsare"Infinity"or"NaN"(Nota

Number).



Tip

AlwayschecktheErrorListwindowafteraBuild

operationhascompleted,andmakesurethatthere

arenowarnings.Bestpracticesuggestseliminating

allwarningsinproductioncode.



Exceptionswithinotherpropertiescanbecaughtduringthe

Buildoperation.







Summary

Customembeddedcodecanprovideamoreelegantapproach

tomedium-complexitycustomcodethanexpressionsthrough

functionreuse,centralizedcoderepository,andadditionalerrorhandlingoptions.

CustomembeddedcodeisaVB.NETcodeembeddedina

report.Acodeisembeddedasapartofareportdefinition

(RDL)fileandcompiledtogetherwiththecontainerreport.

Manyerrorsarecaughtbythecompilerwhenareporting

solutionisbuilt.

AlthoughembeddedcodeallowsadevelopertousefullobjectorientedfunctionalityofVB.NET,embeddedcodeismostlyused

forsimplelogic.Itispossibletodevelopcomplexembedded

code,butthisisnotusuallydoneduetolimiteddebugging

facilitiesandlimitedfunctionalityoftheembeddedcodeeditor.

Theembeddedcodeeditorisasimpletextboxthatdoesnot

haveadvancedfeatures,suchascodecompletion,availablein

VisualStudio.

Whenfunctionsaretoocomplicatedforembeddedcodeto

handleefficientlyoryouhaveapreferencetouseC#insteadof

VisualBasic,youcandevelopandcallacustomassemblyfrom

areport.Thenextchapterexplainshowtoleverageacustom

assemblywithinareport.



Chapter23.HowtoCreateandCalla

CustomAssemblyfromaReport

InThisChapter

Strong-NamedCustomAssemblies

.NETSecurityPrimerforaSSRSAdministrator

AssembliesThatRequireOtherThanExecutePermissions

DebuggingCustomAssemblies

SSRScomeswithacomprehensivesetoffunctionsthatcanbe

usedwithinreports.However,youmightneedtoaddcustom

functionalitythatisnotcoveredbythesetofcommonfunctions

oristoocomplicatedforembeddedcodetohandleefficiently.

Second,ifyou,asadeveloper,arehardsetonC#asa

languageofchoice,acustomassemblyisthewaytogo.A

coupleofexamplesoffunctionalitythatarebetterhandledbya

customassemblyareencryptionandtrendanalysis.



Note

Trendplottingfunctionalityisavailableinthefull

versionoftheDundas'chart.However,thechart

doesnotprovidetrendcalculationinformationtoa

report.Insomecases,trendinformationmightbe

neededtotriggersomeaction,suchasformatting

onareport,andthisiswheretrendanalysis

assemblymightbeuseful.



Let'sstartwithasimpleexampleanddevelopafunction

GetLibraryInfo(),whichreturnsasinglestringwithalibrary

versioninformation.

StartVisualStudio2005andcreateanewClassLibraryProject.

Let'scalltheprojectRSCustomLibrary;seeFigure23.1.



Figure23.1.Newlibraryproject.



[Viewfullsizeimage]



VisualStudiocreatesaprojectwithasingleclassClass1.Let's

renamethefileClass1.csinSolutionExplorertoMainClass.cs.Note

howVisualStudiochangedthenameoftheclassinthecode.

Substitutecodeintheclassmodulewiththefollowingcode:



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

Chapter 22. Implementing Custom Embedded Functions

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

×