Tải bản đầy đủ - 0 (trang)
Chapter 23. How to Create and Call a Custom Assembly from a Report

Chapter 23. How to Create and Call a Custom Assembly from a Report

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

Let'sstartwithasimpleexampleanddevelopafunction

GetLibraryInfo(),whichreturnsasinglestringwithalibrary

versioninformation.

StartVisualStudio2005andcreateanewClassLibraryProject.

Let'scalltheprojectRSCustomLibrary;seeFigure23.1.



Figure23.1.Newlibraryproject.



[Viewfullsizeimage]



VisualStudiocreatesaprojectwithasingleclassClass1.Let's

renamethefileClass1.csinSolutionExplorertoMainClass.cs.Note

howVisualStudiochangedthenameoftheclassinthecode.

Substitutecodeintheclassmodulewiththefollowingcode:



usingSystem;

usingSystem.Reflection;//Needtohavethissowecangetthe

namespaceRSCustomLibrary

{

publicclassMainClass

{

//MethodGetLibraryInfo()returnsthiscustomAssembly

//RSCustomLibrary,Version=1.0.0.0,Culture=neutral,Pub

publicstaticstringGetLibraryInfo()

{

returnAssembly.GetExecutingAssembly().GetName().To

}

}

}



Tip

Tosimplifyacustomassemblytest,developerscan

useasimpleWindowsapplicationtocallassembly's

methods.Thisallowstestingassembly'sfunctionality

priortotestswithSSRS.



Thecompiledassemblymustbelocatedindirectoriesinwhich

itisaccessibleby

ReportDesigner(thedefaultdirectoryisC:\Program

Files\MicrosoftVisualStudio8\Common7\IDE\PrivateAssemblies).



Thisallowscallinganassemblyfromreportsinpreview

mode.



ReportServer(thedefaultdirectoryisC:\Program

Files\MicrosoftSQLServer\MSSQL.3\Reporting

Services\ReportServer\bin).Thisallowscallingassemblyfrom



reportsdeployedonReportServer.



Note

ReportDesignerand/orReportServerreportsan

errorifitcan'tfindthelibrary:

[rsErrorLoadingCodeModule]Errorwhileloadingcodemodule:

'RSCustomLibrary,Version=1.0.0.0,Culture=neutral,

PublicKeyToken=null'.Details:Couldnotloadfileor

assembly'RSCustomLibrary,Version=1.0.0.0,

Culture=neutral,PublicKeyToken=null'oroneofits

dependencies.Thesystemcannotfindthefilespecified.



Let'snowuseourcustomassemblyinareport.Youfirsthaveto

referencetheassembly:

1. OpenthereportpropertiesusingtheReport,ReportProperties

menu.

2. Inthepropertiesdialogbox,clicktheReferencestab.

3. Click"..."andnavigatetothelibrary.SeeFigure23.2fordetails.



Figure23.2.Referencecustomassembly.



Developerscannavigatetoanylocationwherethelibraryispresent,

suchasthebindirectoryofthelibraryproject.Thisoperationonly

recordsthereferencetotheassemblyandnotaspecificlocationof

thisassembly.ReportDesigneraddsthefollowingRDLtoreference

anassembly:



RSCustomLibrary,Version=1.0.0.0,

Culture=neutral,PublicKeyToken=null







4. EnteraClassNameandanInstanceName.FillinginaClassName

andanInstanceNameisoptionalforstaticmethods.Whenyou

specifyaClassNameandanInstanceName,ReportDesigner

createsaninstanceofthespecifiedclassand,subsequently,youcan

accesstheclassinsideofareportusingtheclass'instancename.



ReportDesigneraddsthefollowingRDL:





RsCustomLibrary.MainClass

myMainClass





WhenspecifyingaClassName,youneedtoprefixthenameofthe

classwithitsassembly,suchasRSCustomLibrary.MainClass.Otherwise,

theSSRScompilerreturnsanerror:

[rsCompilerErrorInClassInstanceDeclaration]Errorinclassinstance

declarationforclassMainClass:[BC30002]Type'MainClass'isnotdefined.



5. Calltheassemblyfromoneofthereport'sexpressions.Astatic

methodcanbecalledas=..;

inthiscase,=RSCustomLibrary.MainClass.GetLibraryInfo().Aninstance

methodcanbecalledas=..;

thiscase,=Code.myMainClass.GetLibraryInfo().Astaticmethoddoesnot

requireaninstance,butcanstillbeaccessedthroughtheinstanceif

sodesired.



Nowthatyouhavereferencedacustomassemblyinareport

andcopiedbinariestotheReportDesigner'sdirectory,the

assemblycanbecalledfromthereportinpreviewmodeofthe

ReportDesigner.However,callingtheassemblywillnotworkif

youtrytodebugordeploythisassemblytoaReportServerif

noadditionalstepsaretaken.

Thischapterexplainstheadditionalstepsneededtomakea

deployedassemblyavailabletoreports.



Note



Theproceduresthatyouhaveseenthusfarallow

referencingacustomassembly,butbecauseyou

havenotyetsetsecurityfortheassembly,the

assemblycanonlybecalledinpreviewmode.



Sometimes,youmightneedtopassinitializationparametersto

aclassinacustomassembly.Thisisdonebyoverridingthe

OnInit()methodoftheCodeobjectofareport.Thiscanbedone

byeditingtheRDLdirectlyorusingthecodeeditor.Toopen

codeeditor,usetheReport,ReportPropertiesmenuandclick

theCodetabintheReportPropertiesdialogbox.

SeeFigure23.3fordetails.



Figure23.3.Usingthecodeeditortooverride

OnInit()method.



Toinitializeaclass,youcaneithercreateanewinstanceofthe

classinsideofOnInitandpassparameterstoaclassconstructor

orwriteapublicinitializationmethodforaclassandcallthis

methodfromOnInit.

Whenyoucreateanewinstanceoftheclass,makesurethat

theinstancenameusedintheOnInitmethoddoesnotconflict

withtheinstancenameyouhavecreatedwhenyoureferenced

anassembly.





DimPublicmyMainClass1AsRSCustomLibrary.MainClass

ProtectedOverridesSubOnInit()

myMainClass1=newRSCustomLibrary.MainClass(Report.

EndSub





Toinvokethisinitializationmethod,fromareportyoucanuse

thefollowingexpression:=Code.myMainClass1.GetLibraryInfo()



Note

Ifthereisaconflictbetweentheinstancecreatedin

areport'sreferenceandanyoftheinstances

generatedinthecode,SSRSgeneratesanerror:

[rsCompilerErrorInClassInstanceDeclaration]Errorinclass

instancedeclarationforclassRsCustomLibrary.MainClass:

[BC30260]'myMainClass'isalreadydeclaredas'PrivateDim

myMainClassAs'inthisclass.



Whenyoucallapublicinitializationfunction,createaninstance

oftheclassusingtheReport,ReportPropertiesmenuandthen

clicktheReferencestab.

ThencalltheinitializationfunctionfromOnInit.Makesurethat

theinstancenameusedinOnInitcorrespondstotheinstance

nameusedwhenyoureferencedanassembly.





ProtectedOverridesSubOnInit()

myMainClass.InitializeClass(Report.Parameters!Period

EndSub





Toinvokethisinitializationmethod,youcanusethefollowing

expression:=Code.myMainClass.GetLibraryInfo()

WithintheOnInitmethod,youcanuseitemsfromtheGlobals,

Parameters,andUsercollections.TheFieldsandReportItems

collectionsarenotavailablewhentheOnInitmethodisinvoked.



Note

Donotforgettoprefixthecollectionnamewith

Report(suchasReport.Parameters);otherwise,youwill

receiveanerror:[rsCompilerErrorInExpression]TheValue

expressionforthetextbox'textbox2'containsanerror:

[BC42024]Accessofsharedmember,constantmember,enum

memberornestedtypethroughaninstance;qualifying

expressionwillnotbeevaluated.



Totakeadvantageofinitialization,youneedtoadda

constructortotheassembly.Theupdatedassemblymayhave

thefollowingcode:



usingSystem;

usingSystem.Reflection;

//NeedtohavethissowecangettheAssemblyinformation

namespaceRSCustomLibrary

{

publicclassMainClass

{

staticintmPeriod=-1;

publicMainClass()

{}

publicMainClass(intPeriod)

{

mPeriod=Period;

}

publicvoidInitializeClass(intPeriod)

{

mPeriod=Period;

}

//MethodGetLibraryInfo()returnsthiscustomAssembl

//RSCustomLibrary,Version=1.0.0.0,Culture=neutral,



//ANDinitializationstatus:

//

publicstaticstringGetLibraryInfo()

{

returnAssembly.GetExecutingAssembly().GetName()

+(

(mPeriod!=-1)?

"Initializedwithvalue="+mPeriod.To

:"Notinitialized"

);

}

}

}



Notetheoperator"?"(questionmark)usageinthecode.Ifyou

arenotfamiliarwiththisoperator,itissimilartotheIFfunction

ortheIF-THEN-ELSEstatement.



Note

Ifyouchoosetouseaconstructortoinitializethe

class,anexplicitdefaultconstructor(constructor

withnoparameters)isrequired.Ifnodefault

constructorisdefined,SSRSreturnsanerror:

[rsCompilerErrorInClassInstanceDeclaration]Errorinclass

instancedeclarationforclassRsCustomLibrary.MainClass:

[BC30455]Argumentnotspecifiedforparameter'Period'of

'PublicSubNew(PeriodAsInteger)'.



Itisverylikelythatthefirstdeployedversionofanassembly

willnotbeperfectandonedayyouwillneedtoupdatean

assembly.Youcanupdateanassemblyusingoneoffourways:



1. Maintainthesameassemblyattributes(suchasVersionandCulture)an

assemblyinReportDesignerandSSRSdirectories.Maintainingassembl

keyforthismethodbecausethereport'sRDLcontainsthisinformationi

descriptor.Ifanassembly'sattributeschange,thereportsca

it.Thismethodisthebestforfrequentassemblyupdates,whilemainta

andmethodsignatures.Thismethodofupdatesisespeciallyrelevantdu

andtesting.



2. Updatetheassemblyattributesandupdateallthereferences(usingRep

directlyeditingthetags)toreferencethenewversionofthe



3. Createastrong-namedassembly(seethenextsection,"Strong-named

Assemblies,"formoredetails)andstoreitintheGlobalAssemblyCache

GACallowsmultipleversionsofanassembly.Reportscancallanyofthe

storedintheGAC.Thus,youcankeepbothversionsoftheassemblyan

eitherone.



4. Asinthepreviousmethod,createastrong-namedassembly,storeave

assemblyintheGAC,andforceSSRStoredirectallthecallstothenew

thiscase,anadministratorwouldneedtomodifytheWeb.config

configurationfilestoaddthefollowingentry:











publicKeyTok

culture="...


newVersion="2











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

Chapter 23. How to Create and Call a Custom Assembly from a Report

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

×