Professional Documents
Culture Documents
Me.Write(code)
Home Articles Presentations About
Findthis
T4Tutorial:Creatingyourfirstcodegenerator
PostedbyOlegSych
InformationandLinks
September2,2008 Information September2nd,
T4Tutorial:TroubleshootingCodeGenerationErrors Killingthreebirdswithonestone
CreatingaCodeGenerationScript
n n
NotethatVisualStudiotemplatesintheCodeGenerationfolderareprovidedbyT4Toolbox.Ifyoudont seethemintheAddNewItemdialog,downloadandinstallthelatestversionfromCodePlex.
n n
EnterCrudStoredProcedures.ttastheitemnameandclicktheAddbutton. DoubleclickthenewfileintheSolutionExplorer.Youwillseethefollowingtextinthetexteditor.
C# <#@templatelanguage="C#v3.5"hostspecific="True"debug="True"#> <#@outputextension="txt"#> <#@includefile="T4Toolbox.tt"#> <# //<copyrightfile="CrudProcedureGenerator.tt"company="YourCompany"> //CopyrightYourCompany.AllRightsReserved. //</copyright> #> VisualBasic <#@templatelanguage="VBv3.5"hostspecific="True"debug="True"#> <#@outputextension="txt"#> <#@includefile="T4Toolbox.tt"#> <# <copyrightfile="CrudProcedureGenerator.tt"company="YourCompany"> CopyrightYourCompany.AllRightsReserved.
</copyright> #>
ThisfileisaTextTemplate,alsoknownasaT4Template.TextTemplatesarecodegeneratorsthatcan beusedtogenerateanytextfiles,includingC#,VisualBasic,SQLandXML.TextTemplatesuseASP.NET likesyntaxandconsistoftextblocks,codeblocksanddirectives.Textblocksareblocksoftextinthe templatethatarecopiedtotheoutputfileasis.DirectivesprovideinstructionstothetexttemplatingEngine onhowtoprocessthetemplate.Intheexampleabove,templatedirectivetellstheT4Enginewhich languagethetemplateusesinitscodeblocks.Codeblocks containC#orVisualBasiccodethatruns duringtemplatetransformationandallowmakinggeneratedoutputdynamic. NotethatcolorsyntaxhighlightingforsourcecodeinT4texttemplatesisprovidedbytheTangibleT4 Editor.Ifyouonlyseeplain,blackonwhitetextinVisualStudioeditor,makesuretodownloadandinstall thelatestversionfromTangibleEngineering.
GeneratingStaticOutput
WewillstartimplementingourcodegeneratorbyhardcodingDELETEstoredprocedurefortheProducts tableofNorthwinddatabase.
ChangeCrudStoredProcedures.tttolooklikeso.
WhenyousaveCrudStoredProcedures.tt,theT4 Enginetransformsittogeneratetheoutputfile.Inthe SolutionExplorer,theoutputfileappearsnestedunder thethefile.IfyouareusingVisualBasic,youwillneed toclickShowAllFilesbuttoninthetoolbarofSolution Explorerinordertoseetheoutputfile. Youcanalsotransformthetemplatebyright clickingit intheSolutionExplorerandselecting"RunCustom Tool"fromthecontextmenu.Andifyouhavemultiple texttemplatesinyourproject,youcantransformthem allbyclickingTransformAllTemplatesbuttoninthe toolbar. Thetemplateabovecontainsaprocessingdirective (output)andatextblock.Ifyoudoubleclickthe generatedfile,itscontentswillbeidenticaltothecontentsofthetextblockandwilllooklikeso.
Adding.NETcodetotexttemplate
n
ChangeCrudStoredProcedures.tttolooklikeso
Databasedatabase=newDatabase(server,"Northwind") Tabletable=newTable(database,"Products") table.Refresh() #> createprocedureProducts_Delete @ProductIDint as deletefromProducts whereProductID=@ProductID VisualBasic <#@templatelanguage="VBv3.5"#> <#@outputextension="SQL"#> <#@assemblyname="Microsoft.SqlServer.ConnectionInfo"#> <#@assemblyname="Microsoft.SqlServer.Smo"#> <#@importnamespace="Microsoft.SqlServer.Management.Smo"#> <# DimserverasServer=newServer() DimdatabaseasDatabase=newDatabase(server,"Northwind") DimtableasTable=newTable(database,"Products") table.Refresh() #> createprocedureProducts_Delete @ProductIDint as deletefromProducts whereProductID=@ProductID
Thiscodeuses templatedirectivetospecifythatwhichlanguage(C#orVisualBasic)thistemplateuses initscodeblocks.Thetemplatealsocontainsastatementblockwhichisdefinedusingspecialmarkers <#and#>.Thisblockuses SQLServerManagementObjects(SMO)toretrievemetadatainformationabout ProductstablefromtheNorthwinddatabaserunningonthelocalSQLserverinstance.ThisAPI(SMO)is definedina.NETassembly,Microsoft.SqlServer.SmowhichisinstalledintheGlobalAssemblyCache (GAC)bySQLServersetupprogram.InordertousethisAPI,thetemplateusesan assemblydirectiveto referencetheassemblywhereitisdefinedandanimportdirectivetospecifythenamespacewhere Server, DatabaseandTabletypesaredefined.TheimportdirectiveissimilartotheimportsstatementinVisual BasicandusingstatementinC#.Itallowsthetemplatetousetypesfromthespecifiednamespacewithout havingtousefullyqualifiednames.
MakingCodeGenerationDynamic
Havingmetadatainformationaboutthetargettable,wecannowgeneratetheDELETEstoredprocedure dynamically.
ChangeCrudStoredProcedures.tttolooklikeso.
C# <#@templatelanguage="C#v3.5"#> <#@outputextension="SQL"#> <#@assemblyname="Microsoft.SqlServer.ConnectionInfo"#> <#@assemblyname="Microsoft.SqlServer.Smo"#> <#@importnamespace="Microsoft.SqlServer.Management.Smo"#> <# Serverserver=newServer() Databasedatabase=newDatabase(server,"Northwind") Tabletable=newTable(database,"Products") table.Refresh() #> createprocedure<#=table.Name#>_Delete <# PushIndent("\t") foreach(Columncolumnintable.Columns) { if(column.InPrimaryKey) WriteLine("@"+column.Name+""+column.DataType.Name) } PopIndent() #> as deletefrom<#=table.Name#> where <# PushIndent("\t\t") foreach(Columncolumnintable.Columns) { if(column.InPrimaryKey) WriteLine(column.Name+"=@"+column.Name) } PopIndent() #>
VisualBasic <#@templatelanguage="VBv3.5"#> <#@outputextension="SQL"#> <#@assemblyname="Microsoft.SqlServer.ConnectionInfo"#> <#@assemblyname="Microsoft.SqlServer.Smo"#> <#@importnamespace="Microsoft.VisualBasic"#> <#@importnamespace="Microsoft.SqlServer.Management.Smo"#> <# DimserverAsServer=NewServer() DimdatabaseAsDatabase=NewDatabase(server,"Northwind") DimtableAsTable=NewTable(database,"Products") table.Refresh() #> createprocedure<#=table.Name#>_Delete <# PushIndent(VbTab) ForEachcolumnAsColumnIntable.Columns Ifcolumn.InPrimaryKeyThen WriteLine("@"&column.Name&""&column.DataType.Name) EndIf Next PopIndent() #> as deletefrom<#=table.Name#> where <# PushIndent(VbTab&VbTab) ForEachcolumnAsColumnIntable.Columns Ifcolumn.InPrimaryKeythen WriteLine(column.Name&"=@"&column.Name) EndIf Next PopIndent() #>
Thistemplateuses expressionblocks todynamicallygeneratenameofthetargettableintheoutputfile. Expressionblocksaredefinedusingspecialmarkers<#=and#>andcancontainanyvalid programmingexpression,whichwillbeconvertedtostringandwrittentotheoutputfile.Thistemplatealso usesadditional statementblockstoiteratethroughthelistofColumns andcallsWriteLinemethodto generatestoredprocedureparameterdeclarationsandWHEREclausefortheDELETEstatementbased ontheprimarykeyofthetable.PushIndentandPopIndentmethodsareusedtoformatparameter declarationsandthewhereclause.
Conclusion
ThetexttemplateshowninthisarticlegeneratesasingleDELETEstoredprocedurebasedontable schemainformationretrievedfromSQLServerusingSMO.Inthenextarticle,wewilltalkabout troubleshootingcodegenerationerrors .
Download
n n
Sourcecode,C# Sourcecode,VisualBasic
ReaderComments
WriteaComment
Takeamomenttocommentandtelluswhatyouthink.Some basicHTMLisallowedforformatting.
Writtenby:BFC Postedon:September2,2008at7:33am
Name(required)
WhatIhavetodotohavealltheitems? Thanksinadvance
c d e f g Allowcommentboxtofloatnexttocomments. Typeyourcommenthere.
Writtenby:OlegSych Postedon:September2,2008at8:25am
ImsorryaboutthatBruno.Youprobablygotversion8.8.17.1installed.Iuploadedanewreleaseto CodePlexthismorning,butdidntmakeitdefaultuntilnow.Couldyouinstallversion8.8.31.1?Thisshould
maketheothertemplatesavailableintheAddNewItemdialog.
SubmitComment
Writtenby:Alex Postedon:September5,2008at3:27pm
4
Alex,
Writtenby:OlegSych Postedon:September6,2008at11:19am
Writtenby:PaulKohler Postedon:September16,2008at12:53am
Interesting!Itlooksabitlikecodesmithtemplatesactually
6
Oleg,
Writtenby:JohnCrews Postedon:October12,2008at6:54pm
IwroteanextensiontothestringobjectandIamtryingtouseitina.ttfilebutIgetanerror.Does.tt recongizecustomextensions?
Writtenby:OlegSych Postedon:October13,2008at7:52am
Writtenby:CoreyFurman Postedon:October17,2008at11:49am
Thisseemslikeagreattool IwishitwasavailableforVisualBasic.Net.
Writtenby:OlegSych Postedon:October17,2008at11:55am
ThanksCorey.YoucanalsouseT4withVisualBasic,simplychangelanguageparameterofthetemplate directivetoVBandwriteVisualBasiccodeinthecodeblocks.
10
Writtenby:Igorloginov Postedon:November20,2008at8:27am
11
tutorials.
Writtenby:Igorloginov Postedon:November21,2008at7:20am
Sorryaboutmypreviousquestion.Noproblemnow,justagreatsurpriseHowsimple :)Thanksforthese
12
Oleg,
Writtenby:JohnCrews Postedon:November23,2008at9:51am
13
Writtenby:jeremysimmons Postedon:December9,2008at10:23pm
YoucanpassinaservernameandinstancetotheServerconstructor. InmycaseitwasServerserver=newServer(.\\SQLEXPRESS)
14
Writtenby:KludgeX Postedon:January16,2009at3:32pm
Afterdownloadingv8.12.27.1oftheT4Toolboxandrunningit,theinstallerreportsthatVS2008mustbe installedfirst.However,IalreadyhaveVS2008VBExpressEditioninstalled.WhatamIdoingwrong?
15
Writtenby:OlegSych Postedon:January16,2009at6:34pm
T4ToolboxrequiresVisualStudio2008Standardorhigheredition.EULAforExpressEditionsofVisual Studioexplicitlyprohibitsextensionbythirdpartyaddons.
Writtenby:ecktwo
16
Postedon:January19,2009at4:28am
TheCodeGeneratoritemcategoryisonlyavailableunderVisualc#items. CanitalsobeavailableunderVBitems?
17
Writtenby:OlegSych Postedon:January20,2009at10:34am
18
Alex,
Writtenby:Rich Postedon:January21,2009at7:02pm
Iamnotsurehowfaralongyouareinyouropensourceproject.WhynotjustuseMyGeneration?Itisopen sourceandhasaCodeSmithconverter. RB
19
Writtenby:OlegSych Postedon:January23,2009at6:53am
Willdo,assoonasIstartusingNAntinsteadofMSBuild
20
HiOleg!
Writtenby:hoyoch Postedon:January30,2009at9:20am
21
Writtenby:OlegSych Postedon:January30,2009at9:36am
ItlooksliketheProductstabledoesn thaveaprimarykey.
22
@hoyoch
Writtenby:Jon Postedon:February17,2009at11:50am
YoumightnothavetheNorthwinddatabaseinstalled.
23
Writtenby:Przemek Postedon:March24,2009at5:11am
24
Writtenby:OlegSych Postedon:March26,2009at4:04pm
Thanksforreportingit.Therewasaprobleminbuild9.3.21.1.Getbuild9.3.21.2here.
25
@hoyoch,
Writtenby:JonathanDanylko Postedon:April21,2009at5:44am
Iwasrunningintothesameproblem.Myresultscamebackthesameway. createprocedureProducts_Delete as deletefromProducts where Nokeys,nonothing. IwasrunningSQLServer2005EXPRESSandIrecentlyupgradedtoSQLServerDeveloper. Solution:IuninstalledSQLServer2005Express. SincethisrequirestheMicrosoftSQLServerSMO,SQLServerExpressdoesnthaveit.Onedownsideto havingSQLServerExpress. Noweverythingsrunningjustfine. JD
26
Writtenby:OlegSych Postedon:April21,2009at6:26am
Greatcatch,Jonathan.Thanksforsharingthistip.IwonderifinstallingSMOseparatelywouldhelpaswell.
27
Writtenby:Timeout!!!:Generatesyncframeworkstoredproceduresusingt4templates Postedon:May2,2009at3:33am
[]themsdnsitebuttoactuallygetproductivewithT4andtoseesomesamplecodeinactionvisitthis postonOlegSychsblog.Alsogothroughthevariousarticlesonhisblog,hesdonesomepretty[]
28
Writtenby:ClarkSell:T4TextTemplateTransformationToolkit Postedon:May31,2009at10:12pm
[]OlegSychsblogandespeciallyT4Tutorial:CreatingyourFirstCodeGenerator[]
29
Writtenby:ML Postedon:June16,2009at9:26am
WithVisualStudioTeamSystemSP1,
30
Oleg,
Writtenby:ms440 Postedon:July23,2009at11:57am
31
Writtenby:OlegSych Postedon:July24,2009at5:25am
32
All
Writtenby:MarkKamoski Postedon:August5,2009at7:05am
ThisisatipforT4neophyteslikeme. IfyouarehavingtroubleconnectingtothedatabaseinyourTTtemplate forexample,ifyougetthisCTE Runningtransformation:Microsoft.SqlServer.Management.Smo.FailedOperationException:SetParent failedforDatabaseNorthwind thentrychangingfromthis Serverserver=newServer() tosomethinglikethis Serverserver=newServer(@YouServerName\SQLEXPRESS) andthatmighthelp. Itworkedforme. (Itisabigsmallthing.) HTH. Thankyou. Mark
33
Writtenby:MarkKamoski Postedon:August11,2009at11:36am
34
Writtenby:Ron Postedon:August11,2009at6:12pm
35
Writtenby:OlegSych Postedon:August12,2009at6:11am
Ron,WhicheditionofVisualStudio2008doyouhaveinstalled?DidyouinstallT4Toolbox?
36
Writtenby:AlfredMyers Postedon:September10,2009at3:40pm
37
Writtenby:SalvatoreDiFazio Postedon:October17,2009at11:33am
HiIhadinstalledtheT4EditorandtheT4Toolbox,butIhaventtheCodeGenerationoption. Tnxinadvance
38
rusty!
Writtenby:OlegSych Postedon:October17,2009at1:48pm
Allright,holdon.ImgoingtoperformaVulcanmindmeld StillworkingStillworkingOhman,Imtoo
Seriously,Salvatore,couldyouhelpmeouthere?WhatistheversionandeditionofVisualStudioyouare using?WhichversionoftheT4Toolboxdidyouinstall?Whattypeofprojectdidyoutrytouse?
39
Writtenby:SalvatoreDiFazio Postedon:October17,2009at2:32pm
Thankyou:)
40
HiOleg
Writtenby:JustinSpaey Postedon:November9,2009at3:41pm
41
Writtenby:OlegSych Postedon:November9,2009at5:57pm
Wecanonlyspeculate.Ifyouneedtosolveaparticularproblem,CodeSmithmaystillbeabetteroptionifit providesareadytousesetoftemplatesyoucanuseinsteadofbuildingthemyourselfinT4.
42
Oleg,
Writtenby:GeoffBrown Postedon:November13,2009at10:16pm
43
Writtenby:OlegSych Postedon:November14,2009at8:33am
ThanksfortheheadsupGeoff.IhaverenamedtheFileitemtemplateintoScriptawhileback,butforgot toupdatethisarticle.
44
Writtenby:salman Postedon:November30,2009at5:24pm
Irolledmyownversionofthisbyjusthookingintosqlserversbuildinprocedures.IwishIranintothis postearlierhehe.