Professional Documents
Culture Documents
ApplicationGenerationfor.NET
AlanS.Fisher Somethingsarejustfaster.
Copyright20042005,IronSpeed,Inc. Allrightsreserved. IronSpeedandtheIronSpeedlogoareregisteredtrademarksofIron Speed,Inc. Nopartofthisbookmaybereproduced,storedinaretrievalsystem, ortransmittedbyanymeans,electronic,mechanical,photocopying, recording,orotherwise,withoutwrittenpermissionfromtheauthor. IronSpeed,Inc. 2870ZankerRoad,Suite210 SanJose,CA95134 (408)2283400 www.ironspeed.com FirstEdition,March2004 SecondEdition,May2005 ISBN0975269747
Acknowledgements
IdliketoacknowledgePaulGustafsonforassemblingandediting thisbook.Hishardworkkeptusfocusedonourmissionand ensuredahighlevelofintegrityofcontent. IdalsoliketoacknowledgeStephanieMillerforcontributing materialthatledtothisbookandforcontinuallyencouragingmeto starttheprocess. EricRollins,anauthorityoncodegenerationandcoauthorofCode GenerationinAction,providedmanyinsightfulcommentsand helpfulsuggestions. SamsonWong,ourgraphicdesignerextraordinairecreatedallthe screenshotsandmanyotherillustrationsinthesecondedition. RaziMohiuddincontributedanumberofexamplesandmaterialon techniquesforextendingapplicationgenerators.MichaelCompton andseveralotherIronSpeed,Inc.teammembersprovideddetailed reviewoftheexamplesandotherinput. Thankyouall!
TableofContents
Acknowledgements............................................................................................................................................3 TableofContents ...............................................................................................................................................4 Foreword ..............................................................................................................................................................9 Part1)TheCaseforAutomation ...................................................................................................................12 TheChallengesofWebApplicationDevelopment................................................................................... 14 ThreeTieredArchitectureComplexity......................................................................................... 15 UserInterfaceComplexity .............................................................................................................. 16 DatabaseManagementComplexity .............................................................................................. 18 ScalabilityComplexity..................................................................................................................... 18 SecurityComplexity ........................................................................................................................ 19 Complex,YetBoring,Development.............................................................................................. 19 StandardsMakeApplicationGenerationPossible .................................................................................. 20 UserInterfaceStandardization....................................................................................................... 20 DatabaseStandardization ............................................................................................................... 20 ApplicationIntegrationStandardization...................................................................................... 21 Part2)AutomatingDevelopment:AHistoricalPerspective ...................................................................22 TheEvolutionofAutomatedSoftwareDevelopment .............................................................................. 23 The1980s:IDEs .............................................................................................................................. 23 The1990s:ApplicationServers .................................................................................................... 24 ModernRequirements..................................................................................................................... 25 Today:ApplicationGenerators..................................................................................................... 26 UML&MDAPoorAlternativesforMostDevelopers ............................................................ 27 TheEmergenceofIterativeDevelopment ................................................................................................ 29 Part3)DevelopmentAutomationinAction:CommonProblemsSolved ............................................31 AutomateC/R/U/DPageCreation...................................................................................................... 32 ComplexDisplays.................................................................................................................................... 35 UsingDataGridstoManageLargeResultSets ..................................................................................... 37 AutomaticDataValidation&Display.................................................................................................... 39 DeliveringaCommonRequest:ExportingApplicationData................................................................. 40 Summary ................................................................................................................................................. 41
Part4)Goals&BenefitsofAutomatedDevelopment...............................................................................42 WhatShouldanApplicationGeneratorDo? .......................................................................................... 43 StartingfromScratch:TheApplicationSpecificDataModel .................................................... 44 TheVeryFirstStep:AFunctional,BugFree,Application ......................................................... 44 CodeCompleteness&Organization ............................................................................................. 45 ExtendingtheCodeGeneratorItself(AutomatedCodeReuse)................................................ 45 CharacteristicsofGoodGeneratedCode...................................................................................... 47 ImplicationsforDevelopmentMethodology............................................................................................ 48 GatherFeedbackEarly&OftenintheCyclewithRealSoftware ............................................. 49 UseBusinessAnalyststoDevelopPrototypes............................................................................. 50 SimplifySoftwareMaintenance ..................................................................................................... 51 CustombuildtheUniqueAspectsofyourApplication............................................................. 51 KeyBenefitsofApplicationGenerationMethodology............................................................................. 52 SpeedDevelopmentandReduceTestingTime ........................................................................... 52 EnableCorporateComputingStandards...................................................................................... 53 Automated,YetRobustUIBringsApplicationPowertoLight ................................................ 54 Scalability .......................................................................................................................................... 55 BoostYourCompanysROI............................................................................................................ 55 KeepDevelopmentInhouse .......................................................................................................... 56 Part5)HowAutomatedDevelopmentWorks............................................................................................59 ApproachestoApplicationGeneration.................................................................................................... 60 TheMDA/UMLPhilosophy ........................................................................................................... 60 TheAlgorithmicApproach............................................................................................................. 60 TheDeclarativeMethodPhilosophy............................................................................................. 60 SpecifyinganApplicationsBasicFunctionalitywithCodeGenerationTags......................... 61 WhatDeclarativeMethodApplicationGeneratorsCreate ........................................................ 62 ConnectingWebPagesandDataboundControlstotheDatabase.......................................... 65 CustomizingGeneratedApplications........................................................................................... 66 UsingDeclarativeMethodstoSpecifyanApplication........................................................................ 67 LayoutPages..................................................................................................................................... 67 HowCodeGenerationTagsWork ................................................................................................ 68 LinkingDatabaseTables,ViewsandQueriestoanApplication............................................................. 75 TheComponentBindingProcess................................................................................................... 77 SourcingFromParentsRecordorCurrentRowinaTable....................................................... 79 AddingaNewRecordtoaDatabaseTable.................................................................................. 81 TheApplicationGenerationProcess ....................................................................................................... 82 PresentationLayerGeneration....................................................................................................... 83 ApplicationLayerGeneration........................................................................................................ 84 DatabaseLayerGeneration............................................................................................................. 85 BonusAutomation(EvenMoreCodeYouDontHaveToWrite) ......................................................... 85 SearchTools ...................................................................................................................................... 86 DataSorting&PageNavigation.................................................................................................... 87
Import&ExportFacilities............................................................................................................... 87 ExceptionandErrorManagement................................................................................................. 88 Summary ................................................................................................................................................. 89 Part6)AutomaticSQLGenerationforDatabaseConnectedControls ..................................................90 Meeting&ExceedingUserExpectations................................................................................................ 91 SQLEfficiency......................................................................................................................................... 91 TransactionModel&TransactionManagement .................................................................................... 92 LocationoftheSQLStatements .............................................................................................................. 94 Inline(Embedded)SQL ................................................................................................................. 94 StoredProceduresEnhancePerformance&Maintainability..................................................... 94 GeneratingStoredProcedures ....................................................................................................... 95 DatabaseViewsProvideDataConsolidation .......................................................................................... 96 PrimaryKeyRelationshipsPermitRecordEditing................................................................................. 97 ForeignKeyRelationshipsPermitMultiTableJoins.............................................................................. 98 ConcurrencyControl/ConcurrencyHandling .................................................................................... 100 PessimisticConcurrency ............................................................................................................... 102 OptimisticConcurrency ................................................................................................................ 102 ConcurrencyHandlinginGeneratedApplications .................................................................. 103 CursorManagement.............................................................................................................................. 103 DataRecency .................................................................................................................................. 104 DataManagement.......................................................................................................................... 104 DatabaseCursorsinGeneratedApplications ............................................................................ 104 Summary ............................................................................................................................................... 105 Part7)AutomatingApplicationSecurity...................................................................................................107 GeneratingRoleBasedApplicationSecurity ........................................................................................ 108 SimpleSigninAuthentication ..................................................................................................... 109 SingleRoleAuthentication ........................................................................................................... 110 MultipleRoleAuthentication....................................................................................................... 110 SecuringYourGeneratedWebApplication .......................................................................................... 111 CreatingUserAccounts ................................................................................................................ 112 CreatingUserRoles ....................................................................................................................... 113 ConfiguringYourWebPagesforRoleBasedSecurity............................................................. 114 ConfiguringSignInPagesforYourApplication ...................................................................... 114 SigningIntoYourApplication&ManagingLostPasswords.................................................. 115 AdditionalSecurityIssuestoAddress................................................................................................... 116 AutomaticSignout........................................................................................................................ 116 DataTransmissionEncryption..................................................................................................... 116 ImpliedSecurityfromanNTierArchitecture........................................................................... 116
ActiveDirectoryandLDAP ......................................................................................................... 117 PasswordStorage........................................................................................................................... 117 HandlingSQLInjectionAttacks .................................................................................................. 118 Part8)ExtendingandCustomizingApplications ....................................................................................120 StandardsforGeneratedCode ............................................................................................................... 122 WellorganizedCode..................................................................................................................... 122 CodeShouldMeetProfessionalStandards ................................................................................ 123 AvoidsCodeOrphaning............................................................................................................... 124 AnApproachtoGeneratingExtendableCode....................................................................................... 125 Example:ChangingthePresentationLayer ......................................................................................... 126 Example:AddingCustomDataValidationCode.................................................................................. 128 EveryUsersRequest,Canyouaddabuttonthat?....................................................................... 131 CommonButtonActionsandProperties.................................................................................... 131 PassingPrimaryandForeignKeyValuesinURLs .................................................................. 133 Example:AddingReportingtoaGeneratedApplication ....................................................... 137 Localizing(Internationalizing)YourApplication................................................................................. 143 Summary ............................................................................................................................................... 145 Part9)AutomatingITStrategies .................................................................................................................146 AutomatingPageProduction................................................................................................................ 147 WhatsinaPageTemplate?.......................................................................................................... 151 AutomaticReuseofASP.NETDirectivesinPageTemplateFiles ......................................... 156 APragmatic,YetRevolutionary,ApproachtoCodeReUse ................................................................ 158 AutomatingCodeReUsewithPanels&Components ............................................................ 159 ButtonPanels .................................................................................................................................. 161 GeneratingNavigationMenuPanels .......................................................................................... 164 GeneratingDynamicContextSensitivePanels ......................................................................... 169 AutomatingReUseofCustom&ThirdPartyControls ...................................................................... 174 Example:IntegratingaThirdPartyControl.............................................................................. 175 Example:IntegratingaThirdPartyControlwiththeDatabase ............................................. 176 Summary ............................................................................................................................................... 180 Part10)LookingAhead .................................................................................................................................181 SelectingYourFirstProject .................................................................................................................. 182 FirstEffortCaseStudy:OtisElevator ................................................................................................. 184 FirstEffortCaseStudy:LesSchwabTireCompany ............................................................................ 187 FirstEffortCaseStudy:OpenLatitude................................................................................................ 189 FirstEffortCaseStudy:TexasYouthCommission.............................................................................. 191
OrganizationalRolloutofApplicationGenerationTechnology............................................................ 192 BasicRolloutEssentials ................................................................................................................. 192 AdvancedPlatformPossibilities .................................................................................................. 193 EnablingaNewKindofDevelopmentTeam ............................................................................ 194 TheNewReality:CompetitiveAdvantageRequiresUbiquitousCustomSoftware............................. 195 TheRiseofNanoApplications................................................................................................. 195 TheApplicationGenerationFuture ............................................................................................ 197 ContactIronSpeed .........................................................................................................................................198 AbouttheAuthor............................................................................................................................................199
Foreword
TheIronSpeedfoundersandmanyofourkeyexecutives conceived,built,grewandmadeprofitableoneofthelargestand mostsuccessfulonlinestoresatOnsale,Inc.(whichlateracquired Egghead.com,andisnowpartofAmazon),growingthecompanyto arunrateofover$600Minannualsales.Thelessonslearnedthere duringsixyearsoftorridgrowthinspiredthecreationofIronSpeed. MypartnersandIstartedOnsalebackin1993asanonlineauction houseforallsortsofexcessandoutofstockmerchandise.There werenoecommerceoperationstoemulate,sowetookatripto MinneapolisthemailordercapitaloftheUSforaplanttourof Damark,Inc.,whichspecializedinconsumerelectronicsandhouse wares(whatwecalledbigtoysforbigboys)andhadabout$500 millioninsales. Wegotbackontheplanetocomehomethinkingthattobe successfulinmailorderyouneededaleanexecutivestaff,ahuge roomofpeoplewithheadphonestakingorders,andawarehouse fullofotherpeopleloadingboxes.Itstruckusthatecommercewas exactlythisoperationminustheheadphones.And,wewerehoping thatsincewewerenotmanufacturinganything,thatwewouldbe abletohaveaverysmallwarehouseandnevertakepossessionof mostoftheitemsthatweshipped. Thatmeantthesoftwarehadtoreplacetheroleoftheordertaker, andcustomerservice,a.k.a.:theheadphones.And,thesoftwarehad tointegratewithoursuppliers.Wethoughtitwouldtakenomore thanfiveortenengineerstobuildandmanagethewholething.We thought,Howcomplexcanthissoftwarebe?Afterall,e commerceisbasicallyadatabaseapplicationasetofpages,input forms,andSQLqueries. Bytheendof1999,wehadanITstaffofabout110peopleand65 modulesofsoftwarethataddressedeverythingfromordertakingto bidtrackingtoemailnotificationtosupplierinventorymanagement totroubletickets. Wehadbecome,inessence,agiantwebbasedERPsystem,perhaps thefirstofitskind.Everythingwasheavilyautomatedsalesto fulfillmenttovendors.Itworkedlikeacharmandwasathingof beauty,handlingover12,000orders,500,000customertransactions, andsending750,000emailupdateseachdayoftheweek.
But,howdidwegetsobigintheengineeringdepartment?Those65 modulescameaboutfromourdesiretoautomate.Youdthinkthat wouldmeanwedhaveveryfewpeopleandlotsofcomputersdoing allthework.Well,everybusinessprocessthatcouldbemademore efficientandthuseveryefforttoimprovemarginsbecameanewIT project.Oncethemoduleswerebuilt,ofcourse,theyhadtobe maintained.Andtheyhadtoworkwitheachother,whichrequired moreengineering.And,everysingleaspectfromdevelopmentto integrationtomaintenancerequiredadifferentsetofskillsanda dedicatedteam. Anexample:Ouroriginalcustomerservicesystemcomprisedof phoneandfaxandalotofemail!neededanoverhaulabouttwo yearsintoourhypergrowthphase.Irememberaparticularly painfulholidayseasonwherethenumberofcustomerservice requestsrosewiththeburstinsalesvolume.Wewereswamped withorders,experiencingshippingdelays,vendorswerefailingus, andeverythingseemedtohappenatonce.Soofcoursetherewere lotsofcomplaintsviaphone,faxandemail.Becauseourcustomer servicesystemwasdependentonmanualprocessestolinkthe paper,voiceandelectroniccomplaints,wehadanearmeltdown. Somecomplaintswereprocessedtwice,andallcomplaintswere handledslowly. Weneededacustomerselfservicesystemforroutinerequests,as wellasonepointofaccessforthehistoryofallcustomersto eliminateredundantrequestsandincreaseproductivity.Wealso wantedanemailalertsystemtokeepcustomersapprisedofthe statusofwinningbidsandtheirorderssotheydidnthavetocallus foranupdate. Webuiltitoverseveralmonthsandrolleditalloutwithhuge success.Thatsameyearweenjoyedafourfoldincreaseinbusiness, butwekeptthesamenumberofservicereps(about14)solelydue toautomation. Thenthefundevelopmentworkstarted.Themoreweusedthe system,themorewewantedtoimproveitandcustomizeitforthe particularneedsofourbusiness.Sothenweneededateamof engineerswhowerespecialistsintheseapplicationstogrowitand supportitandlinkitwithotherinternalandpartnersystems. Youcanseehowwegotto110peopleprettyquickly.Although, eveninmymosthonestofmoments,Ibelievewewereasefficientas possibleandeveryoneworkedveryhard.Therewasnofatthere. Coulditbe,wethought,thatitjusttakesahundredpeopleand almostfivedozensoftwaremodulestorunanebusiness?Yikes!
10
Well,theansweristhatitdoesifyoubuildeachmoduleasan island.Thisiswhattraditionalengineeringwisdomdictated.But withthatwisdominmind,weareshatteringthelegendatIron Speed.Webelievethatwithanunderlyingplatformarchitecture thatsupportsallthoseapplications,wecansavetimetomarket, moneyanddevelopmentcosts. Whatdoweknownowthatwedidntknowthen?Thekeyisthat mostofthemodulesandtheiroperationatOnsalewasnot complicatedlogicorcalculationitwastakingdata,processingit, anddisplayingitinadifferentformtosomeoneorseveralpeople.I havetoconfessthatoutofalmostamillionlinesofcodethatmade upthose65modules,thesecretsaucewasonlyasmallfraction maybe20,000linesofcodeonwhichweheldseveralground breakingpatentsforonlineauctiontechnology.Therestwassimply movingdatainandoutofformsanddatabases,andtranslatingitso itcouldintegratewithotherCustomerRelationshipManagement (CRM)andSupplyChainManagement(SCM) Systems. Thoselessonsmandatesomeofthefundamentaltenetsweuseat IronSpeedtobenefitrapidlygrowingcompanieslikeyours: Dataintensiveapplicationsarenotcomplicatedtobuild,but theyareuniqueforeverybusiness. Allfunctionalitymustbeflexibleandextensibletogrow withthebusiness.
11
Part1) TheCaseforAutomation
Marketandtechnologytrendspointto automationastheanswertomanymodern webdevelopmentchallenges.
12
LikesomanyITprofessionals,wevespentthousandsofengineering manhoursfiguringouthowtobuildpowerfulnewwebbased applicationsaswellasmigratingexistingclientserverapplications totheweb.Wevealllearnedtobuildwebapplications,andweall knowtheseprojectsareharderandmorecomplexthanbuilding clientserverapplicationseverwere. Ontheweb,theuserinterfaceincludesoptionsforstatesyoucant control.And,thestatelessclientisfarremovedfromthedatabase, soeachtransactionisadistinctrequest.Additionally,web applicationsmustalwaysalsoincludeprovisionsfordatabase connectionpooling,sessionmanagement,scalabilityand authentication. Thebenefitsweveallheardrelentlesslytouted aboutwebapplicationsthoseofsimpler deployment,improvedinteroperabilityandeasier integrationaresofarremovedfromtheearly planninganddevelopmenttasksthattheyhardly seemtomatter.Really,whoisthinkingaboutthe benefitsofwebservices,SOAP(SimpleObject AccessProtocol)andXML(extensiblemarkup language)whenhesstrugglingtocorrectthecode surroundingthe50thSQLqueryinamultitier application? Thereisabetterway.
Enterprise applications for CRM, product catalogs, supply chain and partner management, and employee-HR portals, are being launched on the Web for easier access, improved service, stronger version control and increased inter-operability.
Anewcategoryofsoftwarethatwecall applicationgenerationsoftwaregeneratesthe majorityofanapplicationscodefasterandmoreefficientlythan traditionalhandcodingapproaches.But,takingadvantageofthis opportunitymeanssheddingthetraditionalclientserver developmentapproachinfavorofawebbasedapplication developmentstrategy. Thisbookdiscussesthechallengesaswellaspossibilitiesofbuilding webapplications;explorestheemergingcategoryofapplication generators;andintroducesthebreakthroughmethodologyfor acceleratingapplicationdevelopmentinventedbyIronSpeed.Later chaptersexplaintheprocessdetailsandunderpinningsofthe approach,andhowmodificationsandextensionsaremanaged.
13
TheChallengesofWebApplicationDevelopment
EverycorporateITdeveloperisfamiliarwithclientserver applicationdevelopment.Thetwotieredarchitecturetypically includesathickclientandathickserverthatruninacontrolled environment.Theclientserverarchitectureformedthebackboneof enterprisesoftwarefordecades. Developingwith clientserver architecturegives youlotsoffreedom toplaceheavy burdensontheclient side.Thereisno needtopingthe databaseforevery transaction,asyou canhouse functionalityand dataintheclient itself,greatly reducingtheneedto scaletheserverside softwareand database.
Runs application software, handles transactions, and provides scalability and access control.
App1
App2
Server
Database Database
Buttoday,everythingismigratingtotheweb.Asaresult,ITnow facesthechallengesofbuildingnewapplicationsfortheweb,and migratinglegacysystemstotheweb.Atfirstblush,webbased applicationssoundgreatbecausetheysaveondeploymentand training.But,betweenthestartoftheprojectanddeploymentofa productionsystem,awholelotofdevelopmentworkaddsseveral layersofcomplexitytotheapplicationdevelopmentcycle. Webapplicationdevelopmentputsthedeveloperinacompletely differentdevelopmentscenario: Webapplicationsarefundamentallydifferent.Theyare threetiered,withathinbrowserclient,arobustapplication serverandadatabase. HTMLisathinclientsomostofthewebapplicationheavy liftinghastohappenattheapplicationserverlevel, includingtheapplicationworkflow. HTMLbaseduserinterfaceslacktherobustnessofdesktop windowingenvironments,likeMicrosoftWindowsandthe
14
AppleMacintosh,makinguserinterfacedevelopmentmore difficult. Webapplicationsarestateless,sotheyrequirecomplex sessionmanagementinordertoimplementcomplex transactions.TheHTMLclientisreallydesignedfordisplay (andnottransactions),sotheapplicationserverlayermust pickupthebulkofthecoordinationandmanagementof databasedriventransactions. Duetotheirrelianceonstandardprotocols,webapplications arefrequentlyexposedtothepublicInternet,andsomust accommodatetightsecurityandaccesscontrol.
Althoughwebapplicationsareintendedtooperateasstandalone systems,theyfrequentlyrelyontheoperationandconnectionwith otherwebapplicationsandwebservices.Ultimately,someofthose interconnectionsmaybebetweenenterprises,andlosethe protectionofthenetworkfirewall. Thatisaverylonglistofchallenges,evenwhenbuildingwitha favoriteprogramminglanguagelikeC#,C++,Java,orVisualBasic. Comparingclientserverapplicationstowebapplicationsandweb servicesislikesayingaMorrisMiniandaBMWarebothcars.Both getyouwhereyouneedtogo,butliftupthehoodandoneisclearly morecomplicatedthantheother.Webapplicationsaremore complextodevelopthanclientserverapplicationsbecausethey includemoreinfrastructure,morefeatures,moreconnections,anda morecomplexruntimeenvironment. Applicationgenerationtechnologyspeaksdirectlytothispoint: buildingwebapplicationsfromthebaremetaliscomplexandtime consuming.Acceleratingthedevelopmentcyclewithoutsacrificing performance,featuresandinteroperabilityarethekeymetricsby whichapplicationgenerationsoftwareisbeingmeasured.
ThreeTieredArchitectureComplexity
Specifically,thethreetieredarchitecturecreatesnewchallengesfor developersinseveralareas:creatingthewebbaseduserinterface, providingapplicationinfrastructure,databasemanagement, scalabilityandsecurity. Traditionalclientserverapplicationsdidnthavetoworryabout thosethingsnearlytothesamelevelaswebapplications. TheBrowserClientTier:HTMLisreallydesignedtodisplay contentandisnotrobustenoughtohandlecomplexenterprise
15
transactionmanagement.Javascripting,richmediaandactive server/javaserverpagesbringthelanguageforwardtowardsimple interactivity,butclearlyHTMLisalongwayfromtherobust, controlled,desktopwindowingenvironmentofclientserver applications.Thisforcesallthecodingandinteractionsthathappen attheclientlevelintraditionalapplicationsfurtherdownyour applicationarchitecture. TheApplicationServer:Muchofthefunctionalityfoundinthe clientlayerofaclientserverapplicationisnowpushedtothe applicationserverlevelforwebapplicationsanexpandedrolefor thetraditionalservertierthatnowsitsbetweenthethinHTMLclient (notdoingmuchmorethandisplayingthe userinterface)andthedatabase.Thenew applicationservertierliterallypowerseach webapplicationandwebservice. Backintheolddays,thiscomplete infrastructurecouldbebuiltindependently andfromscratchforeachapplication.Of coursewedidntknowtocallitanapp server,butwewouldbuildafoundation layerthatsupportedotherfunctionality. Whileanapplicationserverprovidessome ofthethingsyouneed,itisntcentralto yourdevelopment,andsoitcanttakeyou quitefarenoughforyourwebbased applicationneeds.
Users expect a certain threshold of functionality and user interface look and feel. Appreciated features like navigation, search, pagination and table sorting can each take weeks to develop.
TheDatabaseTier:Webbased applicationsseparatethedatabase completelyfromtheserverlayerinordertoallowcontinuousand nonsynchronizedrequeststobetransferredthroughthenew ApplicationServermiddletier. InastatelessenvironmentlikeHTTP,eachseparatetransaction mustloginandoutofthedatabase.Asmanywebapplicationsare outwardfacingtowardcustomers,employees,partnersorsuppliers, atransactionnowincludeseverythingfromconfirmationpage viewstoorders,requestsandbids.Thus,theloadonthedatabase getsprettybigprettyquickly.Theemergenceofwhatwetodaycall applicationserverswasadirectefforttomitigatethisneedfor databaseconnectionpooling.
UserInterfaceComplexity
Handinhandwiththecomplexityofstatelesstransaction processingistheuserinterfacedevelopment.
16
HTMLisacomparativelylowfunctionalityuserinterfacerelativeto aWindowsorMacintoshenvironment.Thatglossymagazinefeel ofanHTMLuserinterfaceismisleading.WhileHTMLisgreatfor presentingstaticpages,therichinteractionthatwedesirein enterpriseapplicationsismissing.Additionally,andperhapsasa resultofthatglossylookandfeel,thereisaddedpressureon transactionbasedapplicationstobemoreuserfriendlyand forgiving. ConsiderthedifferencebetweenthewebandaMicrosoftWindows applicationlikeExcelorOutlook. InWindowsapplications,multistepprocessescanbeperformed withinasingleapplicationscreen.Forinstance,youcandragand dropanemailfromonefoldertoanother.Thisfunctionalityisnot possibleinHTML,norcancomplexitybestructuredasconveniently asinacontrolledclientserverapplication.InWindows,complex functionalitylikefindandspellcheckishandledwithapopup windowthatkeepstheoriginalscreeninview.Thatsortof functionalityhastobehandledonthewebviaaseriesofstaticpages thatonlymimicwhatisafluidandsimpleuserexperienceonthe desktop.Althoughthewebexcelsatlowervolume,lower complexitytransactions,thosearenotalwaysthetypesof transactionsrequiredbyhighuseenterpriseclassapplications. HTMLfallsshortwhenyoutrytooffertheselectionchoiceof anythingmorecomplicatedthanadropdownmenu.Seemingly simplefeaturesthatarecommonplaceonmostwebapplicationscan takeweekstodevelopsearch,tablesorting,paginationand hierarchicalnavigation.Thosefeaturesaremorethannicetohave, theyareexpected. Yourusersdontseethecomplexityofyourapplicationcode;they onlywantapremierexperience.Theywanttochangetheirown accountinformation;changetheirmindhalfwaythrougha transactionandsaveonlytherelevantfields;ensureonecustomeris forbiddenfromseeinganothercustomersdataandtheywantall thepagestoloadinunderthreeseconds. Makingmattersevenmorechallenging,todaysapplicationusersare familiarwiththewebandwithsophisticated,highlyintelligent formsandnavigationfeatures,andwantsimilarfeaturesintheir businessapplications.Mostdevelopersdreadtheinclusionofthese features,suchaspaginatedreports,hierarchicalnavigation,filtering, andfulltextsearch,becausetheamountoftimetheytakeupisnot proportionaltothechallengeorinteresttheycreate.Still,becauseof theirpervasivenessontheweb,thesefeaturesarenowpartofanew
17
baselineoffunctionalitymostendusersexpectinanywebbased application.
DatabaseManagementComplexity
Inawebapplication,databasemanagementconcernsmanifestin twokeyareas:usersessionmanagementanddatabaseconnection pooling.Sincetheverynatureofawebapplicationisstateless,there isagreatneedtomanagetransactionintegrity A web browser client cant tell andcompletion.Webapplicationsrequirean when a user is logged out once environmentthatsupportsthecreationand the transaction has begun. In managementofprocessesbuiltfromthese essence, every transaction statelesstransactions. even in a multi-transaction process is potentially a unique Intraditionalclientserverapplications,a session. sessionwasstraightforward:theuserlogged in,stayedin,andthenloggedoutwhenthey closedtheapplication.Theentiresession loggedinoncetothedatabase.Inthestatelessenvironmentof HTTP,thereisnosuchthingasacontrolledsession.Aweb browserclientcanttellwhenauserisloggedoutoncethe transactionhasbegun.Inessence,everytransactionevenina multitransactionprocessispotentiallyauniquesession. Anewwayofmanagingthedatabaseconnectionsisobviously requiredtosupportthisstatelesssessionenvironment.Web applicationservershandlethisbymaintainingapoolofdatabase connectionskeepingopenanumberofconnectionsandreusing themforeachtransactionrequest.Thiswayrequestsfrommultiple usersaswellasmultiplerequestsfromindividualusersregardless oftheordertheyarereceivedcanbehandledwithoutrepeatedly logginginandloggingoutofthedatabase. Functionstoaddresstheseissuesarebestcentralizedandmanaged asaseparatecollectionoffunctionsontheirownmachines.An applicationservermiddletierisasecondgenerationapproach, recognizingthatmuchmoresupportisneededthanwithclient serverapplications.
ScalabilityComplexity
Sincewebapplicationsareintendedtoscaletoenterpriseoreven interenterpriselevels,scalabilitymustbeensured. Inclientserverapplications,applicationscalabilityismanaged primarilythroughtheclient.Eachenduserrantheclientside applicationonadesktopmachine,sonoextracomputing horsepowerwasneeded.Andsincesomuchoftheapplication
18
functionalitywasfullycontainedintheclientside,therewasntas muchconcernaboutscalingapplications. Inwebapplications,theentireapplicationfunctionalityis concentratedinthenewmiddlelayer,runningontheapplication server.Thisapplicationservergivesyouthescalabilityyouneedto haveonedatabasesupportmultipleapplicationsandmultiple servers.Now,theapplicationcodehastoscaleaswellassupport multipleusers.Fiscally,webapplicationsaremoreexpensive,since applicationservermachinesandsoftwarearenowrequiredtorun them.Noneoftheapplicationfunctionalityrunsonthedesktop machineanylonger. Thereisabenefit,however.Thestrategyofmanagingscalabilityat theapplicationserverlevelletsyouenablemultipleservermachines torunyourapplicationsandprocesstransactionsagainstasingle, centralizeddatabase(thedatabasetier).Itsmuchmoredifficultto createamultimachinedistributeddatabasearchitectureinaclient serverdevelopment,socreatingscalabilityattheapplicationserver tiererasesthatconcern.
SecurityComplexity
RunningonthepublicInternetmeansthatbynatureyour applicationsandtheunderlyingdatabasesthatdrivethemare exposedtoincreasedlevelsofrisk.Thisrequiresincreasedattention andsupportforsecurity.Evenintranetonlyapplicationsrunon standardIPprotocols,whichareeasiertohack.Securityisatopof mindconcernateverystepofwebbasedapplicationdevelopment anddeployment. Multiplelayersofprotectionareneededfromboththeapplication itselfintheformofauthenticationanduseraccesscontrol,aswellas fromyournetworkfirewallandothersecuritymeasures.
Complex,YetBoring,Development
Inmanysoftwaredevelopmentscenarios,engagingwithcomplexity canbe,onanintellectualplane,exhilarating.Insuchscenarios,it canbeextraordinarilysatisfyingtogetsomethingtowork.Such satisfactionisparticularlysweetwhenthesolutionisparticularly elegant,timely,orvaluable. Inbuildingwebapplications,however,theresnotmuchgloryin makingsureyourC/R/U/D(Create/Review/Update/Deleterecord) pagesarecomplete,yourdatabasescales,gettingyouruserroles right,andmakingsureyourUIworksandisintuitive.Beyondthe initialphaseofdecidingwhatsneeded,theworkofbuildingthe
19
StandardsMakeApplicationGenerationPossible
HowcanITdepartmentsbuildtheseincreasinglycomplexweb basedapplicationswiththeincreasinglypressuredandlimited resourcesoftoday? Theanswerisapplicationgeneration. Andwhatmakesapplicationgenerationpossiblenowwhensomany attemptsinthepasthavenotsucceeded? Theanswerisstandards. Whileapplicationsusedtohavetoaccommodatesomanydifferent platforms,today,standardizationisappearinginmanyareas.This makesiteasiertogeneratesubstantialportionsofanapplication.
UserInterfaceStandardization
Duringthelasttenyears,theenduserinterfaceenvironmenthas becomestandardizedwithHTMLwebbrowsersbecomingtheclient interfaceofchoice.Fordesktopapplications,MicrosoftWindows remainsthedefactochoiceforcorporateenvironments. Standardizingtheuserinterfaceenvironmentmakesiteasierto generateuserinterfacecodethatrunsonalmostanymachineatany location,especiallyifitsHTML. Moreover,mostusersseethewebbrowserwithitsabilityto combinerichtextandgraphicswithtraditionaldatadisplayand formbasedinputasafriendlier,moreintuitiveuserinterfacethan traditionaldesktopwindowingmetaphors.Infact,mostofthemajor ERPandCRMvendorshaverewritten,orareintheprocessof rewriting,theirapplicationsfortheweb.Itwontbelongbefore mostotherapplicationsfollowsuit.
DatabaseStandardization
Mostenterpriseapplicationsstandardizedoverthelast20yearsto operateonSQLbasedrelationaldatabases.Morerecently,database middlewarelikeODBCandJDBCmakeiteasiertoretarget applicationstodifferentdatabases(e.g.,OracleandDB2)without
20
ApplicationIntegrationStandardization
Morerecently,SOAPandXMLarebecomingestablishedas applicationintegrationstandards,andmakeitpossibletodevelop applicationsthatcanadapttonewbusinessrulesandconnectacross systems.Whilemostapplicationintegrationisdeployedbehinda companysfirewall,webservicestechnologyoffersthepromiseof crossenterpriseintegration,tyingtogethersystemsrunningon entirelydifferentplatforms. Oursisnowavastlydifferentapplicationdevelopmentworld comparedtotraditionalclientserverenvironments.Thisgradual standardizationofuserinterfaceenvironments,application integrationprotocolsanddatabaselanguageshasbroughtustothe pointwhereapplicationgenerationtechnologycanbebuiltand deployedtoacceleratewebapplicationdevelopment.
21
22
TheEvolutionofAutomatedSoftwareDevelopment
Thegoalofsoftwaredevelopmenttoolshasalwaysbeentohelp programmersdomorewithless,anddeveloprobustapplications morequickly.Earlyattemptsatacceleratingapplication developmentgotusonlypartofthewaythere.RememberRPGII (theolddataprocessingmodel),CASE(ComputerAidedSoftware Engineering),andtheearlycompilercompliers?Someofthesestill existasdatamodelingtoolsorhavebeenintegratedintoIDEs.Some evolvedintocodegeneratorsthatfocusononecodesubsetor another.Stillothersevolvedtoofferlibrariesofprebuilt components.Evensomeoftodayswebpagedesigntoolssimplify applicationdevelopmentbyenablingdatabasecallswithinHTML pages. Inthe1980s,IntegratedDevelopmentEnvironmentspromisedit.In the90s,HTMLandXMLpromisedit.Today,inthe00s,SOAP andwebservicespromiseit. Eachofthosepromisesgotdeveloperspartofthewaytothegoal. Eachtookonesegmentofthedevelopmentcycle,andidentifiedthe elementsthatwerecommon,couldbestandardized,andwerenot customorcareerbuildingexercises.Aswebservicesstandardsoffer newlayersofstandardsandapplicabilityacrossmanyenterprise anddepartmentalarenas,todaysapplicationgeneratorscandeliver onthepromisefirstproposedthreedecadesago:thatsoftware applicationscanbegeneratedrapidlyandwithhighquality.
The1980s:IDEs
Ofcourse,softwaredevelopmenttoolshavebeenaroundforaslong astherehasbeensoftware.Afterflashinglightsandmanual switches,someoftheearliesttoolsweremachinesthatstoredcode onpunchcardsorpapertape,andsavedprogrammersfrom performingthetaskmanually. Onthesoftwarefront,operatingsystemsevolvedtosave programmersfromhavingtowritebasicoperationsoverandover again.Afewyearslater,programminglanguagesandrelated compilersandlinkersappeared.Thesetoolsfreedprogrammers fromlaboringwithassemblycode. Inthe1980s,themostsignificantwaveofsoftwarethatwrites softwarewastheIntegratedDevelopmentEnvironment,orIDE. Lookingback,thecodetheseearlytoolsactuallyprovidedwasnt thatsignificant,butitdidgiveyouastandardlookingapplication framework.
23
WithinanIDE,eachapplicationwasfamiliarduetotheshared components,andeachapplicationsharedacommonlookandfeel. Thisdevelopmentwasfoundtobetremendouslyvaluable,and madedevelopmentskillsfromenterprisetoenterprisemuchmore portable.LearningtodevelopwithoneoftheseIDEsbecamea transferableskillset,andmanyapplicationdevelopersgained experiencewiththesetools. Aboutthissametime,avarietydatabaseenginesappearedfroma numberofvendors.Theseengineshelpeddeveloperscaptureand storeinformationmoreefficiently,andintroducedoptimizedsearch, relationalcapabilities,andfastrecordlookupfeatures.Usinga databaseengine,aprogrammercouldleveragecodehedidnthave towrite,andcreatedataintensiveapplicationsthatwerefasterand moresophisticated. Eventually,allofthesedatabaseengineslargelystandardizedon SQL(StructuredQueryLanguage),andagain,skillsprogramming queriesononedatabaseenginebecametransferableacrossthe industry.
The1990s:ApplicationServers
Applicationserversbecameavailableinthelate1990sformuchthe samereasonthatIDEsanddatabaseengineshadbecomepopular andvaluable:theapplicationserversincludedabaselevelof functionalitythatwascommonforallapplicationsanddidntneed toberebuilteverytime.Plus,thefactthatthisfunctionalitywas handledinthesamewayforeachparticularapplicationserver makesapplicationdevelopmentmorepredictable.Again, developersgainedexperiencewithoneofthevendorsproductsand thatexperiencebecametransferablearoundtheenterpriseandthe marketplace. Inrecentyears,asecondgenerationofapplicationserverhas appeared.Thesenewapplicationserversincludecomponentsfor databaseconnectionpoolingandsessionmanagement.Although thisisavaluablecontributiontoreducingthedevelopmentcycles andmakesthosecomponentsmorestandardizedacrossthemarket, thesefeaturesstillhavetobecustomizedandintegratedintoeach specificapplication.Additionally,thecomponentsincludedinmost applicationserversdontgonearlyfarenoughforthestateless environmentoftodayswebapplications.Noapplicationserver thinksatallaboutnoncontrolledornonsequentialstateswithina complexendusertransaction.And,noapplicationserver accommodatestheneedforuserinterfacefunctionalityinthemiddle serversoftwarelayerrequiredbecauseHTMLisathinclient.
24
ModernRequirements
Buildingonthisaugusthistory,todaysclassofapplication generationoffersabroadermorecomprehensivesolution.Simply put,anapplicationgeneratorisadevelopmenttoolonsteroids.Asa result,thebestoftodaysapplicationgeneratorsgeneratea significantportionofyourentireapplicationforyou. Apowerfulapplicationgeneratorshould: 1. 2. Helpbuildtheapplicationspecificdatamodel. Generateeverythingneededforafunctionalntier application,linkeverythingtogether,anddeliverabugfree, functionalprototypeofthedesiredapplication. Automaticallygeneratepurecommentedsourcecode: nativetothetargetplatform,optimizedfortheproduction environment,withnorequirementsforproprietaryruntime serversorlibraries. Generatefamiliarlanguages,suchasVisualBasic,C#or Java,andsupportstraightforwardintegrationand customization. Providecompleteandwellorganized,commentedsource codethatseasytomodifyandextend. Automaticallypreserveandreintegratecustomizationsor extensionsduringsubsequentapplicationregenerations.
3.
4.
5.
6.
25
Today:ApplicationGenerators
Nowthatenterpriseapplicationsaremigratingtotheweb,theuser interface,creationoftheapplicationinfrastructureanddatabase managementfunctionalitybecomesaprimecandidatefor automationbecausethesecomponentscanbeeasilystandardized. Oneofthereasonsapplicationgenerationissoimportantandtimely nowisbecauseoftheubiquityofHTML,XML,andSOAP.Asa concept,applicationgenerationworksbestwhenyoucangenerate softwarethatrunsanywhereinanyenvironment.Application generatorsbuildinmanyfeaturesthatyoumightnothavethetime todobyhandbecauseyouhaveanapplicationbacklogtowork downanddeadlinestomeet. Severalproductsclaimingtobeapplicationgenerationtechnologies orapplicationassemblytoolsareonthemarketandeachoffers differentfeaturesandfunctionality.Thetoolsvaryindepthand breadthofapplicationcodegenerated,andsodoestheamountof timeandcomplexityittakestoreachapointwherethegenerated softwareleavesoffandtherestoftheapplicationmustbedeveloped byhand. Athoroughreviewoftheapplicationgenerationoptionsshould considerthesethreegeneralcategoriesofapplicationgenerationthat focusontheroutineorcommonelementsfoundinmostwebbased
26
applicationsandwebservices.Specificallythesearewebbaseduser interfaceanduserinterfacecode,workflowandSQLqueries,andthe databaseschemaanddatabaseaccesscode. UserInterfaceFunctionalityandFeatures:Webbaseduser interfacepages,userinterfacecode,search,navigation,pagination, filtering,sortingandreports. ComplexApplicationInfrastructure:Workflow,businessrules, SQLqueries,sessionmanagement,accesscontrolandauthentication. DatabaseManagement:Databaseaccesscode,databaseschema, databaseconnectionpoolinganddatamigration. Bygeneratingsomeoralloftheseelements,youquicklyaddalevel ofrobustnesstotheapplicationthatmakesitmorecompleteand powerful,andyetstillletsyoufocusonthemoreinterestingand importantworkthatisspecifictoyourbusinessneeds. Whilehandbuiltcodewouldsurelygetthejobdone,itsnotthe mostinterestingorsignaturecomponentsofanapplication,norisit themostefficientuseofdeveloperresources. Applicationgeneratorscanprovidedeepfunctionalityforfree: Generatetheroutineprogramcodeandprovidea predictablebaseforallyourwebbasedapplications; Generatecodeofconsistentlyhighqualityandperformance andsoyouhaveajumpstartonyourdevelopmentandcan predicthowthefoundationofeachapplicationwillbehave; Allowdeveloperstofocusondevelopingtheuniqueaspects oftheirapplications,whichtypicallyinvolvesproprietary andcareerbuildingdevelopmentwork.
UML&MDAPoorAlternativesforMostDevelopers
Nohistoricalperspectiveonapplicationgenerationwouldbe completewithouttouchingonUML(UniversalModelingLanguage) andMDA(ModelDrivenArchitecture).UniversalModeling Languagesgenerallydescribehigherlevel,typicallymoreEnglish like,programminglanguagesthatarchitectsusetodesigntheoverall informationarchitecture.Oncecomplete,thispseudocodeneeds tobetranslatedintoproductioncaliberapplicationsoftwaresource code. Similarly,ModelDrivenArchitecturegenerallydescribesavisual toolthatdescribestheoverallapplicationarchitecture.Thesetools
27
typicallyinvolvevisualrepresentationsofboxesofvariousshapes connectedbylines.Again,oncebuilt,thesevisualrepresentations mustbetranslatedintoproductioncaliberapplicationsoftware sourcecode. Whilesometimestoutedasrecentbreakthroughtechnologiesthat representthefutureofsoftwaredevelopment,bothUMLandMDA representanapproachtoprogrammingthatsbeenaroundforalong time.Mostintroductorycoursesincomputerscienceatleast introducethetopicsofinformationarchitectureandsystemsdesign astheinitialstepsinthestructureofanycomputerscienceproject. UMLandMDAdescribeaclassoftoolsandtechnologiesthatcater tothisacademicapproachtoprogramming. Inmostcommercialsettings,thisacademicapproachisntused.In fact,suchexercisesareviewedwithdisdainbymanyexperienced andtalentedprogrammers.Theseprogrammerstendtotakepride inbeingabletocreatefunctionalsystemswithoutwastingmuch timeonthedesignphase. Infairness,UMLandMDAcanworkwellinprogrammingshops thathavereligiousconvictionaboutapplicationplanningand development.Suchenvironmentsaretypicallyfoundinscenarios wheretheapplicationsbeingdevelopedarehuge,andinvolvelots developerswritinghundredsofthousands,ormillions,oflinesof code.Insuchscenarios,UMLandMDAapproachescanprovide mechanismthathelpcoordinatetheteam,organizetheworktobe done,andmanagethemassiveamountofinformationsuchprojects inherentlyinvolve. Evenonanindividuallevel,thesetoolscanbeproductiveifyouare ahighlystructured,organizedthinkerwhoarchitectsanddesigns first,andthenwritescodebasedonyourdesign. Whileusefulinsomeenvironmentsasnotedabove,UMLandMDA representapproachesareoverkillformostsmallscalecustom softwaredevelopmentprojectswithintheenterprise.Theseprojects, byandlarge,aretransactionintensive,andmostlyinvolveusers puttinginformationinto,andgettinginformationoutof,corporate databases.Further,mostprojectsfacetightdeadlines,and constantlychangingrequirements. ThehighlystructuredapproachtoprogrammingimpliedbyMDA andUMLtoolsdonotlendthemselveswelltothesecommon productionenvironments.Infact,suchanapproachcaneven impedeprogressincommonenvironmentsthatdealwithconstantly changingenduserrequirements.Assuch,mostprogrammersin
28
TheEmergenceofIterativeDevelopment
Still,webapplicationsdointroducemorecomplexitythanever before.Asaresult,itisimperativethatthedesignbeflawlesswhen thedevelopersitsdowntobegincoding.Spendingthreeweeks addingfunctionalitytoyourapplicationonlytofindoutthatthe usercommunitywantedsomethingoutsidethespecificationisnot productiveorenjoyable(foranyone).Yet,itisverydifficultto predictuserpreferencesbeforeusersbegintouseanapplication, evenifyouhaveaverydetailedrequirementsspecification document.Inevitably,thedirectivetobeabletosearchinaproduct catalogapplicationagainstthedescription,price,manufacturerand notes,notjusttheproductname,comesafterthethreeweek investmenttobuildthesearchfeaturebasedontheoriginal specifications,whichdidnotincludethatfunctionality. Inthedaysofclientserverapplications,someofthisfrustrationwas accepted,asusershadlittleexpectationthatanyapplicationwould befamiliartothemthefirsttimetheyopenedit.Application trainingwasanexpectedandrequiredconditionofuse.Thiswas acceptablesinceapplicationswerebuiltforrelativelysmalland controlledgroupsofusersi.e.:thecustomerserviceteamorthe salesteam. Webapplicationdevelopmentopensnewchallengesinbothareas. Usersdoexpectwebapplicationstobefamiliartheyexpectthe webapplicationtoconformtocommonlyacceptedstandards, featuresandnavigation.Inaddition,trainingisnotreallyanoption asusersofwebapplicationsareoftenbroadgroupswithdynamic membershipsi.e.:suppliers,customersandallemployees.
29
Rapidly creating user interface pages is an advantage of application generated technology. This helps developers and end-users give relevant feedback early in the development cycle.
30
31
Sofar,wevereviewedtwohighlevelconcepts.Inthefirstchapter, wediscussedwhyapplicationgenerationiscomingofage,andthen, inthesecondchapter,wedescribedtheevolutionofthetechnology. Withthemotivationandhistoryofapplicationgenerationinmind, thischapternowdivesintospecific,realworld,problemsthat developersoftodayswebbaseddataintensiveapplicationsmust solvetofieldproductionapplications. TheexamplesheredrawonourexperiencewithIronSpeed Designer,ourapplicationgeneratorproduct.ShippingsinceAugust of2003,IronSpeedDesigneristheleadingapplicationgeneratorfor buildingwebapplicationsontopofMicrosofts.NETframework andSQLServertechnologies.Currentlyusedbyhundredsof developerstobuildapplicationsrangingfromcustomerserviceto databasepublishing,IronSpeedDesigneristhetoolofchoicefor many.NETdevelopmentprojects. Theexamplespresentedhererepresentmanydevelopment problemswhereanapplicationgeneratorcangreatlysimplifythe taskathand.
AutomateC/R/U/DPageCreation
Perhapsthemostintimidatingaspectofbuildingdataboundweb basedapplicationsisthevastnumberofHTMLformsneededfor userstocreate,review,update,anddeleterecordsintherelevant databasetables. Whileallofthesepagesarenecessary(theyretheheartofmost usage),theworktoproducethemisprobablythemostboring. Theresnotmuchdifferencebetweenoneformandthenext,and eachform,onitsown,israrelyinteresting.Thevolumeofpagesthat needtobecreatedandthemundanenatureofthetaskcombineto mutetheenthusiasmofeventhemostgunghodeveloper.Perhaps thisiswhydevelopersusethederogatorytermC/R/U/D (Create/Review/Update/Delete)todescribethesepages. Asyoumighthaveguessed,applicationgeneratorscanlargely mitigatethepersonalitydamagereportedlycausedbysuchmind numbingwork. Beyondeliminatingthedrudgerytypicallyassociatedwiththetask, applicationgeneratorscanalsoassistinenforcingcorporate standards.Oncetheappropriatetemplateshavebeensetup,every applicationthatutilizesthesetemplatesautomaticallyincorporates anyfeaturesincludedinthetemplate.
32
Layout pages as viewed from the Layout Page Files folder in Iron Speed Designer Oneapproachanapplicationgeneratorcantaketoautomatethe productionofrepetitivepagesisthroughtheuseoflayoutpagesand pagetemplates.Severalstandardlayoutsandtemplatesinavariety ofdesignthemescancomebundledwiththetool.Whenusingan applicationgenerator,youcaneitheradoptthesestandarddesigns, orcreateyourown. Database table view pages. Database table view pages function as reports in applications generated by Iron Speed Designer. Unlike traditional reports, which are static in nature, database table view pages are highly interactive, and allow customization by application users. The database table view pages go far beyond typical web-based reports because of this interactivity, and because they can allow application users to add, edit, and delete data as well as view data. Developers select which columns are displayed in the table view as well as their display order in the table and how the data is sorted. Additionally, search and hierarchical drill-down controls can be added to the table view.
33
Show Record pages. The Show Record page displays the contents of an individual database record in a field-value format. The fields on this page are not editable by application users. These pages can be configured as to which table fields are displayed and how they are ordered on the page.
Add and Edit record pages. Add Record and Edit Record pages can be created for entering and editing record data. These pages can be configured as to which table fields are displayed, how they are ordered on the page, and whether the application user can enter values into the fields.
DeleteRecordFunction YoushouldexpecttheapplicationgeneratortocreateaDeleterecord buttonforeachtableviewpage.Abuttonforthisoperationshould appearabovethetableintheDatabasetableviewpage. Correspondingbuttonsforthesewebpagesshouldbeplacedonthe tableviewpageaswell. Delete buttons are automatically generated for table view pages.
34
ComplexDisplays
Todaysapplicationgeneratorscreatedataboundapplicationsbased ontheinstructionsyouprovidewithinyourapplicationsHTML. TheseinstructionstaketheformofXMLbasedcodegeneration tagsthatspecifytheindividualdataboundcontrolsyouwant withinthepagetheDataGridcontrols,filtercontrols,search facilities,andnavigationcontrols.Whentheapplicationgenerator runs,itconvertsthesecommandsintoacombinationofpresentation layerASPXpagescontainingtheactualcontrols,applicationlayer codebehindsandapplicationlogic,anddatabaselayerSQL statementsandtransactionmanagementcode.
35
Whenyouconsiderthedifferenceintimeandprogrammingeffortto insertonecodegenerationtagintoanHTMLpageasopposedto handcodingalltheASPX,C#,orVisualBasiccodebehindsplus SQLstatementsforeachcontrolitiseasytoseehowquicklyan applicationgeneratorsavesyousignificanttime. Someoftheadvancedfunctionsenterpriseclassapplication generatorscanhandleinclude: Displayingdatainadatagridortableview (rangingfromsimplerowandcolumntablesto sophisticatedtableswithintables) Parentchildrelationships (onetomanyandmanytomanytables) Filteringandsorting (especiallyincombinationwithotherpagecontrols) Multitablejoins (fromthesamedatabaseoracrossmultipledatabases) Databoundcontrols (e.g.,search,sort,navigation) Templatedrivencolumns (e.g.,boxcolumns,unevencolumnheight,multiple databases) Custompagination (e.g.,alphabetical,nonevenlydistributed,etc.) GenerationofcustomSQLstatements DataEntry
36
UsingDataGridstoManageLargeResultSets
Manydatagridsservetheirpurposeassimpletabulardatadisplays. However,manyCRM,contactmanagement,andotherbackoffice Webapplicationsalsoneedtoofferformsinputfunctionalityto applicationusers.ASP.NETofferssomeshortcutstomakefields editable.However,makinganentiredatagrideditableorallowing editingoftemplatecolumns(usingdropdownmenus,forexample), requiresanadvancedknowledgeofASP.NET.Astateoftheart applicationgeneratorwillallowyoutomakeindividualdatagrids orentireformseditable(asshownhere)withouthandcoding. Dropdownlists,radiobuttons,andothercontrolsshouldalsobe optionsforanydatagrid. ThestandardASP.NETDataGridcontrolfetchestheentireresultset fromadatabasequeryintothe.NETapplicationlayer,evenifthat resultsethasmillionsofrows.Thisleavestheapplicationlayerto dotheheavyliftingsortingandfilteringactivitiesbestlefttothe databaseratherthantheapplication.Manipulatinglargedatasetsin theapplicationlayercanhavehugeresourceimplicationsfor applications.
37
Tominimizethedatatransmissionloadandtheapplications memorystoragerequirements,manyapplicationdevelopersemploy databasecursormanagementaconventional,wellestablished databasetechniquetomanagethenumberofrecordsdownloaded fromthedatabasewitheachdatagridpagerequest. Anapplicationgeneratorcangeneratecursormanagementcodethat retrievesonepageofdataatatime,andonlywhenrequested,rather thanretrievingtheentiredataset.Managingthestateofyour applicationpageswithoutdraggingdownperformanceisoneofthe mostdifficultchallengesforwebapplicationdevelopers. Whencursormanagementisemployed,theapplicationprogram doesntattempttomaintainthedataset.Whenthenextpage(orany otherpage)isrequested,thegeneratedapplicationprogramsimply passestherequesttothedatabaselayer,wheretheappropriateSQL queryisrunagaintorequesttheneededpagesdata.Thequery parametersincludethepagenumberrequestedandthebatchsize, whichisthenumberofrecordsperpage.Moreover,theSQLquery isrerunsothatanyrecordsaddedordeletedsincethepreviouspage fetchareproperlyaccountedfor.Bycontrast,ifthecursorwere simplymaintained,anydataupdateswouldnotbereflectedwhen goingfrompagetopage.
38
AutomaticDataValidation&Display
Inmostrealworlddataboundwebbasedapplications,asignificant portionoftheapplicationsactualusageinvolvesdataentryand maintenancebyusers.Becauseusersalwaysmakemistakes, developershavegrownaccustomedtousingstronglytypeddata objectsandassociatedvalidationlogictohelpensuredataintegrity. Whilesuchanapproachismandatedbydesignsenseandbest practices,timeandbudgetpressurescancausedeveloperstocut corners.Insuchscenarios,developerscanbeintimidatedbythe massiveprospectofaddingtypecheckinganddatavalidationlogic tohundreds,ifnotthousands,ofHTMLforms. Setting the validation type in Iron Speed Designer
39
Togivedevelopersaneasysolutiontothisproblem,application generatorscreateapplicationswithstronglytypeddataaccess objects.Thegeneratedcodetakesadvantageofthedatatypes specifiedinthedatabasetogeneratespecificaccessfunctionsthatare stronglytyped.Moreover,applicationsbuiltinthisfashioncanusea varietyofbuiltindatafieldvalidationtypesandtheircorresponding datainputvalidation. Developerscanspecifytheseadvancedfieldvalidationtypeswitha simpletoolasshownintheexample,andthenhavetheapplication generatorusethistypewhengeneratingthedatabaseaccesscode. Forexample,thedatabasemightspecifyanemailaddressfieldasa varcharfield.Intheapplicationgenerator,youcandesignatethis fieldasvarchar,orbetteryet,asEmailAddressoneofthe builtinadvancedfieldvalidationtypes.Ifyoudesignatethefieldas EmailAddresstype,thenthegeneratedcodeisevenmorestrongly typedasanemailaddress,thusensuringthegeneratedcodeandany extensionsyouwritecomplywiththestrongtyping. Someofthedatatypeswhereapplicationgeneratorsinclude validationlogicare:Boolean,country,creditcardexpirationdate, creditcardnumber,currency,date,emailaddress,floatingpoint number,image,password,percentage,U.S.Phonenumber,U.S. State,U.S.ZIPcode,andURL. Moreover,generatedapplicationsincludecodethattranslates betweenthedatabasestorageformatforafield,tothedisplayand inputformats,andthenbackagainuponinsertiontothedatabase. Forexample,aphonenumbermaybestoredas6502152200,but displayedas(650)2152200.Byusinganapplicationgenerator, developerscanavoidwritingsuchcode.
DeliveringaCommonRequest:ExportingApplicationData
Oneofthemostcommonrequestsfrombusinessusersofdata managedbywebapplicationsisadataexportfeature.Endusers liketodownloadthedata,loaditintoExcelorsomeothertool, organizeandanalyzeit,anduseittocreatesummarygraphicsforall mannerofbusinessreportsandpresentations. Ascommonasthisrequestis,itsnotalwayseasy,orevenpossible, toimplementwithsomelegacyapplications.Ifthedataismanaged byanoutdatedorofftheshelfapplicationthatdoesntsportan exportfeature,viabledataexportfacilitiesmaynotevenexist. AnapplicationgeneratormightcreateanExportTablewizard webpageforeachtableviewpage.AcorrespondingExportbutton
40
Data exported by the Export wizard in an application created with Iron Speed Designer. Theexporteddatashouldincludecolumnheadingsinthefirstrow ofthedatatomakeiteasierforotherapplicationprogramstoimport andmakesenseofthedata.
Summary
Theseproblemsarerepresentativeofamyriadofissuesand challengesfacedbyanyonelookingtobuildadataintensiveweb applicationonMicrosoft.NETandSQLServer.WithIT departmentsfacingongoingresourceandscheduleconstraints,and increasingapplicationdevelopmentcomplexity,application generatorsrepresentaninnovativesolutiontopressingproblems likethese.
41
42
WhatShouldanApplicationGeneratorDo?
Regardlessofwhichtypeofapplicationgeneratoryouchoose,you wantthegeneratedcodetobesomethingyoucangetyourarms around.Thegeneratorhastodeliveraproductivityboost. Historically,codegeneratorshaveoftenintroducedasmany headachesastheyvesolved.Forexample,developershave struggledwiththeincompletenessofthegeneratedcode,orthe difficultyofintegratingthatcodewiththeirowncustomizationsor extensions. Theseproblemsandotherscanbeavoidedwithcarefuldiligence duringthetoolselection.Toassistyouinthetoolselectionprocess, thischapterdescribes: theessentialcapabilitiesofmodernapplicationgenerators, theimpactthesebenefitshaveuponsoftwaredevelopment methodologies,and; theimportantattributesofhighqualitygeneratedcode.
Wellbeginwithahighleveloverviewofthecapabilitiesofmodern applicationgenerators.Tobeconsideredstateoftheart,amodern applicationgeneratorshould: Startfromscratchwithanapplicationspecificdatamodel. Asaneasyfirststep,createeverythingneededfora functionalthreetierapplication,linkeverythingtogether, anddeliverabugfree,functionalprototypeofthedesired application. Automaticallygenerateallofthesourcecodeforthe application,nativetothetargetplatform,andoptimizedfor theproductionenvironment. Providecompleteandwellorganizedsourcecodethatseasy tounderstand,modifyandextend.
43
Automaticallypreserveandreintegratecustomizationsand extensionsduringsubsequentapplicationregenerations.
StartingfromScratch:TheApplicationSpecificDataModel
Whenbuildingsoftwareapplications,howyoustarthasahuge impactonwhereyoufinish.Inmostsituations,thewebapplication tobebuiltwilldependonexistingdatabases,andtheinformation architectureoftherelevantdataanddatamodel. Whetherengineeredbyarchitectsororganicallyevolvedovertime, everyproductiondatabasesportsadatamodel.Asyoumight expect,thewaythisdataisorganizediscentraltothedesignofany customsoftwareapplication. Forthebestresults,modernapplicationgeneratorsimportand organizethecodetheyproducearoundtheproductiondatamodel. Nodevelopmenttoolshouldeverintroduceitsownspecialpurpose datamodel,orforceaconversionfromonemodeltoanother. Generalpurposeonesizefitsallapproachestotheunderlyingdata cancreateunnecessaryperformance,complexity,andmaintenance problemsdownstream. Thankfully,modernapplicationgeneratorsaredesignedtocreate customapplicationsaroundanydatamodel.
TheVeryFirstStep:AFunctional,BugFree,Application
Acommonfrustrationsharedbymanydeveloperswhove experimentedwithcodegenerationtoolscentersaroundthe incompletenessofthecodethatscreatedbythetool.Insomecases, atoolmayonlygeneratecodeforonepartoftheapplication(justthe HTMLpages,orjustthecontrols,orjusttheapplicationlogic,etc.). Insuchcases,thedevelopermustlearnhowtoconnectthegenerated componentswiththepartsthetooldidntcreate.Ifthetooldoesnt provideadequateassistance,suchaneffortcanbelaborious,tedious, andfrustrating. Notsowithapplicationgenerators.Themaindistinctionbetween codegeneratorsandapplicationgeneratorsisoneofscope.Anold fashionedcodegeneratormayhelpadeveloperproducesomeparts oftheapplicationthatarerepetitiveinnature,butmostofthe responsibilityfortheoveralldesignandimplementationstillrests withthedeveloper. Applicationgenerators,ontheotherhand,takeonmuchmore responsibility.Thisgenerationoftoolsprovidestheoverall architecturefortheapplication,generatescodeforeverystandard
44
CodeCompleteness&Organization
Ofcourse,eventhemostfeaturerichgeneratedapplicationisnt entirelyusefulifthesourcecodeisunintelligibleorscattered. Wheneverageneratorproducessourcecode,itneedstobecreated andstoredinawaythatsnaturallyintuitive. Whileeverydeveloperfacessomelearningcurvewhenusingany newdevelopmenttool,suchachallengecanbemitigatedwhenthe toolproducescodethatseasilyread,organizedwell,andflows naturallyintothedevelopersstandarddevelopmentenvironment.
ExtendingtheCodeGeneratorItself(AutomatedCodeReuse)
Lastly,andperhapsmostimportantly,applicationgeneratorsshould automaticallypreserveandreintegratecustomizationsorextensions duringsubsequentapplicationregenerations. Today,mostgoodapplicationgeneratorsarethemselvesextensible. Amajordrawbackofpastcodegeneratoreffortsisthatthetools wereonewaystreets:Onceyoupushedthegeneratebutton,you ownedthecode.Suchaprimitiveapproachjustdoesntworkfor todaysiterativestyleofdevelopment. Ideally,theapplicationgeneratorshouldallowyoutoputyour extendedormodifiedcustomcodebackin,andallowthatcustom codetobecomepartofwhatthetoolcangenerateforfuture applications.Ratherthanjustspitbackoutwhatisputin,the applicationgeneratoraddsvaluebycreatingarepositoryofcode assets.Further,byautomatingtheprocessforreusingcustomized codewrittenforoneapplicationinanother,theseassetsbecome moreflexibleandmultipurpose.Usingapplicationgenerators,you andotherdevelopersanywhereinyourorganizationcaneasily leveragethesecodeassetsoverandoveragain. Inessence,theapplicationgeneratordoeswhatnodeveloperhas timeorincentivetodo:Itmanagesselectedapplicationcodeand createsaknowledgebaseofreusablecodethatmeetsthespecific standardsandpracticesofthatuniqueorganization.Onceinplace, codewrittenspecificallyforoneapplicationcanberegeneratedfor
45
futureapplicationdevelopmentautomatically.Allofthistakesplace withoutanyadditionalworkordragontheinitialapplications projectschedule. Specifically,youmightleveragecustomcodeinthefollowing scenarios: PresentationLayer:Becausemanylargeenterprisesrequirelocally constructedapplicationsconformtoadistinctsetoffunctionalityas wellaslookandfeelstandards.Withmodernapplication generators,thisstandardfunctionalityisimplementedoncewith customHTMLlayoutpages.Originallybuiltforaninitial application,theselayoutscanbeautomaticallyreusedwhen creatingfutureapplications.Onceinplace,itsactuallyeasierfor developerstoconformtosuchstandardsthantodeviatefromthem. ApplicationLayer:Anyaspectoftheapplicationlogicshouldbe abletobeextendedandthenregeneratedforfutureapplications. Forexample,anordermanagementsystemmayapplydifferent ordervalidationlogicfororderscomingfrompartnersthanfor ordersfromtheinsidesalesteam.Anotherexamplemightbe customdatastructurestorepresentvariousawardlevelsina customerloyaltyapplication.Inbothofthesecases,oncethecustom codeiscreatedforoneapplication,itcanberegeneratedfor additionalapplicationsautomatically. DataLayer:Thegeneratedapplicationshouldbeabletoworkwith anydatasource,notjustSQLcentricdatabases.Examplesof alternativedatasourcesincludecustomwebservices,messagebuses (suchasIBMsWebSphereMQorTibcosRendezvous),andeven realtimedatafeedsfromsensorssuchasdigitalthermometers, cameras,ormotiondetectors.Sinceallofthesesourcesare potentiallyrelevantconsumersandproducersofdata,generated applicationsneedtobeconstructedinafashionthatembracesthese dataservices,andmakesintegrationasstraightforwardaspossible. Ineachofthesescenariosandmore,applicationgenerationdelivers onthepromiseofcodereusebyeliminatingthereusedevelopment penalty,andautomatingtheinclusionofthesecustomextensions withnewapplicationsastheyaregenerated. Later,wellshowseveralexamplesofhowcodereuseisenabled throughapplicationgeneration.Ofcourse,thebenefitsofemploying anapplicationgeneratorcanbediminishedifthecodethatscreated automaticallyisntwellformed.Itscrucialthatthetoolcreate goodcodethatcanbeunderstood,extended,andcustomizedby thedevelopmentteam.
46
CharacteristicsofGoodGeneratedCode
Inordertoevaluatethetrueeffectivenessofanyapplication generator,itisimportanttounderstandthenecessarycharacteristics ofthegeneratedcode.Someofthesecharacteristicsareidenticalto thoseweexpectfromatopnotchprogrammer.Othersarespecific towhatadevelopmentteamneedswhencodeisautomatically createdforthem. Weshouldexpectgreatcodefrombothtalentedseniordevelopers andapplicationgenerators.First,theybothneedtocreatecodethat iseasytounderstandanotherprogrammershouldbeabletotake overcodeandnotfeelaneedtorewriteallofit. Whetheritsgeneratedornot,easytounderstandcodehasseveral importantcharacteristics: Itisorganizedinsourcefilesinalogicalandconsistentway (usuallyhierarchically),whichmakesiteasytofindthecode foraparticularfunction,structure,class,method,or definition. Thecodenamingconventionsclearlyindicatetheroleofthe entity. Thecodeisformattedcleanlyandthereislittleresidualor unneededcodelyingaround.Thereslittletonoclutterin thesourcefiles. Inlinecommentsareplentiful,andclearlyindicatethe functionandstructureofthecode,anditsintendedpurpose.
47
ImplicationsforDevelopmentMethodology
Astheapplicationgenerationtechnologydescribedabovebecomes widelyavailable,itssuretohaveanimpactonhowprofessional softwaredevelopersgoabouttheirbusiness.Thenextfewpages describesomeofthechangestoexpectasprogrammersincorporate automationtoolsintothewaytheybuildenterprisesoftware. Inaclassicapplicationdevelopmentmodel,threegroupsof individualsareinvolvedinthedevelopmentteam. Systemanalystsdeterminethefunctionalityofthe System Analysts applicationandwritethespecification.Thenthe databaseadministratorsandprocessmodelersgetto workandbuildthenecessarydatabases(models)for Database Administrators theapplication.Atthatpoint,theprogrammersstart Process Modelers coding.Oncetheprogrammersstartwritingthecode, theydontletgoofthecodeuntiltheapplicationis released.
Application Generator
Whenyouuseanapplicationgenerator,thismodel becomesmorecomplicated,becauseafourthparty Development Team (theapplicationgenerator)isaddedtotheprocess. (Code Customizers) Eachtimethedataorprocessmodelchanges,thecode mustberegenerated.Inmostapplication developmentefforts,thedatamodelisinastateof fluxthroughoutthecodingprocess,whichcreatesaneedfor adaptability(usuallybythedevelopmentstaff).Inachanging environment,anapplicationgeneratormustbeabletoplaya supportivevalueaddedrole,ratherthananobstructiverole,tothe developmentteam. Forexample: Thedevelopmentteamnotonlyrequiresaccessto100%of thecodethattheapplicationgeneratorcreates,butthecode mustbeeasilyextendedandcustomized. Thedevelopmentteammustbeabletoeasilyintegratepre existingcodeaftergeneration.
48
GatherFeedbackEarly&OftenintheCyclewithRealSoftware
Typically,developmentrequiressomeprototypesoftheapplication inordertogainrelevantandhelpfulfeedback.TheRADapproach prototypestheapplicationinordertoobtainsomeofthisfeedback. ButRADdoesntusuallybuildmuchofthefinalapplication. Amoreiterativedevelopmentstylebecomespossiblewhenthe abilitytocreateanddeploycustomapplicationsquicklybecomes financiallyfeasible.Iterativedevelopmentmanifestsitselfwith growinguseofrefactoring(leveragingexistingcodeassetsintonew webbasedapplications)andRADtools. Thistrend,prevalentinITshopsthroughouttheindustry,notably shiftsemphasisawayfromrestrictiveapplicationplatformsand outsourcingbothofwhichareprovingtoberiskierandmore costlythanoriginallyanticipated. Moreover,iterativedevelopmentlendsitselfbettertotodaysmore dynamicbusinessenvironmentthanmoretraditionalstructured developmentmethodologies.Aniterativeapproachembeds developerswithintheoperationallinemanagementofan organization,andallowsthemtoconstantlyincorporatefrequent feedbackfromendusers.Iterativedevelopersrecognizethatthe mostsuccessfulapplicationsareconstantlyrefined,andactively morphthoseapplicationstoaccommodatetheshiftingneedsofthe everchangingmoderncompany. Applicationgenerationtechnologygoesfurtherthantherapid applicationdevelopment(RAD)approachesofthepastandthemore recentextremeprogrammingtrend.RADisaboutputtinga prototypeinfrontofuserstoobtainfeedbackduringthe developmentcycle,notjustattheendwhenitistoolateandtoo complicatedtomakeanysignificantchanges. Mostusers(andclients)havedifficultyarticulatingwhattheywant inadesiredapplicationbecausetheycantenvisionit.Inthis
49
respect,RADisreallyhelpfulbecauseaprototype(orevenamock upgraphic)canspuradialog. Sometimes,theusercommunityrequestinganapplicationfromthe ITdepartmentwillemployagraphicartisttodevelopthewebbased interfaceinordertoguidethediscussionwiththedevelopment team.Thiscanbehelpful,butthistacticusuallyinvolvesdesigning abouthalfadozenofthetoplevelscreens.However,production qualitywebapplicationscanhavehundredsoreventhousandsof screens.Someofthereallyimportantworkflowscreenslike accountmaintenancepagesanddataimportingwizardsinevitably getleftoutofthisprocess.Andyet,oftenthoseworkflow experiencesrepresentthekindoffeedbackdevelopersneedmost. Untilmeaningfuldialogoccursbetweenanalystsandusers, functionalrequirementstypicallyremainvagueandincomplete. Usinganapplicationgenerator,developerscandramaticallyshorten thepathtomeaningfuldialog.Insteadofanincompleteprototype ormockupgraphics,theycangenerateafunctionalfirstpassofthe entireapplication,andpopulateitwithrealworlddata.By presentingalive,robustapplicationtoendusers,developers empowerthemtogivedeepandmeaningfulfeedbackforalllevels oftheapplication. Still,successfuliterativedevelopmentrequiresadvancedsoftware toolstokeepeverythingorganized.Otherwise,thissomewhat chaoticdevelopmentprocesscanleadtoabigpileofspaghetticode. Thisiswherecontemporaryapplicationgeneratorscanhelp.They aredesignedtofacilitateiterativedevelopment,andreduce developmenttimepenaltiesaschangesaremadeandupdates deployed.
UseBusinessAnalyststoDevelopPrototypes
Beyondenablingearlyandrelevantfeedbackonworking applications,applicationgeneratorsempowerITdepartmentsto rethinktheresourcemixandprojectassignmentsoftraditional developmentteams.SinceexperiencewithC#,C++,Java,orVisual Basicisntrequired,applicationgeneratorsempowernewcategories ofdevelopers(businessanalysts,programmanagersand informationarchitects)withunprecedentedabilitiestocreateand deployworkingapplications.ThisdiffersconsiderablyfromRAD andextremeprogrammingmethodologiesthatrequiredevelopersto createprototypesbeforeenduserfeedbackcanbegathered. Typically,thesemembersoftheITdepartmentarespecifically trainedandexperiencedatgatheringfeedbackfromendusers.
50
SimplifySoftwareMaintenance
Assoonaswebapplicationsarelaunched,requestsformodifications startrollingin.Sometimestheseareissuesendusersdidnot anticipate;sometimestheyreflectchangesincompanystrategyor marketconditionsthatwereunanticipated.Sometimesuser interfacechangesarenecessarybecauseofadvancesontheother websites.Ascertainfeaturesbecomecommonplace,everyweb applicationisexpectedtokeeppace.Whydowebbasedportals changetheirlookandfeelcontinuouslyandyetTimemagazine doesnot?Thewebmakeseverythingmoreaccessible,andincreases thecompetitivepressureforpushingmore,ratherthanless,tothe usercommunity. Thispressuretoconstantlyevolveandimprovelandssquarelyon theITdepartmentandmakesapplicationmaintenancemore significantthanwithclientserverapplications.Beforetheweb,the conceptofRAMrapidapplicationmaintenancewasneverapart oftheapplicationdevelopmenttoolset. Typically,thissortofmaintenanceisadevelopersleastfavorite task.Thereisnothingworsethantryingtoguesswhattheother guywasthinkingwhenhewrotetheoriginalcode. ApplicationgenerationlargelysolvestheRAMproblem. Applicationgeneratorsfullyregeneratetheentirecodebasewith eachmodification.Thegeneratedcodekeepsupwitheachnew revisionandeachnewmanagementdirective.Sofinally,forthevast majorityoftheapplicationssourcecode,noonehastoperform softwarearchaeologytounderstandsomeoneelsesworkbefore accommodatingarelevantchangerequest.
CustombuildtheUniqueAspectsofyourApplication
Withanapplicationgenerator,youshouldexpecttogenerateabout 80%oftheapplicationcode,expecttofocusthevastmajorityofyour developmentresourcesontheother20%oftheapplicationthatis uniqueandproprietary.Thisremaining20%willcontaintheunique algorithmsandbusinesslogicandmustbedevelopedbyhand. Beverywaryofanytoolthatclaimstocreate100%ofevery application.
51
Giventhatacrucialpartoftheapplicationmustbecreatedbythe developer,modernapplicationgenerationsoftwareoffers convenientandcomfortableinterfacesfordevelopingand integratingthisremaining,butcrucial,20%. Therearetwocommontypesofintegrationthatmustbeconsidered whenusingapplicationgenerationsoftware:integratingbusiness logicandcommunicatingwithexternalapplications. IntegratingBusinessLogic Integratingbusinesslogicrequiresaclosecouplingbetweenthe80% thatisgeneratedandthe20%thatisbuiltbyhand.Thisisbest accomplishedbyasetofAPIs,orsetofobjects,forconnectingyour codewiththegeneratedcode.Ideally,thisintegrationispersistent fromregenerationtoregeneration,meaningthatyourintegration workisnotlosteachtimetheapplicationisregeneratedbythe applicationgenerator.Ifitslost,thenyoulosemuchofthebenefit ofusingapplicationgenerationsoftwareinthefirstplace. IntegratingExternalApplications Integratingexternalapplications,suchasathirdpartyCRM package,isbesthandledusingapplicationintegrationprotocols. Increasingly,webservicesprotocolslikeSOAParebeingusedfor externalintegration,andideally,yourapplicationgenerator supportsthesewebserviceprotocolsaswell.
KeyBenefitsofApplicationGenerationMethodology
Onceapplicationgeneratorsareintegratedintothedevelopment processandculture,developmentorganizationscanrealizea numberofbenefitsassociatedwithadoptingthisautomation technology.Thenextfewpagesexploreafewoftheseimportant benefits.
SpeedDevelopmentandReduceTestingTime
Evenifenduserswanttowebifytheirfavoriteclientserver application,thedevelopmentcosttorefactorexistingapplications intonewandimprovedstreamlinedwebversionsisoftentoohigh. Recognizingthisdilemma,severalvendorsofferavarietyoftools thatpromisetoimprovedeveloperproductivity,andhence,lower thesedevelopercosts. Today,applicationgenerators,codegenerators,andRADtools automatevariousaspectsofapplicationdevelopment,andpromise toreduceoveralldevelopmentcosts.Infact,Microsoftisreleasing
52
ASP.NET2004withseveralnewfeaturestoimprovedeveloper productivitysuchasdragndropwizardsandsomeautomatedcode generation.AnotherexamplefromMicrosoftistheEnterprise TemplatesfeatureinVisualStudio.NET.Thesetemplatesare planninganddesignmodulesthatallowthedeveloper,amongother things,tobuildcodesnippetsintheIDEitselfsotheycanbeshared acrossanumberofapplications. Inessence,thesetoolsmakeitpossiblefordeveloperstoautomate andmanagethedevelopmentofapplicationcode,andcreatea knowledgebaseofreusablecodeassetsthatmeetsthespecific standardsandpracticesofthatuniqueorganization. Thismeansthatthecostofapplicationdevelopmentand maintenanceisdroppingfastforthoseorganizationsand developerswhoareadeptatincorporatingthisnewgenerationof toolsintotheirdevelopmentprocesses.
EnableCorporateComputingStandards
Inadditiontocosteffectivelybuildingandmaintainingstateofthe artenterprisewebapplications,todaysdevelopersmustwritethis softwareinawaythatconformstocorporatestandards.IT organizationsstrivetoestablishandmaintainstandardsformany aspectsofthesoftwaretheywritesuchasuserinterface, functionality,navigation,lookandfeel,colors,etc. Onceinplace,suchstandardsassistITorganizationstoreduce trainingandsupportcostsbyleveraginguserexperience. Unfortunately,thecostsassociatedwithupholdingsuchstandards canmitigatetheirbenefit.Whendevelopersaresaddledwith constantlyreengineeringcodetoconformtothesestandards, compliancetendstodegrade. Byadoptingadevelopmentmethodologythatincorporates applicationgenerationasacentraltheme,ITorganizationscanturn thetablesonthiscommonproblem.Onceanapplicationgenerator hasbeenextendedtosupportcorporatestandardsforuserinterface andfunctionality,futuredevelopmenteffortscansupportthese standardsatnoadditionaldevelopmentcost.Infact,deviatingfromthe corporatestandardisactuallymoreexpensivethanconformingtoit. Allofasudden,theeconomicsofsupportingstandardsarereversed, andthebenefitsofstandardizationcanberealizedacrossallnew webapplicationdevelopmentefforts.
53
Automated,YetRobustUIBringsApplicationPowertoLight
Inwebbasedapplications,theuserinterfacetakesonsignificantly moreimportancethanintheirclientservercousins.Becauseofits ubiquitousnature,thewebisalreadyfamiliartocorporateend users.Asaresult,enduserstypicallyexpectanywebbased applicationtobeeasiertouse. Infact,theuserinterfacehasbecomethebellweatherforapplication robustness.Evenexperienceddevelopers(whomightknowbetter!) willlookatauserinterfaceandmakejudgmentsaboutthe complexityanddepthoftheunderlyingapplication.Thiscanbe somewhatfrustratingtoinformationarchitectsanddeveloperswho canspendenormouseffortcreatingpowerfulcapabilitiesatthe applicationordatalayers. Regardlessofthepowerorperformanceoftheunderlyingdatabase representation,thewebbaseduserinterfacesendsthemost powerfulmessageabouttheentireapplicationthananyotheraspect ofthesystem.Theimpressionsofendusersandmanagementare shaped,byandlarge,bytheuserinterface. Mostapplicationdevelopers,however,arenottrainedtobuild highlyusableandinteractivewebbasedinterfaces.Whilelarge commercialecommerceandcorporatesiteshaveteamsofpeople designingthewebpages,mostITdepartmentsdontnormallyhave accesstotheseexperts. Again,applicationgeneratorscanhelp.Theyautomaticallygenerate thebrowserbaseduserinterfacepagesandtheunderlyinguser interfacecode.Moreover,theydosousingcontemporaryuser interfacestandards.Thesestandardsleveragetheexperienceend usershavewithotherwebapplications.Applicationgenerators leveragethesestandardsandtheexperiencebaseofmostwebusers tomaketheapplicationstheycreatemoreuserfriendlythanthose builtbyhandrightfromthestart. Partoftheeaseofuseadvantagegeneratedapplicationsresultsfrom merecompleteness.Generatedapplicationsincludeallthetoplevel pagesandreportsyoudexpect,andalltheroutineaccount informationanddatamanagementpages.Suchpagesnormally requirehoursandhoursofmindnumbingtediousdevelopmentto create,butareessentialtodeployinganyproductionsystem.By providingallofthesepagesupfrontthroughautomation,generated applicationsavoidalloftheusabilityproblemsassociatedwith commonerrorsofomissionandsimpleprogrammingerrors.
54
Scalability
Buildingtransactionintensivewebapplicationsthatscaleiseasier saidthandone(anditsnoteventhateasytosay).Whenfacedwith multiplehighpriorities,tightdeadlines,andlimitedresources, developerscancutcornersoncreatingapplicationswithscalability inmind.Oftentimes,thesequickfixstyleapplicationsdont anticipateneedsbeyondshorttermrequirements.Asthese applicationsbecomeintegratedintoanorganizationsbusiness processes,theycangeneratemountainsofchangerequests,and consumemoreandmoreresourcesastheircreatorscontinueto patchandfixandenhanceanapplicationthatwasneverintended forthecurrentusagepattern. Evenconsideredupfront,scalabilityis,evenforexperienced developers,difficulttoimplement.Sinceallofthebusinesslogicin webapplicationsisconcentratedserversideintheapplicationlayer, scalabilityfrequentlybecomesabigissueforwebapplications. Functionalityisntdistributedtotheclientsideasitiswithclient serverapplications,soyoucantrelyontheapplicationusers machinetooffloadcomputationallyintensivetasks.Hence, improperlydesignedapplicationscancauseperformancebottlenecks inthemiddletier.Applicationgeneratorsshouldbuildapplications withathreetierarchitecturethatscaleseasily,includingoptimized SQL,andadvancedtransaction,cache,andsessionmanagement techniques. Asyoucansee,thedemandsonanapplicationgeneratorarehigh, andallofthesedemandsmustbemetforthismethodofapplication developmenttobeaviablesolution.
BoostYourCompanysROI
Utilizationofapplicationgeneratorshasmeaningfulfinancial benefitstoanyorganizationchoosingtoleveragethetechnology. Considerthefollowingtable:
55
Programming Challenge
Native .NET program code generated by Iron Speed Designer in just a few hours
Time Savings
Cost Savings*
Presentation Layer
Sophisticated User Interfaces: Page filters and sorting, including end-user reports Sophisticated User Interfaces: Full text search Sophisticated User Interfaces: Navigation Sophisticated User Interfaces: Pagination Iron Speed Designer generates all the web pages required for enterprise-class applications. Quickly add sorting and filtering on tables, records and fields. Select search for any combination of tables or fields. Add hierarchical navigation to any page or database table view. Add pagination controls to any database table view. 100 hours $4,000
Application Layer
Application Architecture Generates a standard 3-tier architecture with presentation layer ASPX pages and ASCX controls, an application layer class hierarchy that is easily modified, and database layer SQL statements and transaction management code. Generates a straightforward class hierarchy that easily accommodates code extensions. All your code modifications are preserved. Weeks or months of hand coding $400 - $12,000
Code Extensions
Same
N/A
Database Layer
SQL Statements Application Security *Based on $40 per hour Thetableaboveusessimpletimesavingsforjustafewcommon featurestobegintocalculatethefinancialadvantagesofutilizing applicationgenerators. Beyondthesesimpleyetconcretefigures,otherimportantfactors shouldalsobeconsideredwhencalculatingtheROIofapplication generators.Forexample,usinganapplicationgeneratorgenerally meansthatyoullbedeployingapplicationsfaster,andthesoftware startsworkingforyourcompanysooner.Incaseswherethese applicationsenableproductivitygainsornewrevenues,thevalue associatedwithearlierdeploymentdatescanbeextraordinary. Generates all the SQL statements required in efficient stored procedures Automatically generates role-based security for any number of roles, using your own users table. 100 hours 35 hours $4,000 $1,400
KeepDevelopmentInhouse
MostITdirectorsdontoutsourcedevelopmentbecausetheydisdain softwaredevelopment.Theydstillprefertodevelopinhouse.The
56
goalsofmostoutsourcingaretosavemoneyandtogetapplications launchedmorequickly.Fromafinancialperspective,theheadcount costadvantagesofoffshoredevelopmentresourcesappeartostretch developmentdollarsfarther,andenablethedevelopmentofmore applicationsoftwarewiththesame,orevenreduced,budgetdollars. Alas,thehiddencostsofoutsourceddevelopmentprojectsare frequentlyworsethantheirpromisedsavings.Whileitmayappear cheaperatfirst,managersofoutsourcedprojectssoonlearnthat someonewhodoesnotspeakyourlanguageandlocated12time zonesawayisreallyhardtomanage.Moreover,theycanneverfully understandtheinternalcustomersyousupportbecauseitishardto collectandshareusercommunityfeedback.Thedialogbetween usersanddeveloperscandisappearwhenfacedwhensignificant barriers(timezonedifferences,nativelanguagedifferences,and corporatecultureclashes)existbetweenusersanddevelopers. Whendealingwithdemandingusersandtightdeadlines,these challengescanbeespeciallytroublesome. Further,missioncriticalapplicationstendtoembedatremendous amountofintellectualpropertyinrelevantsourcecodemodulesand databases.Grantingoutsidersaccessintroducessignificantriskto thebusiness.Losingcontroloftheseassetsmeanscompetitorscould getaccesstoyourproprietarydataandbusinessprocesses.Beyond competitors,suchassetswouldbeofgreathelptomalicioushackers lookingtocausechaoswithinyourenterprisesystems. SowhatisabudgetchallengedITdirectortodo? Anincreasinglypreferredalternativeistokeeptheworkinhouse, useadvancedsoftwaretoolstoempowernondeveloperstodoalot oftheheavyliftingforroutineinfrastructureprogramming,and focusdeveloperresourcesontheuniqueandcareerbuildingcode thatgivestheapplicationpersonalityanddimension.These advancedtoolsincludeapplicationgenerators,tiercodegenerators, RADtoolsandcomponentlibraries. Forexample,adeveloperatamajortiredistributorrecently launchedanenterprisewidestorereportingapplicationfor360 storesinjusttwodaysusinganapplicationgenerator.Hisoriginal estimatefordevelopingtheapplicationbyhandwas2person months.Whilethiswasntthemostcomplicatedanddemanding application,theresnodoubtthathis2dayturnaroundtime providedafaster,easier,safer,andcheaperalternativetoan outsourcedsolutionofanykind. Sinceapplicationgenerationspeedsdevelopmentandletsyoukeep theentireapplicationdevelopmentprojectinhouse,itcompares
57
58
59
ApproachestoApplicationGeneration
Recognizingtheadvantagesofapplicationgenerationasdetailedin thepreviouschapter,developertoolsprovidershaveintroduceda varietyofproductstohelpprogrammersrealizethebenefitsof automation.Aswithmostaspectsofsoftwaredevelopment,there areavarietyofapproachesandphilosophiesregardingsuchtools andtheirrelationshipstothedeveloperandthedevelopment process.
TheMDA/UMLPhilosophy
SometoolssubscribetotheUML/MDAapproach.Here,thetool createssourcecodeforyourapplicationbasedonamodelofthe applicationfunctionality.Themethodologyassociatedwiththis approachtypicallyrequiresalotofeffortupfront,inthedesignand planningstage,tobuildanarchitecturalmodeloftheentire applicationasafirststep.Oncethemodeliscreatedandcomplete, thetoolconvertsthemodelintoapplicationsourcecode.
TheAlgorithmicApproach
Anotherphilosophyforanapplicationgeneratorcentersonan algorithmicapproach.Here,thetoolinferstheapplication functionalityfromaparticularinputsource.Sometoolsstartwith thedatabase,andinferthebusinesslogicandUIfromthere.Other toolsemphasizeeitherthebusinesslogicortheUIasthestarting point.Inanycase,analgorithmicapproachemploysanalgorithmto drivethecreationofyourapplication. Recently,anewapproachtoapplicationgenerationhasappeared. Thisnewapproach,calledthedeclarativemethod,empowersthe developerbycreatingtheapplicationwithmultipleinputs (primarilybasedonuserinterfacerequirementsandexisting databaseschemas). Theremainderofthisbookwillfocusonthisdeclarativeapproach, itbeingthemostrecentandmostpowerfulapproachtoapplication generation.
TheDeclarativeMethodPhilosophy
Declarativeapplicationgeneratorsworkbytranslatingadeclarative descriptionofyourapplication(forinstance,anHTMLpage containingcodegenerationinstructions)intoaworkingntier applicationwithwellpartitionedservicelayers.
60
Unlikealgorithmicgenerators,declarativeapplicationgenerators dontpresumetoknowwhatthefunctionalityoftheapplication shouldbe.Ratherthanrelyonapredeterminedandstatic algorithm,theydynamicallycreatetheapplicationbaseduponthe directionoftheprogrammer. Thedeclarativemethodofapplicationgenerationrecognizesthat onlyasmallpercentageofthecodeinanyapplicationisthesecret saucethetrulyuniqueelementsthatdifferentiateoneapplication fromanother.Accordingly,the80%90%oftheapplicationthatis basicinfrastructurelendsitselfquitewelltoautomaticgeneration basedonaspecificationofwhatthedeveloperwantsinthe application. Thisdeclarativemethodisanimportantandusefulapproachfor modern.NETapplicationdevelopmentbecause: Thisishowdeveloperswork. MostapplicationsarearchitectedbasedonahandfulofHTMLpages andadatabaseschema.Developersbuildtheapplicationfromthose startingpoints.(Infact,HTMLmockupsanddatabaseschema diagramsformthefoundationofmanyapplicationdevelopment proposals.)Thedeclarativeapplicationgeneratordoesthesame thingitusesyouruserwebpagesandexistingdatabaseasinputs, andgeneratesalargevolumeofinfrastructurecodeinafractionof thetimeofhandcoding. Also,declarativemethodapplicationgeneratorstypicallycancreate customworkingapplicationsnotjustaprototypeorindividual componentsinjustacoupleofhours.Suchanapproachsupports aniterativeapproachtodevelopment,andshavesmonthsoffthe developmentcycle.
SpecifyinganApplicationsBasicFunctionalitywithCode GenerationTags
Bywayofexample,theIronSpeedDesignerapplicationgenerator callsthesedeclarativedescriptionslayoutpages.Layoutpagesare HTMLwebpagesthatdefineyourapplicationswebbaseduser interfaceandcontainsimpleXMLbasedcodegenerationtags. UsingyourfavoriteHTMLeditor,youinsertcodegenerationtags intoyourHTMLateachplacewhereyouwantapagecontrolto appeareverythingfromadatagridtabletofilterstodatadriven menus.Oncecodegenerationtagsareplacedinthepage,the applicationgeneratorpromptsthedeveloperforinformationabout whichdatabasetablesandfieldstouseforeachdatabound component.
61
Theenduserneverseesthecodegenerationtagsbecausetheyre strippedoutwhencreatingtheapplication.Whentheapplications pages(orscreens)aregenerated,thetoolreadsthetagsandreplaces themwithalltheappropriatecode.Thisprocessefficiently constructsthesecomplexpages,andaccuratelyconnectseachdata boundcontroltothedatabase.Asaresult,youdonothavetowaste timeprogrammingASPX,VBorSQLtocreatesophisticateduser interfaceswithanapplicationgenerator.(Laterinthischapter,well furtherdescribehowcodegenerationtagsdrivetheIronSpeedDesigner applicationgenerationprocess.) InputstoGenerateYourApplication
WhatDeclarativeMethodApplicationGeneratorsCreate
Usingtheseinputs,applicationgeneratorsproduceallthecode requiredbyafunctionalapplication.Thiscodeisorganizedinaway thatsconsistentwithstandardntierarchitectures.
62
PresentationLayeracompletewebbaseduserinterface Sophisticatedwebbaseduserinterfacepages,includingdatabase connectedforms,tablesandreports.Advancedfeaturesinclude reportswithfilteringandsorting,fulltextsearch,navigation,data validation,andtablepagination. ApplicationLayernative.NETprogramcode Easilyextensibleclasshierarchybuiltontheplatformbaseclasses (suchasthe.NETFramework),aswellasenterpriseclassfeatures suchasrolebaseduseraccesscontrol. DatabaseLayerallyourSQLandtransactionmanagement AlltheSQLqueriesfordatadisplayandreportingaswellasrecord insertion,modificationanddeletionaregenerated.Advanced featuresincludemultitablejoinsandapagebasedtransaction model. GeneratingtheWebBasedPresentationLayer Translatinganendusersvisionfortheirwebapplicationintoa functionalandintelligentuserinterfacerequiresthreemainsteps, eachofthemnontrivial. Buildtheapplicationsbasicfunctionalitywiththeselection andplacementofsophisticatedpagecontrolsandfunctions rangingfromfilteringandsorting,tosearchandpagination;
63
Fortunately,declarativemethodapplicationgeneratorscanhelp witheachofthesesteps. CreateHundredsorThousandsofWebPages Earlyon,whenbrainstormingorsellingtheproject,onlyahandful ofhighlevelpagesaretypicallymockedupbyawebdesigner. Thesepageshelpcommunicatethebasicideasabouttheproposed applicationtoallthoseinvolved.Buttoactuallybuildanddeploy theapplication,thedevelopermustcreatetherestofthepagesby handbasedontheseinitialdesigns.Whiledesigningthe applicationslookandfeelisnottrivialtobeginwith,repeatingit overandoverforeachofthehundredsofpagesrequiredtorunyour webapplicationisasignificantandtimeconsumingchore. The four standard database-connected table view pages can be automatically generated for each table in your applications: Show Table, Show Record, Add Record and Edit Record.
64
ConnectingWebPagesandDataboundControlstotheDatabase
This graphic emphasizes the relationship between two code generation tags as inserted in a layout page, and the resulting pages with corresponding data-bound elements.
Whenusingadeclarativemethodapplicationgenerator,onceyour codegenerationtagsareplacedinyourlayoutpages,thetool promptsyouforinformationrequiredtoconnecttheresulting controlstotheunderlyingdatabasesandtosetotherparameters. Typically,awizardguidesyouthroughthisbindingprocess,and youdontneedtoknowanySQLorbeanexperiencedprogrammer togenerateadvancedpagecontrols. Whentheapplicationisgenerated,thecodegenerationtagsare strippedoutofthefinalASPXpages,andreplacedbycorresponding webcontrols,serversidecodebehindlogic,andtransaction managementcode.Thismeansthatcodegenerationtagshaveno runtimeeffectonyourapplicationbecausetheyarenotpresentin thegeneratedapplicationsourcecodetheyonlyexistin preliminaryinputfilesforthepurposeofinformingtheapplication generatorabouttherequiredfunctionality. ManyITdepartmentshaveanSQLombudsmanwhoisanexpert SQLDBAandcheckstheSQLcodewrittenbyalltheother developers.Adeclarativemethodapplicationgeneratorsimplifies
65
thedevelopersandtheombudsmanstasksbyautomatically generatingeverySQLquery(andthewrappercodearoundit)for eachwebbasedcomponentthataccessesthedatabase. Inthisway,thedeclarativemethodapplicationgeneratorcreatesa complete,customwebbaseduserinterfaceforcomplex,datadriven, webapplicationstypicallyhundredsoreventhousandsofdistinct webpages.Thisapproachallowsyoutoquicklycreatesophisticated pages,including: Databasetableviewpageswithcomplexdatagridcontrols Individualrecordviewpages Add/Edit/Viewpagesforeachtableviewandrecordtype Reports Datainputformsandeditabletables Accountmanagementpages
CustomizingGeneratedApplications
Further,mostdeclarativemethodapplicationgeneratorstypically workwiththeexpectationthattheyarenotproducingallofthecode fortheapplication,onlymostofit.Asaresult,theyprovide mechanismsforincorporatingcustomcodeaspartoftheprocess. Formanyapplications,someorallofthefollowingmayberequired: Integrationwithexistingcustomsystemsusing programminglanguagessuchasVisualBasic,C#orJ#. Theadditionofcustomapplicationlogic. Additionalorcustomizeddatavalidationcode. Adjustmentofstylisticelementsrangingfromchangingthe applicationslookandfeelthecolors,fontsandother visualelementstocreatingmorecomplexpagelayouts withmultipledatabaseconnectedtables,fieldsandfilter controls.
66
applications.Thecustomizationsofthegeneratedapplicationare preservedwhenyouregeneratetheapplication. Thisprocessisdiscussedingreatdetaillaterinthisdocumentinthe ModifyingGeneratedApplicationschapter. 100%AccesstoGeneratedCode Applicationgeneratorsbasedonthedeclarativemethodgenerateall ofthecodeyouneedforaworkingapplication,andtypicallydont requireanyadditionalserversidelibrariesorlicenses.Productsthat claimtohelpautomatedevelopment,butalsorequirespecialserver softwarefromthetoolvendortoactuallydeploytheapplicationcan nolongerbeconsideredstateoftheart.Sometimes,theseold fashioneddeploymentschemesimposeunnecessaryperformanceor functionalbottlenecks.Someevenimposeadditionallicensing restrictionsonhowtheapplicationcanbedeployed. Modernapplicationgeneratorsimposenosuchrestrictions. Nowthatyouhaveabasicunderstandingofhowapplication generationworks,letsexploretheprocessinmoredetail.Thenext sectiondescribeshowcodegenerationtagsandlayoutpagesare used,detailsthecomponentbindingprocess,explainshowdatabase tablesarelinkedtoapplications,andexplainshowapplication generationproducesthepresentationlayer,theapplicationlayer, andthedatalayerofeachandeveryapplicationitcreates.
UsingDeclarativeMethodstoSpecifyanApplication
Aswereviewedearlier,theapplicationsuserinterfacedepends greatlyuponthelayoutpagesyoucreateHTMLinfusedwith codegenerationtags.Letslookathowyoucanuseyourfavorite HTMLeditortocreatethelayoutpageswithanydesignyouchoose. AllHTML,DHTML,andclientsidescriptinginthesefilesis incorporatedintotheASPXpagesgeneratedbytheapplication generator.
LayoutPages
Whenusingadeclarativemethodapplicationgenerator,HTML layoutpagesdefinetheapplicationswebbaseduserinterfaceand containcodegenerationtagsthatdefinewhichdataboundcontrols youwantonthevariouspages(moreaboutthisinthenextsection). LayoutpagesarenormalHTMLfileswith.HTMLfileextensions. TheycancontainanyHTMLyouwish,inanydesignyouwish. Mostlayoutpagesarecreatedusingoneofthepopularwebpage
67
HowCodeGenerationTagsWork
Whenusingadeclarativemethodapplicationgenerator,any combinationofsimpleXMLbasedcodegenerationtagscanbe placedinyourlayoutpagestoaddcomponentssuchasdatagrids, fieldvalues,filters,buttons,andimagestoyourwebpages.Just placetheappropriatetaginlayoutpagesatthelocationwhereyou wishthespecificcontroltoappear. Youcanusecodegenerationtagsto: Addanynumberofdataboundcomponentstoawebpage, includingtables,records,fieldsandfilters.Createpagesof anysophisticationandlayout.
68
Codegenerationtagsareveryeasytouse. BecausecodegenerationtagsareXMLstatements,anyHTMLeditor canbeusedtoaddthemtoanyneworexistingHTMLlayoutpage. HTMLeditorsandwebbrowsersignorethemfordisplaypurposes, andallowthepagestobeviewedwithoutseeingthecodegeneration tag. Theapplicationgenerator,however,interpretsthemduringthe componentbindingandapplicationgenerationprocesses,and replacesthemwiththecodeforcorrespondingwebcontrols,code behindlogicandtransactionmanagement. Unlikemanyscriptinglanguages,codegenerationtagsarentSQL queries,soneitherthedevelopernorthewebdesignerneedlearnthe SQLlanguage.TheapplicationgeneratorgeneratesalloftheSQL queriesusinginformationgatheredabouteachofthecode generationtagsduringthebindingprocess. Codegenerationtagsaredesignedtobeusedbywebdesignersthe graphicartistswhodesignthecreativelayoutofwebpages withoutrequiringthemtobecomeprogrammersorlearnanynew language.Awebdesignercandropacodegenerationtagintoaweb pagespecifyingonlythetagtypeandname.Therearenoadditional parameterstolearnorprogram. Codegenerationtagsdonotspecifydatabasebinding.The applicationgeneratorpromptsthedeveloperfortheadditional informationitneedstogeneratethepagecomponentspecifiedby eachcodegenerationtag.Thus,programmerscanfocusonlayout withoutworryingabouthowtoconnectthecomponentstothe database. Codegenerationtagsexistforeverythingfromverysimpletohighly complexpagecomponents.Sometagsinstructthetooltogenerate codetodisplaydataonapage,whileothertagsinstructthetoolto generatenavigationandfilteringcontrols.Stillothersgovernpage layout.
69
Code Generation Tags Used by Iron Speed Designer Field Display Tags FieldLabel FieldValue Record Tags Record Table Tags Table ItemTemplate AlternatingItemTemplate SeparatorTemplate HeaderTemplate FooterTemplate Button Tags ImageButton LinkButton PushButton Table Component Tags FieldStatistics Pagination TableStatistics
Theapplicationgeneratorbindsthesecodegenerationtagswiththe rightdataduringthebindingprocess.Later,duringtheapplication generationprocess,theapplicationgeneratorreplacesthecode generationtagswithASPXandtheappropriatecontroltags(suchas Microsoft.NETservercontroltags). TheImageTagAHelloWorldExample OneofthesimplestcodegenerationtagsistheImagetag.The Imagetagdisplaysanimageinthegeneratedwebpage,andcan referenceaURL,afilename,ordatabasetable.Theexamplebelow showsanImagecodegenerationtaginanHTMLlayoutpageand theresultingpage.
<HTML> <body> <GEN:Image Name=Logo /> </body> </HTML>
70
When using Iron Speed Designer, after binding the Image tag to a URL and generating the application, the resulting page looks like this.
WecanbuildonthisexamplebyaddingasecondImagetag.
<HTML> <body> This is the first image: <br><GEN:Image Name="Logo1" /><br> This is the second image: <br><GEN:Image Name="Logo2" /> </body> </HTML>
After binding two Image tags to two different URLs and generating the application, the resulting page looks like this.
71
Whenbindingthistag,theapplicationgeneratorpromptsyoufor theinformationnecessarytoconnectthebuttontotheappropriate applicationfunction. Nowthatyouvebeenintroducedtothenotionofcodegeneration tags,andhaveseenhowthesetagsareincludedinHTMLfiles,itsa goodtimetoexplorehowanapplicationgeneratorcanusethesetags tolinktheHTMLpagestothedatabase. UsingtheFieldValueTagtoDisplayData Probablythemostcommonlyusedcodegenerationtagisthe FieldValuetag.TheFieldValuetagtellstheapplicationgeneratorto writethecodetofetchafieldfromadatabaserecordanddisplayit onawebpageatthespecifiedlocation.Duringtheapplication generationprocess,theapplicationgeneratorreplacestheFieldValue tagwithapresentationlayercontrolinthegeneratedASPXorASCX file. AStandAloneFieldValueTagExample TheFieldValuetagcanbeinsertedbyitself,aloneinalayoutpage, orwithinasurroundingRecordtagorTabletag.Belowisavery simplelayoutpagethatcontainsastandaloneFieldValuetag, whosefieldnameisCompanyName. FieldValuetagsmaybeusedstandaloneanywhereinyourlayout pages.Duringthebindingprocess,theapplicationgenerator promptsyoufortheparticulardatabasetable,field,andselection criterianecessarytofetchtheappropriatedatafieldfromthe database. TheexamplebelowshowsasingleFieldValuetagplacedinalayout page.
<HTML> <body> <GEN:FieldValue Name=CompanyName /> </body> </HTML>
72
LiketheImagetag,theFieldValuetagisplacedanywhereinyour HTMLlayoutpagewhereyouwishthedatatobedisplayed.
The FieldValue tag is bound to a database table and field. After generating the application, the resulting page looks like this. Youmaywonderhowthegeneratedapplicationknewwhichrecord tofetchanddisplay.Intheexampleabove,weboundeachofthe FieldValuetagstouseaquerystringparameterpassedinviathe pagesURL,e.g.:
http://qa-net/Alan1/MyPages/Invoice2.aspx?ID=ALFKI
Inthiscase,Invoice2.aspxisthenameoftheASPXpagegenerated bytheapplicationgeneratorfromalayoutpagenamed Invoice2.html.IDisthequerystringparameterusedtoidentifythe primarykeyoftherecordbeingretrievedfromthedatabase.This name,ID,wasarbitrarilychosenandthereisnothingspecialabout ID.ItequallywellcouldhavebeenKeyoranyothername. ALFKIistheprimarykeyvaluethatuniquelyidentifiestherecord wewishtodisplay.Again,thereisnothingspecialaboutthisvalue; itcouldhavebeenanyotherprimarykeyvalueintheCustomer table. Laterinthegenerationprocess,whenyoubindthelayoutfile,the applicationgeneratorwillaskyoutoselecttheparticulardatabase table,field,andselectioncriterianecessarytofetchtheappropriate datafieldfromthedatabase. GroupingFieldValueTagswithRecordTags Typically,FieldValuetagsaregroupedwithinanenclosingRecord tag(asshowninthesamplelayoutpagebelow).TheRecordtag groupstogetherFieldValuetagsthatfetchanddisplaydatafromthe samephysicalrecord.TheRecordtagprovidesamostconvenient waytooptimizethegeneratedcodebecauseasingleSQLqueryis generatedfortheRecordandassociatedFieldValuetags.Ifthereis noenclosingRecordtag,eachFieldValueisgeneratedasaseparate controlwithitsownSQLquery.
<HTML> <body> <GEN:Record Name=Customer> <td><GEN:FieldValue Name="FirstName"/></td> <td><GEN:FieldValue Name="LastName"/></td> <td><GEN:FieldValue Name="Address"/></td> <td><GEN:FieldValue Name="City"/></td>
73
74
LinkingDatabaseTables,ViewsandQueriestoanApplication
Nowthatwevedescribedthemechanicsofusingcodegeneration tagstocreateplaceholdersinfordataboundcontrols,letsexplore howapplicationgeneratorsspecifywhichdataisrelevanttothe application.
Shipping Methods
Shipping Carriers
Orders
Suppliers
Order Details
Products
Main Tables Lookup Tables Images, PDFs, etc. Users File Library
You start with your database tables, as represented by this simple database schema. Then, using Iron Speed Designer, you identify database tables to which the generated data-bound controls will be bound. This process, called linking, points Iron Speed Designer at the specific database table schemas, foreign key relationships, and other parameters that it ultimately uses to generate the SQL statements and stored procedures that are the bulk of the generated database layer.
Thefirststepinthisprocessinvolvestellingtheapplication generatorwhatdatabasetablesarerelevanttotheapplication.To
75
facilitatethisconfiguration,developersusinganapplication generatorwilluseaspecialsetoffeaturesorwizard,tospecify exactlywhatdatabasetablesshouldbeassociatedwiththe application. Usingawizardlikethis,developerscanlinkanynumberofdatabase tablestotheapplicationfromanynumberofdatabases.Thereisno practicallimittothenumberoftablesthatcanlinktotheapplication. Armedwiththisinformation,theapplicationgeneratorthenqueries theindicateddatabasesandcollectstheschemasoftheselected tablesaswellasrelatedforeignkeyrelationships.Theinformationis usedduringthecomponentbindingandapplicationgeneration phases.Thetoolwillusethetableschemasofthelinkedtablesin ordertogenerateappropriateSQLqueriesanddatabaseaccesscode. Similarly,foreignkeysareusedwhengeneratingmultitablejoins andothersimilarSQLqueries.
The user selects the database tables to be linked and Iron Speed Designer imports the table schema and associated foreign key relationships with other tables. Remember,anapplicationgeneratorisnotadatamodelingtool;it cannotcreateormodifydatabasetables(schemadefinitions)norwill itgraphicallydepictrelationshipsbetweenthevarioustables.For manyyearsnow,databasetoolswiththissortoffunctionalityhave beenavailablefromavarietyofvendorstoassistwithdatabase designandimplementation.Theapplicationgeneratorworksin conjunctionwiththesedatabasedesigntoolstoputwebbased applicationsintoproduction.
76
TheComponentBindingProcess
Oncethedatabasetableshavebeenidentified,componentbinding whichreferstotheprocesswheretheapplicationgeneratorfuses eachindividualdataboundcontrol(representedbythecode generationtagsinlayoutpages)toitsunderlyingdatasources,takes place. Individual components on the page, represented by code generation tags, are bound to the underlying database tables and fields. This allows Iron Speed Designer to generate specific code and SQL queries corresponding to the underlying database tables.
Usingawizardwithintheapplicationgenerator,youselectalayout pagetobind.Theapplicationgeneratorthenscanstheselected layoutpageandpresentsalistcontainingeachcodegenerationtag inthepage.Itthenallowsyoutobindeachtagtotheappropriate datasource(s),selectdisplaystyles,andsetotherparametersspecific tothetagstype. Basedonitsuniquepurpose,eachcodegenerationtagpromptsthe applicationgeneratortorequestrelevantbindingparameter informationfromyou.Forexample,anImagecontrol(Imagecode generationtag)isboundtotheURL,filenameordatabasefield containingtheimagetobedisplayed.Similarly,theTablecontrol (Tablecodegenerationtag)isboundtotheunderlyingdatabase tableormultitablejointobedisplayed,alongwiththelayoutsofthe headerrow,datarows,andfooterrows.
77
Forthosetagsassociatedwithtablefieldsandrecords,the informationcollectedincludesselectioncriteria.Theselection criteriadeterminewhichrecordsareselectedfromthedatabasefor displayorediting,andprovideabuiltinfilteringmechanismto specifyhowmuchdatatodisplaywithinaRecordorFieldValue control. ThisselectioncriteriaformsthebasisoftheunderlyingSQLquerys WHEREclause.Dependingontheselectioncriteriayouspecify, theresultsetcanbeassimpleasasinglerecordfromasingle databasetableorascomplexasmultiplerowsfromamultitablejoin (asshowninthefollowingfigures). For each code generation tag found in the layout file, Iron Speed Designer determines what information it needs about the component and then asks you for that information. In this illustration, a FieldValue tag is bound to its data source.
In addition, Iron Speed Designer asks for information on how to display the data both to specify the exact table and field as well as the style that the data should use on the page.
78
SourcingFromParentsRecordorCurrentRowinaTable
Forexample,fieldsdonthavetobeboundoneatatime.Typically, theyreboundinconjunctionwithrecordsortables.Theselection criteriaofthecontrolsassociatedRecordorTabletagareused. Selecting the data source as the parent tags record allows a Record or Table tag to aggregate data retrieval for a collection of enclosed FieldValue tags.
79
In this example, the customer information is sourced from a single record in the Customers table and displayed on the web page. The Record code generation tag is bound to the Customers table. The individual FieldValue tags are set to source their data from Select record(s).
The record retrieved by the parent tag a Record tag or Table tag determines the data displayed for the enclosed FieldValue tags.
80
AddingaNewRecordtoaDatabaseTable
When binding the tag, use this Record tag option to create the code that adds a new record to the database. Here,thefieldorgroupoffieldsenclosedbyaRecordtagisadded asanewrecordtothedatabase.Whenyoubindthetaginthis fashion,theapplicationgeneratorcreatescodethatallowstheuserto enteranewrecordintothedatabase.
<GEN:Record Name=Customer> NOTE: Code generation tags are <td><GEN:FieldValue Name="FirstName"/></td used to both display data as well as <td><GEN:FieldValue Name="LastName"/></td> input data, depending on their <td><GEN:FieldValue Name="Address"/></td> component bindings. Either way, there is no difference in how the code <td><GEN:FieldValue Name="City"/></td> generation tags are used in your <td><GEN:FieldValue Name="State"/></td> <td><GEN:FieldValue Name="ZipCode"/></td> layout page. <td><GEN:FieldValue Name="Country"/></td> </GEN:Record>
In this example, the name, address, and other contact information is collected from the web page and inserted into the Customers table in the database. The Record code generation tag is bound to the Customers table. The individual FieldValue tags would have their data sources bound to Add new record as shown above.
81
TheApplicationGenerationProcess
Whenyoupressthegeneratebuttoninanapplicationgenerator, theentirethreetierarchitecture,withallofthecodenecessaryfor eachlayer,isgeneratedatonce.Thetoolgeneratesyour applicationsASCX,ASPX,C#,SQL,andVisualBasicfiles. Thefollowingfigureprovidesavisualdiagramthatrepresentsthe varietiesofcodeandfilesthataregeneratedineachlayerofthe application. Sincetherearethreeinputsintotheapplicationgenerator(layout pages,databasetableschemas,andcomponentbindings),youmight assumetheresaonetoonecorrespondencewiththelayersinthe application.Thisisnotthecase.Severalinputsaffectmultiple layers.Forexample: Whilethelayoutfilesaretransferrednearlyverbatiminto ASPXfiles,eachcodegenerationtagisreplacedwithan appropriateASP.NETcomponent. Componentbindinginformationisusedtospecifythose ASP.NETcontrolsinthepresentationlayer.Additionally, itsusedtospecifyapplicationlayerlogic,suchasthedata validationcode. TablebindinginformationisusedtogenerateVisualBasic codeintheapplicationlayer(suchasthedatabaseaccess classesandthedatavalidationcode),aswellastheSQL queriesinthedatabaselayer.
82
The relationship between the application generation inputs and the application layers.
PresentationLayerGeneration
Duringtheapplicationgenerationphase,thelayoutfilesareusedas thebasisforallASPXpagesandASCXcontrols.Theapplication generatorpassesthroughalloftheHTML,DHTML,andclientside scriptinglanguageswhengeneratingtheASPXpages.However, whenacodegenerationtagisencountered,theapplicationgenerator replacesitwiththecorrespondingdataboundcontrol. Theapplicationgeneratorgeneratesusercontrolsthatinheritfrom thebaseclassesofthetargetplatform.WhenusingIronSpeed Designer,forexample,thisistheMicrosoft.NETstandard UserControlclass,anditsapplicationgenerationprocessalsocreates VisualBasiccodebehindclassesfortheASPXpagesandASCX controls.(Youcaneasilyextendorcustomizethesecontrolsby writingVisualBasiccodeinthecodebehindclassesforthepageand controls.) Inmanycases,anapplicationgeneratorwillactuallygeneratemore thanoneusercontrolforeachcodegenerationtag.Theseadditional
83
controlsaretypicallyvalidatorcontrolsthatenableserverside validationofthedataenteredbytheapplicationuser.
ApplicationLayerGeneration
Theapplicationgeneratoralsocreatesasetofclassesthathandle issuessuchaspagemanagement,databaseaccess,security,anddata validation.Manyofthegeneratedclassesinheritbehaviorfrom .NETframeworkclasses,whichprovideadvanceduserinterface controlsandservermanagement. Insidethefiles,theapplicationgeneratorcreatesaclasshierarchy thatisgranularandpredictable.Forexample,IronSpeedDesigner createstwoclassesforeachwebpage,named<page_name>and <page_name>Gen.Thatis,awebpagenamedViewProductshas twoclassesassociatedwithit,ViewProductsandViewProductsGen. The<page_name>Genclassesareregeneratedeachtimeyou regeneratetheapplication.The<pagename>classesaregenerated onlyonceandcalledsafeclasses.Thesecanbemodifiedto containcustomizedcodethatwillnotbeoverwrittenwhenthe applicationisregenerated.
System.Web.Ui.Page (.NET Class) BasePage (Iron Speed Base Class) ViewProductsGen (Generated Application Class) ViewProducts (Safe Class)
Iron Speed Designer creates a predictable set of classes for all UI controls. The generated classes are replaced each time you regenerate your application; however, the Safe classes are only generated once. As a result, the Safe classes can contain customized extensions to your application.
Theapplicationgeneratorcreatesclassesforallobjectsincluding pages,tables,records,fields,buttons,menus,andsoon. Althoughanapplicationgeneratorcreatesarunningapplication whenitgeneratescode,noonecanexpectanuncustomized, automaticallygeneratedapplicationtohavetheexactlookandfeel orfunctionalitythatisdesiredforaproductionapplication. Developerscommonlymakeseveraltypesofcodeextensionsto thesegeneratedapplications,including: Addingspecializedcustomerdatavalidationroutines Addingcustomcalculatedfieldvaluesusingdatafromthe database
84
DatabaseLayerGeneration
Generatedapplicationsaretypicallyconfiguredwithapagebased transactionmodel.Thismeansthatchangesmadetoanyunderlying databasetableonthecurrentwebpagearenotstoreduntiltheuser clicksOK(ortakesasimilaractiononthepage).Asaresultofthe action,allchangesarecommittedtothedatabaseaspartofasingle transaction.IronSpeedDesignergeneratedapplicationsusethe transactionclassesinADO.NETtoperformcommitsandrollbacks. AnapplicationgeneratorautomaticallygeneratesalloftheSQL statementsrequiredforeachdatabaseconnectedform,webpage, table,andreportintheapplication,aswellasallofthedatabase accesslogicandstoragemanagementcode.ItgeneratestheSQL statementsbasedontheinformationcollectedduringthedatabase andcomponentbindingprocesses,soyoudonotalwaysneedto knowSQLtobuildpowerfulapplicationswithanapplication generator. SomeapplicationgeneratorsplacemostofthegeneratedSQLin storedprocedures,enhancingruntimeperformancebecausethe queriesarestoredandexecuteddirectlyfromthedatabase.This prudentapproachminimizesthenumberofroundtripsbetweenthe applicationprogramandthedatabase,andfurtherenhancesoverall applicationperformance. Specifically,whenusingIronSpeedDesigner,alldatabasetable view,recordview,recordinsertion,recordupdate,andrecord deletionSQLqueriesareplacedinstoredprocedures.
BonusAutomation(EvenMoreCodeYouDontHaveToWrite)
Inadditiontowritingthecodeforeachlayeroftheapplication,a goodapplicationgeneratorwillalsothrowinanumberoffeatures andcapabilitiesthateveryapplicationshouldhave.Often,these featuresarecutbydevelopmentteamswhoareshortontimeand resources,andrushingtogetabasicapplicationintoproduction.
85
Sample application generated with Iron Speed Designer with many bonus features. Letsexploreafewoftheseextras,andseehowapplication generatorsaddextraordinaryrobustnessandcompletenesstoeven thesimplestapplication.
SearchTools
Becauseoftheubiquityoftheweb,usersofallskilllevelshave grownaccustomedtousingtextsearchfacilitiesinmanyweb applications,andasanavigationalaidonthewebitself.Asaresult, expectationsaboutsearchfacilitiesspillovertoallkindsofweb applications,andthatincludestheonesyourebuilding. Whilebasictextsearchtechnologyiswellunderstood,and straightforwardtoimplement,manyapplicationsneverincludeit becauseofthetimeandenergythatsrequiredtoimplement,test, andmaintainthefunctionality. Whenusinganapplicationgenerator,searchfacilitiesareincluded withtheapplicationbydefault.Assuch,youcandeliverbasic searchfeaturesaspartoftheapplicationyourecreatingwithno additionalwork.
86
DataSorting&PageNavigation
Aswithsearchfacilities,experiencewithcommercialwebsiteshas raiseduserexpectationsaboutdatasortingfeatures.When presentedwithmultiplepagesoftabulardata,usersnowexpectto beabletosortthedatabyclickingontheheadingsofthetablethats presented.Theyalsoexpecttobeabletospecifyhowmanyrecords shouldbedisplayedonaperpagebasis,andthenpagethroughthe data,onapagebypagebasis. Thesoftwaretechnologyneededtodeliverthesesortingand navigationfeaturesisstraightforwardtoimplement,butittakestime andefforttogetitright.Whilesuchfacilitiesareintegraltoalldata intensivewebapplications,thecodetoimplementthesefeaturesis tediousandtimeconsumingtowrite,test,andmaintain. Whenusinganapplicationgenerator,datasortingandpage navigationfacilitiesareincludedwiththeapplicationbydefault.As such,youcandeliverthesebasicfeaturesaspartoftheapplication yourecreatingwithnoadditionalwork.
Import&ExportFacilities
Justabouteveryapplicationinvolvesdatathatsomeuserwillwant toexportfrom,orimportinto,thedatabase.Hereagain,many commercialwebapplicationsdeliverthesefeaturesfortheuserwith theclickofabutton.Assuch,userexpectationshaverisen,without afullappreciationofthetechnologythatsneededtodeliverthese capabilities. Implementingdataimportandexportfacilitieswithinwebbased businessapplicationscandramaticallyreducethebacklogofservice requeststhataretypicallyhandledbytheDBA.Onceavailable, theseimport/exportfacilitiescaneliminateanentireclassofIT supporttroubleticketsbyenablinguserstoselfservicethese requests. Butimplementingreliableimportandexportfeaturescanbetricky toimplement,andgettingitwrongcanbedisastrous.Assuch, manyapplicationsaredeployedwithoutthesefeatures,andIT supportstaffscontinuetobeburdenedwiththeserequests. Hereagain,whenusinganapplicationgenerator,import/export facilitiescanbeincludedwiththeapplicationbydefault.Assuch, youcandeliverbasicimport/exportfeaturesaspartofthe applicationyourecreatingwithnoadditionalwork.
87
ExceptionandErrorManagement
Oneofthemostneglectedfeatures,andyetoneofthemostusefulto endusers,ishighqualityexceptionhandlinganderrormanagement. Whenusersmakeorperceiveerrors,theexperiencetheyhave copingwiththeproblemformsthemostpermanentimpressionof theprogram.Inextremecases,poorerrorandexceptionhandling canleadtotheuserabandoningtheapplicationaltogether. Applicationgeneratorscanlargelyalleviatethisrisk,ifnoteliminate itentirely.Foreachapplicationtheycreate,theyanticipateseveral differenttypesoferrorsthatcanoccuratruntime.Thefollowing fewpagesdescribeafewdifferentkindsofpotentialerrors,andhow ageneratedapplicationshouldhandleeachtypeoferror. UserInputValidationErrors Astriteasitmaysound,thetruthisthatthelargemajorityof problemsasoftwareapplicationwillencounterwillresultfromuser error.Simplethingsliketypos,enteringdatainthewrongfield,or skippingarequiredfield,shouldresultinthegeneratedapplication displayinganerrormessagetotheuser. Toensureitsnotmissedbytheenduser,theerrormessageshould bedisplayedinapopupdialogboxorinlineimmediatelyatthe timeoftheerrorandprovidetheuserwithanopportunitytocorrect theerror. Agoodapplicationgeneratorwillautomaticallygenerateinputfield validationcodeforallsupportedfieldtypes.Thisthoroughlytested validationcodewillnotifytheuserofinputerrorsdirectlyonthe webpage,andgivetheuserachancetocorrecttheerrorsand resubmittheentry. InternalErrors Internalerrorsarecausedbyincorrectsystemconfiguration,or becausearequiredresourcehasbecomeunavailable.Theserequired resourcescanincludeanetworkconnection,awebserver,adatabase server,etc. Forthesekindsoferrors,thegeneratedapplicationshoulddisplay anerrormessageonawebpagefortheapplicationuser,andexplain thereasonfortheerror.Additionally,thegeneratedapplication shouldlogtheseerrorstotheserverseventlog.Loggingthese eventswillenablethemtobeviewedthroughtheEventViewerby thesystemadministrator,andhopefully,helpidentifytheproblem, andaccelerateitsresolution.
88
DatabaseExceptionErrors DatabaseerrorsoccurwhentheSQLstatementsexecutedareinvalid orwhenthedatabaseisnotconnected.Thesetypesoferrorsare largelyavoidedwhenthecodeiscreatedwithanapplication generator.SuchtoolsshouldalwayscreatesyntacticallycorrectSQL queries,butsometimes,thesequeriescanbreakwhendatasources arereorganized,whenneededtablesarearchived,etc. Hereagain,thegeneratedapplicationshouldgenerateanerror messagefortheenduser,andprovideasmuchinformationas possibleaboutthenatureoftheproblem.Aswithinternalerrors notedpreviously,seriouserrorsshouldalsobeloggedtotheservers operatingsystemeventlogsotheycanbeviewedthroughtheEvent Viewerbythesystemadministrator. ApplicationLogicErrors Applicationlogicerrorsoccurwhenthesoftwareapplicationitself hasabug.Typically,applicationgeneratorsautomaticallycreate codethatfeaturescorrect,highlyreliable,applicationlogic. However,errorscanbeintroducedwhenyouextendorchangethe generatedcode. Eveninthesecases,thegeneratedapplicationshouldinclude unhandlederrors.Whentheyarewithinapage,theycanensurethe errorsarenotedintheeventlogsotheycanbeviewedviatheEvent Viewer.
Summary
Inthischapter,weveintroducedhowthemostfundamental capabilitiesofamodernapplicationgeneratoroperate.Weveseen howyoucandirecttheapplicationgeneratortocreatethebasic componentsofyourapplication,andalsoroundoutmanystandard featuresthatareoftenoverlooked. Inthenextchapter,wellfocusonthedatalayerofthegenerated application,andexplorehowdatabaserelatedfunctionalityis createdwithapplicationgenerationtools.
89
90
Meeting&ExceedingUserExpectations
FamiliaritywiththeWebhasmadetodaysenterpriseendusers moredemandingthaneverwhenitcomestoadvanceduserinterface featuresforwebapplications.Addingtheexpectedcombinationof filtering,fulltextsearch,navigation,paginationandothercontrolsis atimeconsuming,oftentedioustaskforapplicationdevelopers. Therearelikelydozensofdifferentpagesinyourapplicationthat eachneedSQLqueriestoimplementfunctionality,pluswrapper codetoglueitalltogether.Thosepagesincludeinputforms, reports,andallsortsofpageswheredataisdisplayedinavarietyof formats.WritingtheSQLqueriesisoftenthemostchallengingtask forwebapplicationdevelopers,usuallyrequiringthehelpofaDBA orSQLspecialist. ThenextfewpagesdiscusshowapplicationgeneratorslikeIron SpeedDesignercreatedatabaseconnectedwebapplicationswith sophisticatedfeaturessuchassorting,filteringandreporting.Well alsoexplorespecificaspectsofthegeneratedcodeandthe methodologyforgeneratingthesourcecodeforthesefeatures automatically. Specifically,wellcoverthefollowing: SQLefficiency Transactionmodel LocationoftheSQLstatements Existingdatabaseviews Compositeprimarykeys Complexforeignkeyrelationships Concurrencycontrol Cursormanagement
SQLEfficiency
SQLstatementsarehardtowriteevenifyouareanexpert. However,writingefficientSQLqueriescanhaveagenuineeffecton theperformanceandscalabilityofyourapplication.Thisis
91
especiallytrueinthestatelessenvironmentoftheweb,where maintainingtransactionstatebetweenpagesisdifficult. ApplicationgeneratorsshouldapproachSQLgenerationfroman efficiencyperspective.Forexample,theyshouldplacequeriesfor multitablejoinsinasinglequerytoreduceroundtripstothe database.Andtheyshouldtakeintoaccountfieldsthatareindexed, andpossiblygosofarastosuggestingfieldsthatshouldbeindexed inordertoimproveperformance.Theyshouldalsogiveyouthe choiceofplacingyourSQLdirectlyintheapplicationlayerorin storedprocedures. TechnologythatgeneratesSQL statementsmustbetied specificallytoyourdatabase schema.Genericqueries (queriescomposedonthefly thatdonotuseparameterized fieldvalues)canslowdown applicationperformancesince theyoftenrequireseveralround tripstothedatabaseto complete.Specificqueriesthat includethenamesoffield valuessavetripsbecausethey usetheactualfieldnamesfrom yourdatabase.Thisishowyou wouldwritethestatementsby hand,andthisiswhatyou shouldexpectfromaqualityapplicationgenerator.
TransactionModel&TransactionManagement
Inwebbasedapplications,itsparticularlydifficulttoaccumulate transactioninformationacrossmultiplepages,movingfromone pagetoanother,becauseofthestatelessnatureoftheweb.This makesitimportanttounderstandwhatconstitutesatransactionand whenitshouldbecommittedtothedatabase.Forexample,atypical webbasedordercheckoutprocess,suchasashoppingcart,collects differentaspectsoftheorderinaseriesofpages,suchasthe customersnameandaddress,creditcardinformation,andshipping instructions. Thedifficultyisthattherearefewoptionsforstoringinformation collectedonthosepagesotherthaninthedatabase,inthe.NET cache,orinbrowsercookies.Whileeachapproachhastradeoffs,an applicationgeneratorcanfreeyoufromtheburdenofimplementing theseschemes.
92
Unfortunately,storingauserstransactioninformationinbrowser cookiesposessecurityandbandwidthissues.So,formost applications,storingtransactioninformationinthedatabaseisthe bestoption.Thismakesitimportanttounderstandwhatconstitutes atransactionandwhenitiscommittedtothedatabase. Moderngeneratedwebapplicationsarecreatedwithapagebased transactionmodel.Thismeansthatallofthechangesmadetoany recordortableonthecurrentwebpagearesubmittedwhentheuser clicksOKortakesasimilaractiononthepage.ThisOK commitstothedatabaseaspartofasingletransaction.Specifically, IronSpeedDesignerapplicationsusethetransactionclassesin ADO.NETtoperformcommitsandrollbacks. This order form illustrates how data can be pulled from (or inserted into) multiple database tables into one page in a parent-child relationship. When Save is clicked, records are inserted into several tables, including the Order, Order Details, and Customer tables. In particular, multiple records are inserted into the Order Details table, one record for each line item. The entire transaction is concluded with a single commit.
Applicationgeneratorsusestoredprocedurestoupdatethedatabase whenappropriateanddirectedbythedeveloper.Ifthereare multiplerelatedrecordsbeingaddedorupdatedaspartofasingle transaction(e.g.,OrderswithmultipleOrderItems),theneach recordisupdatedindividually,andrequiresmultipleroundtripsto thedatabase.Therecordinsertions,updates,anddeletions themselvesareperformedwithindatabasestoredprocedures,but theapplicationlogiccallingthesestoredproceduresresidesinthe generatedVisualBasic.NETcode. Inamultiparttransaction,theentiretransactionisconcludedwitha singleCOMMITstatementattheendofthetransaction.Whilethese manytomanyupdatesdorequiremultipletripstothedatabase,
93
theyarecommittedtothedatabasebyasingleCOMMITattheend ofthetransaction.
LocationoftheSQLStatements
Inanydatabaseapplication,thereisafundamentaldecisionasto whethertoplacetheSQLstatementsintheapplicationlayerorinthe databaselayer.Asyoumightexpect,thereareadvantagesand disadvantagestoboth. BecauseapplicationgeneratorswritealltheSQLstatements, developerscanoftenchoosewheretheywanttheSQLgenerated strictlybasedonperformanceandsystemarchitecturecriteria,and withoutregardtoinhouseexpertiseconstraints.Thereisgenerally norequirementthatthedeveloperlearnSQLorproprietarystored procedurelanguages,suchasPL/SQL(OraclesStoredProcedure Language)orTransactSQL(MicrosoftsSQLServerLanguage).
Inline(Embedded)SQL
IfSQLstatementsareplacedintheapplicationlayer,theyare embeddedintheapplicationssourcecode.Inthisstyle,theburden ofwritingandmaintainingtheSQLtypicallyfallstotheapplication developersbecausetheyaretheoneswritingtheapplicationsource code.Inthiscase,thedeveloperofthecodewritesandinsertsthe SQLstatementsattheappropriateplaces.Thisapproachaffords developerstheopportunitytotightlyintegratetheSQLandthe queryresultswithintheirsourcecode.Assuch,italsorequires applicationdeveloperstobeexpertsintwolanguagestheir primarydevelopmentlanguageC#,VisualBasic,orJavaaswell asSQL.Thisisoftentimesdifficultfordevelopers. Therearealso,ofcourse,goodreasonstoplaceSQLqueriesdirectly inthedatabasesuchasmatchingthestyleofexistinglegacy applications,databaseconstraints,andDBApreference.
StoredProceduresEnhancePerformance&Maintainability
IfSQLstatementsareplacedinthedatabaselayer,theyresideinthe databaseasstoredprocedures.Thisapproachnotonlymovesthe SQLtoadifferentlayerinanntierarchitecture,butinmostcases movesittoaphysicallyseparateservermachine.Inthisstyle,the burdenofwritingandmaintainingtheSQLtypicallyfallstothe databaseadministrator(DBA)oranindividualdeveloperwhose primaryskillandexpertiseiswritingSQL.Inthisscenario, developersrelyontheDBAtoimplementpartoftheirapplication (theSQL)andinterfacetheircodewiththestoredprocedurescreated bytheDBA.
94
CentralizingtheSQLinthedatabaselayerallowsforacertain amountofapplicationlogictobemaintainedinacentrallocation andsharedacrossmultipleapplicationprograms.Moreover,many developersandDBAconsiderimplementingqueriesinstored proceduresasabestpractice.Consolidatingmostorallofan applicationsSQLinstoredproceduresmakesiteasiertoreview, modifyandtuneindividualquerieswithouthavingtodiginto applicationcode. Finallythereistheissueofexecutionperformance.Generally,more complexSQLstatementscanbeplacedinstoredprocedures.When executedlocallyonthedatabaseserver,thistechniqueoftenreduces thenumberofroundtripsbetweentheapplicationprogramandthe database.Efficiencyisalsoimprovedbecausethequeriescanbepre parsed,potentiallysavingparsingtimeifthequeryisdynamic. Whilebandwidthandlatencydontalwayspresentproblemsfor manybehindthefirewallapplications,theycanpresentaproblem inwebservicesenvironmentswheretheapplicationprogramsarent physicallynearbythedatabaseexecutingthequeries.
GeneratingStoredProcedures
AgoodapplicationgeneratorwillautomaticallygeneratealltheSQL statementsrequiredforeachdatabaseconnectedform,webpage, table,andreportinyourapplication,aswellasallthedatabase accesslogicandstoragemanagementcode.Becausethisgenerated SQLisbasedonyourdatamodelanduserinterfacedesign,youdo notneedtoknowanySQLtobuildapplicationswithanapplication generator.Further,theapplicationgeneratoroftenprovidesa varietyofdatafiltersandnavigationcomponentstoprovideyour enduserswithadditionalviewingandreportingflexibility. Fromourperspective,theapplicationgeneratorshouldplacemostof thegeneratedSQLinstoredprocedurestoenhanceruntime performance(becausethequeriesarestoredandexecuteddirectly fromthedatabase).Enhancingperformancefurther,thisapproach minimizesthenumberofroundtripsbetweentheapplication programandthedatabase. Allthedatabasetableview,recordview,recordinsertion,record updateandrecorddeletionSQLqueriesshouldbeplacedinstored procedures.Tablejoinqueries,however,areplacedingenerated VisualBasic.NETfunctions. Transact-SQL Stored Procedures Add Purpose Insert a single record in the table.
95
Transact-SQL Stored Procedures Delete DeleteRecords DrillDown Export Get GetList GetStats
Purpose Delete a single record from the table. Delete a set of records based on search criteria. Get a list of distinct column values based on search criteria. Export records from the table based on search criteria. Get a single record from the table. Get a list of records based on search criteria. Get summarized or calculated information from a table based on search criteria. Several possibilities including counting records, summing or averaging values. Update a single record in the table.
Update
Iron Speed Designer generates these database stored procedures, one set for each table and database view. The stored procedures for creating, updating, and deleting records accept field values as parameters, such as record ID's and filter strings, and then execute the appropriate INSERT, UPDATE, or DELETE statements in the stored procedures.
DatabaseViewsProvideDataConsolidation
Adatabaseviewissimplyasubsetofthedatabasesortedand displayedinaparticularway.Adatabaseviewlimitstherecords displayedandcouldcontainasubsetofrecords,suchasproducts thatareinstock,orcustomersthathavepurchasedgoodsgreater than$1000.Aviewcouldalsocontainasubsetoftheinformation foreachitem,suchasproductname,description,andprice,but notthedimensionsoftheproduct.Similarly,theorderofthe columnsisspecifiedinthedatabaseview.Someapplicationsuse databaseviewsorstoredprocedurestoembedsecurityinthe databasesothattheapplicationcannotcompromisesecurity regardlessthequeryused. Becausedatabaseviewsareanintegralpartofyourunderlying databasestructure,itsimportantthatyourgeneratedapplication embracethem.Manyorganizationsusedatabaseviewsasawayof consolidatingdataforreportingandotheruseswhereacommon definitionisrequired. ApplicationsgeneratedbyIronSpeedDesigner,forexample,fully supportdatabaseviews.Foreachview,youcancontrolwhich columnsaredisplayed,whatordertheyaredisplayedin,howwide eachcolumnis,howthedataissorted,andwhattypesofrecordsto display.Ingeneral,youcanperformanyoperationonadatabase viewinIronSpeedDesignerthatyoucanonanytable.Toprotect
96
theintegrityofthedatabase,youcannotinputdatadirectlyintoa databaseview.Thismustbeperformedintheunderlyingtables fromwhichthedatabaseviewisderived. A screen shot from Iron Speed Designer showing a combination of tables and database views included in an application.
PrimaryKeyRelationshipsPermitRecordEditing
Primarykeysindatabasetablesindicatewhichfieldsareusedto uniquelyidentifyeachrecord.Forexample,aCustomertable generallyhasaCustomerIDprimarykeyfieldthatcontainsaunique customerIDvalueforeachindividualcustomer.Inorderto generatecodethatcanupdateordeleteanindividualrecord,the applicationgeneratormustknowwhichfield(s)touseasthe primarykeyforselectingandaccessingindividualrecords. Frequently,atablewilluseseveralfieldstogethertoformaprimary key.Thesearecalledcompositeprimarykeys.Forexample,a Customertablemayusethecombinationofaphonenumberfield andlastnamefieldtouniquelyidentifyacustomerrecord. Theapplicationgeneratordeterminescompositekeyrelationshipsby queryingthesysteminformationintheconnecteddatabase(s).If multiplerowsarereturnedforagiventable,itmeansthatthetable
97
An example web page generated by Iron Speed Designer. The generated application uses primary key relationships to retrieve the appropriate Order table record for editing. The application uses foreign key relationships to retrieve the associated Customer table records for editing.
ForeignKeyRelationshipsPermitMultiTableJoins
Foreignkeyrelationshipsinadatabasespecifyhowonetableis relatedtoanothertable.Forexample,anOrdertablemayhavea CustomerIDfieldthatisaforeignkeytotheCustomertable.The OrderIDfieldindicateswhichCustomerrecordisassociatedwith theparticularorder.
98
Iron Speed Designer uses foreign key relationships specified in your database to generate complex pages with multi-table joins like this one. Foreignkeyscanalsoindicateonetomanyrelationshipsbetween tables.Forexample,anOrdertablemayhavearelatedOrderDetail tablecontainingmultiplelineitemsforeachindividualorder.The OrderDetailtablehasanOrderIDfieldthatisaforeignkeytothe Ordertable. Forexample,IronSpeedDesignerusesforeignkeyrelationshipsto constructmultitablejoinsinSQL.Intheexampleshownabove,the generatedapplicationisabletodisplayCustomerandOrderDetail informationwithinasingleOrderpage,byautomaticallygenerating thetablejoinsinSQL. Agoodapplicationgeneratordeterminesforeignkeyrelationships byqueryingthesysteminformationintheconnecteddatabase(s).If multiplerowsarereturnedforagivenforeignkeyname,itmeans thattheforeignkeynameisacompositeforeignkey,i.e.,multiple foreignkeyfieldsreferencingatablewithacompositeprimarykey. Specifically,IronSpeedDesignersupportstwotypesofforeignkey relationships: Explicitforeignkeys.Iflinkeddatabasescontainexplicitforeign keyrelationships,IronSpeedDesignerautomaticallyusesthem whengeneratingyourapplicationsSQL. Virtualforeignkeys.YoucanalsoinformIronSpeedDesignerof implicitforeignkeyrelationshipsbetweenyourdatabasetablesthat maynotbedefinedinthedatabase.IronSpeedDesignerdoesthe rest,generatingappropriateapplicationlogicandSQLqueries. IronSpeedDesignerdoesnotdifferentiatebetweenvirtualand explicit(real)foreignkeyswhenitgeneratestheunderlyingdatabase
99
accesslogicandSQLquerystatements.Forexample,virtualforeign keysareusableforonetooneandonetomanyrelationshipsand alloweditingofmultiplerelatedrecordsfromeitherasingleor multipletables. ForeignkeyfieldsareshownintheDatabasessectionofIron SpeedDesigner.Forexample,anOrderstablemayhavea CustomerIDfieldthatisaforeignkeytothe Customers.CustomerIDfield.(Ifthetablehasmultiplefields referencingthesameprimarytable,thentheforeigntablehasa compositeforeignkey.)
ConcurrencyControl/ConcurrencyHandling
Inanymultiuserenvironment,concurrencybecomesanissuewhen twousersupdatethesamerecordinthedatabase,oneafterthe other.Ifbothusersareviewingthesamerecord,andthenmake independentchanges,howtheapplicationhandlesconcurrency determineswhichuserschangesupdatethedataintherecord.The wayyourapplicationhandlesconcurrencyaffectstheabilityofyour applicationtohandlesimultaneoustransactionsagainstthesame records.
100
Optimistic concurrency handling ensures that a second user does not unintentionally overwrite the changes made by a first user. Insomeapplications,thesecondusertoupdatearecordwill overwritethechangesmadebythefirst.Inothers,theapplication willwarntheseconduserthattherecordtheyareviewinghasjust beenupdated.Instillothers,thesecondusersviewisautomatically updatedwhenthefirstuserupdatestherecord. Intraditionalapplicationdevelopment,thedeveloperhastohand codeconcurrencyhandlingintotheapplicationlayer.Thiscanbe trickycodetowrite,andithastobewrittenforeachtransactionin yourapplication.Unfortunately,doingitrightdoesntearnyouany specialrecognitionwhereasmistakescanhaveyouhuntingbugsfor days. Implementingconcurrencyhandlingistypicallyverytediousand mustbeappliedcarefullytonearlyeverytransactioninan application.Applicationgeneratorscreatethisconcurrency managementcodeforyou,savinghoursofhandcodingheadaches.
101
PessimisticConcurrency
Pessimistic,ornegative,concurrencycontroliswhenarecordis lockedatthetimetheuserbeginshisorhereditprocess.Inthis concurrencymode,therecordremainslockedforthedurationofthe edit.Theprimaryadvantageisthatnootheruserisabletogetalock ontherecordforupdating,effectivelyinforminganyrequestinguser thattheycannotupdatetherecordbecauseitisinusebysomeone else. Thereareseveraldrawbackstopessimisticconcurrencycontrol.If theusergoesforacoffeebreak,therecordremainslocked,denying anyoneelsetheabilitytoupdatetherecord,evenifithasbeen untouchedbytheinitialrequestor.Also,inordertomaintainrecord locks,apersistentconnectiontothedatabaseserverisrequired. Sincewebapplicationscanhavehundredsorthousandsof simultaneoususers,apersistentconnectiontothedatabasecannotbe maintainedwithouthavingtremendousresourcesonthedatabase server.Moreover,somedatabasetoolsarelicensedbasedonthe numberofconcurrentconnections.Assuch,applicationsthatuse pessimisticconcurrencywouldrequireadditionallicensesforuse. Becauseofthisdrawback,almostallapplicationsuseoptimistic concurrencycontrol.
OptimisticConcurrency
Withoptimistic,orpositive,concurrency,therecordisnotlocked duringtheeditphase.Instead,therecordislockedforasplitsecond justbeforethenewchangesarecommittedtothedatabaseand immediatelyunlockedafterthechangeshavebeenmade.Optimistic concurrencyisgenerallyusedinenvironmentswithalowcontention fordata,suchaswebapplications,wherethereareminimalchances oftwousersneedingtoupdatearecordincloseproximitytoeach other. Ofcourse,withoptimisticconcurrencyhandling,itbecomes incumbentuponeveryrequestortocheckiftherecordhasbeen updatedbeforetheycommitanychanges.Thereareseveral techniquesfortestingforanoptimisticconcurrencyviolation.One involvesincludingatimestampcolumninthetable.Inatestfor optimisticconcurrencyviolations,theUpdateDateandTimeare comparedwiththeoriginalvaluereturnedwhentheeditbegan.If
102
ConcurrencyHandlinginGeneratedApplications
IronSpeedDesigneralsoimplementsoptimisticconcurrency handlingingeneratedapplications.Specifically,IronSpeed Designercalculatesachecksumforeachrecord.Ifthechecksumis differentwhentheapplicationpreparestoupdatearecord,thenthe applicationassumestherecordwaschangedbyanotheruser.A warningmessageisdisplayedontheapplicationpagealertingthe seconduser.
CursorManagement
AdatabasecursoristheresultingsetofrecordsreturnedbyanSQL query.Thecursorallowsyoutorequesteachrecordinsequenceso thatthequeryresultsmaybedisplayedinadatagrid,reportor otherwiseoperatedupon. Cursor management allows each record to be requested in sequence and displayed in a data grid or report.
103
DataRecency
Oneissuethatemergeswithcursorsisthefreshnessofthedatain theresultset.Aslongasthecursorisinuse,itcontainsthesetof recordsretrievedwhenthequerywasoriginallyperformed. However,thisdatamaygrowstaleovertime,especiallyifthequery resultisbeingdisplayedinascreenthatanapplicationuseris reviewingoveraperiodoftimeminutesorhours.Theapplication userisviewingtheresultsetthatwascurrentwhenthereportwas firstcreated. Inapplicationswheretheunderlyingdatachangesfrequently,itmay bedesirabletoreruntheSQLqueryastheapplicationusermoves frompagetopageintheirreport.Thisensuresthateachdisplayed pagehasthemostcurrentdata.Whilethisalsoplacesanextraload onthedatabasebecauseitmustrerunthequerymorefrequently,all modernrelationaldatabaseshaveverygooddatacachemanagement thatsignificantlyreducesthecostoffrequentlyrerunningqueries.
DataManagement
Asecondissuetoconsideriswhethertheentireresultsetispulled fromthedatabaseintotheapplicationlayer,awellknownproblem with.NETdatagrids.Whenaresultsetcontainsonlyafew hundredrecords,movingallofthedataintotheapplicationprogram requiresminimalbandwidthandmemorytostoreandmanipulate theresultsetintheapplication.Whentheresultsethashundredsof thousandsormillionsofrecords,however,itbecomesnearly impossibletoefficientlymoveallofthatdataintotheapplication program.Veryfewapplicationprogramsarestructuredto manipulatethatquantityofdatainmemorywithoutadditionalfile managementlogic,whichdefeatsthepurposeofusingthe underlyingdatabasewhichprovidesexactlythesefacilities.So,in applicationswheretheresultsetscanbelarge,itsbestfor applicationstoretrieveonlyamanageablesubsetoftheresultset fromacursorsuchasonepageofdataoperateonthatdata,and thenrequestthenextsubset.
DatabaseCursorsinGeneratedApplications
Inkeepingwiththisphilosophy,applicationsgeneratedshoulduse databasecursorstoretrievedatafromthedatabase.Thecursor shouldbeusedtoretrievethenumberofrecordsbeingdisplayedon thedatabasetableviewwebpages.Onlyonepageofdatashouldbe
104
retrievedfromthedatabaseanddisplayedatatime,minimizingthe datatransmissionloadandtheapplicationsmemorystorage requirements.Queryresultsshouldnotbestoredinatemporary databasetableview,butratherretrieveddirectlyfromthedatabase anddisplayedtotheuser. Theapplicationprogramdoesnotneedtomaintainthestateofthe cursor.Whenthenextpage(oranyotherpage)isrequested,aSQL querycanberunagaintorequesttheneededpagesdata.Thequery parameterscanincludethepagenumberrequestedandthebatch size,whichisthenumberofrecordsperpage.TheSQLquerycanbe rerunsothatanynewrecordsaddedsincethefirstpagewas displayedarenowretrieved.Bycontrast,ifthecursorweresimply maintained,anynewrecords,recordupdates,andrecorddeletions wouldnotbereflectedwhengoingfrompagetopage.Moreover, maintainingthecursorrequirestheapplicationtokeepthedatabase connectionopen,whichisnotanefficientuseoftheavailable databaseconnections.
When requesting a new page to display in a tabular data grid, applications generated by Iron Speed Designer run queries afresh so that the most current data is retrieved. In this example, clicking on the Next Page or Previous Page buttons at the top of the table instantiate a new database cursor to retrieve the result set. Only the currently requested page of data is retrieved from the database and displayed on the web page, eliminating the need to cache data in the application layer of the generated application.
Summary
Thischapterhascoveredonlybrieflythemainissuesofbuildingthe databaselayerofamodernntierapplication.Thebottomlineisthat expectationsforfullfeaturedwebbasedapplicationsarehigh amongexecutivesaswellasendusers.
105
106
Part7) AutomatingApplicationSecurity
APragmaticApproach
107
Thisseemingly straightforward EditOrder pagecancreate codehavoc whenyouhave toadd enterpriseclass security, concurrency andtransaction management codebyhand.
GeneratingRoleBasedApplicationSecurity
Mostapplicationsserveavarietyofconstituentscustomers, customerservice,marketing,sales,andmanagement,tonameafew. Itsincreasinglycommonincontemporarywebapplicationsto permitmuchbroaderaccesstoapplicationsandtheirunderlying datathanwascommonwithclientserverapplications,whichhad morerestricteduserbases.Withbroaderusecomesanincreased needtopartitiondataaccordingtotheusertypeandsometimes downtotheindividualuseraswell. Oneofthemostconvenientsecuritymechanismsisrolebased securitybecauseitallowsindividualuserstobeassignedintoroles, andthenaccessisgrantedattherolelevel.Thismakesfor convenientadministrationbecausemostapplicationsneedjusta handfulofroles5or10atmostbutmayhavethousandsofusers.
108
Broadlyspeaking,applicationgeneratorsshouldsupportatleast threetypesofrolebasedsecurity: 1. Simplesigninauthentication.Applicationusersmustsign intotheapplication.Onlyuserswithusernamesand passwordscansignin,givingyoucontroloverwhocan accessyourapplication. Singleroleauthentication.Applicationusersmusthavea designatedroleinordertoaccessaparticularwebpage. Individualwebpagesareconfiguredsothatonlythoseusers withthedesignatedrolecanaccessthepage.
2.
SimpleSigninAuthentication
Simplesigninauthenticationdistinguishesbetweenuserswhoare signedinandthosearenot.Userswhoarenotsignedinarecalled anonymoususers.Becauseoftheflexibilitytherolebasedsecurity model,youcangrantaccesstoindividualpagestoeithersignedin oranonymoususers,ortobothsignedinandanonymoususers. Thisisveryusefulwhenyouwantyourapplicationtopresentone viewofyourdatatoasignedinuserandadifferentview,perhaps morelimited,tousersthathaventsignedinordonthavean account(anonymoususers). Simple sign-in authentication distinguishes between users who are signed-in and those who are not (anonymous users).
109
SingleRoleAuthentication
Singleroleauthenticationdistinguishesbetweenvariousgroupsof usersbasedontheirassignedrole.Individualapplicationpagescan beconfiguredtopermitaccesstouserswhohavetherequiredrole. Inthesingleroleauthenticationmodel,individualapplicationusers haveonlyoneroleassignedtothem.However,theapplication pagescanbeconfiguredtopermitaccesstomultipleroles,for example,salesandmarketing. Single role authentication distinguishes between different classes of users based on their assigned role.
Eachuserhasoneroleassignedtothem.Thisroleassignmentisin thesamedatabasetableastheusernameandpasswordinformation requiredforsimplesigninauthentication. Single role security requires just a single database table with basic user name and password information.
MultipleRoleAuthentication
Inmoresophisticatedrolebasedsecuritysystems,userscanbe assignedmultipleroles,effectivelygivingthembroaderaccessthan wouldbegrantedbyasinglerole.Asimpleexampleisthatevery customerservicerepresentativemaynotbeauthorizedtoaccess customercreditcarddata.Inthisexample,thecustomerservice supervisorhasoneroleasarepwithaccesstocustomeraccount
110
information,andasecondroleasmanagerwithauthorizationto issuerefundsorcredits.Ideally,thoserolesareaccessible simultaneouslywithoutrequiringtheusertologinunderasecond role. Multiple-role authentication distinguishes between different classes of users based on their assigned role. Individual application users can have multiple roles assigned to them, and individual web pages can be configured to permit access by multiple roles.
Multiple role security requires linking several database tables with basic user name and password information.
SecuringYourGeneratedWebApplication
Sofar,weveintroducedthebasicapproachestorolebasedsecurity, anddiscussed,atahighlevel,someofthecircumstancesthatmight leadyoutochooseoneapproachoranother.Nowletstakea
111
specificlookathowapplicationgeneratorsassistyouincompleting thiswork. Courteousapplicationgeneratorswillautomaticallyaddenduser authentication(signin)accesscontrolasastandardfeaturetoyour generatedapplications.Withsuchatool,youshouldbeableto assignanynumberofrolesandgiveaccesstoanynumberofrolesto eachuser,andcreateasigninfeaturebasedonyourownusertable inyourdatabase.Usingsuchfacilitieswithinapplicationgenerators, youcanquicklysecureindividualpagestospecificroles. Specifically,theapplicationgeneratorshouldsupport: SeparatetablesforUsers,UserRoles,andRoles.Youcan haveaone,two,orthreetableuserrolesconfiguration. Avarietyofdatatypesforthesetablessoyouarenot requiredtochangeyourschematouserolebasedsecurity. Pageaccessrestriction,menuhiding,andbuttonhiding. Usingemailtosendpasswordremindersforlostpasswords.
Nowletsexploreeachofthesestepsindetail.
CreatingUserAccounts
Rolebasedsecurityispredicatedonyourapplicationsabilityto knowwhotheuserissothatappropriatepageaccesscanbegranted. Thisrequiresuserstologintotheapplication,whichinturnrequires yourdatabasetocontainusernameandpasswordinformationfor users. Ifyouareimplementingrolebasedsecurity,yourapplication generatorwillrequireonetableinyourdatabasetobedesignatedas aUsersTable.TheUsersTablecontainsalistofallofyour applicationsusersandcanbeanytableinyourapplication.Within thistable,youmusthavethreeimportantfieldsfortheapplication
112
generatortousewhenbuildingthesigninmechanisminyour application:UserID,UserName,andPassword. AnytableinyourdatabasecanbeaUsersTable;thereshouldbeno restrictiononwhichtablemaybedesignatedasaUsersTableor whatotherfieldsitmayhaveotherthanthoselistedabove. Field UserID FirstName LastName UserName Password Address Type Integer String String String String String An example table designated as a Users Table. This table contains normal account information, including First Name, Last Name, and Address, as well as the required sign in information (shown highlighted).
CreatingUserRoles
Rolebasedsecurityrequiresuserstobelongtodifferentroles.Based ontherolesassignedtoindividualusers,theyaregrantedaccessto specificpagesthatpermitaccessforthoseroles.Yourdatabasewill needatablethatidentifiestherole(s)assignedtoeachuser. Agoodapplicationgeneratorwillsupporttwodifferentstylesof userassignedroles: Userhasonlyoneassignedrole.Eachuserhasoneandonly oneroleassignedtohim.Theroleassignmentcanbeplaced eitherintheUsersTable(seepreviouschapter)orina separateUserRolesTable. Userhasmultipleassignedroles.Eachusercanhavezeroor morerolesassignedtohim.Theroleassignmentsareina separateUserRolesTable,effectivelycreatingaonetomany relationshipbetweeneachindividualuserintheUsersTable andmultiplecorrespondingentriesintheRolestable.
113
PlacingRoleInformationinYourUsersTable Insituationswhereanindividualuserhasonlyoneassignedrole, theroleassignmentisusuallymaintainedintheUsersTabledirectly, althoughthereisnorequirementthatthisinformationbeinthe UsersTable. Field UserID FirstName LastName UserName Password RoleID Address Type Integer String String String String String String A Users Table with a role assignment for each user. This configuration permits only one role per individual user. This example shows the table designated as your applications Users Table containing the sign in information (UserID, UserName, and Password), as well as the assigned role (RoleID).
ConfiguringYourWebPagesforRoleBasedSecurity
Onceyouvespecifiedyourusers,andassignedtheappropriateroles tothoseusers,youllneedtospecifywhichusersgetaccesstowhich pages.Theapplicationgeneratoryouuseshouldmakethatprocess easy.Thetoolshouldofferstandarddefaults,aswellasquickaccess toyourspecificroles.Usingthetool,youshouldbeabletoquickly specifywhichroleshaveaccesstoeverypageinyourapplication. Each web page you wish to secure should be configured to accept only those users with the appropriate roles. Here is a screen from Iron Speed Designer where these permissions are set.
ConfiguringSignInPagesforYourApplication
TheSignInandSignOutpagesinterfacewiththerolebasedsecurity system,andpermityouruserstologinandlogoutofyour application.
114
An example Sign In page automatically generated by Iron Speed Designer as part of its rolebased security implementation. Signing out of an application.
SigningIntoYourApplication&ManagingLostPasswords
Anapplicationgeneratorcanautomaticallygenerateadefaultsign inpageforyourapplication.Ofcourse,youcanmodifyorreplace thepagethatsprovided.Heresanexampleofsuchadefaultsign inpage:
115
AdditionalSecurityIssuestoAddress
Inadditiontothemajorsecurityorientedfeaturesnotedabove,an applicationgeneratorcansaveyoutimebyhandlingamyriadof othersecurityissues.
AutomaticSignout
Forexample,manydevelopersconsideritabestpracticetohavethe applicationstheycreateautomaticallylogoutapplicationusersafter aperiodofinactivity.Thisfeatureguardsagainstidentitytheftthat canoccurwhenauserleavestheirwebbrowseropentoan application,andanunauthorizedpersonusesthatbrowsertoextract identityinformationorperformtransactionsintheapplication. Afteraperiodofinactivity,say30minutes,theapplicationuser shouldbepromptedtosigninagaintoreaffirmtheiridentity.Of course,theapplicationgeneratorshouldmakeiteasytochangethe amountoftime.
<sessionState . . . Timeout=30 />
When using Iron Speed Designer, the time out interval is set in the web.config file of the generated application, as shown here.
DataTransmissionEncryption
Eventually,mostwebbasedapplicationstypicallyusethepublic internetforremoteaccess,orforaccessbycustomersorsuppliers. Asaresult,yourapplicationshouldencryptinformationthats transferredbetweenyourdatabaseandtheusersbrowser. TodaysmodernwebserversofferbuiltinSSL(securesocketlayer) encryption.Thisstandardsecurityensuresthatnoonecanseeyour dataasitpassesoverthepublicinternetoroveryourprivate intranetandlocalareanetworks(withoutanextraordinaryamount ofeffort). Theapplicationgeneratoryouuseshouldcreatetheapplicationso thatitusesencryptionbydefault.
ImpliedSecurityfromanNTierArchitecture
InadditiontoemployingdataencryptionwithSSL,generated applicationscangarneranadditionallevelofsecuritybyemploying anntierarchitecture.Insuchasetup,thedatacollectedfroman applicationuserispassedthroughthewebserver,tothegenerated application,andthentothedatabase.Thisntierarchitectureofthe generatedapplicationensuresthatyourdatabaseisnotconnected
116
ActiveDirectoryandLDAP
ActiveDirectoryandLDAP(lowoverheaddirectoryaccessprotocol) aresinglesignonfacilitiesavailablefromMicrosoftandother vendorsthatprovideasinglesignonanduserauthentication facility.Whenusingasinglesignonfacility,anendusercansign inonce,andthatsigninwillbetransferredtoallapplicationsused bytheuserduringthesession.Suchanapproachsavestheuser fromtheinconvenienceofsigningintoeachandeveryindividual applicationtheymayaccessduringasession.Moreover,these facilitiesprovidecentralizeduseraccesscontrolforITdepartments, andmakeiteasierforthemtomanageuseraccounts. Becauseofthestandardnatureofthissortoffeature,application generatorsshouldcreateapplicationswithsupportforActive DirectoryandLDAPautomatically,orprovideeasytouseexamples thatdemonstratehowsuchfacilitiescanbeintegratedintothe applicationstheygenerate.
PasswordStorage
Mostapplicationswithbuiltinpasswordsecuritystoretheuser nameandpasswordinformationintheunderlyingdatabase.While thisisaconvenientapproachandallowsforeasyadministration,it isntthemostsecurebecauseavarietyofusers,mostlyinternal,will typicallyhaveaccesstothepasswordinformation. Amaliciousemployeewithaccesstopassworddatacansteala usersidentityandforgebogustransactions. Sadly,thisformofidentitytheftisalltoocommon.Oncea passwordhasbeenstolen,itcanbeusedbyinsiderstocreate fictitiouscustomeraccounts.Theseboguscustomeraccountscan thenbeusedtoshipproductstomaildrops(stealingmerchandise), ortoinitiaterealcreditcardrefundstofakeaccounts(fraud).
117
Onesimpleandeffectivedefenseagainstthisformofidentifytheftis encryptingthepasswordinthedatabaseusingoneofseveralsimple encryptionprotocols.Onemethodhastheapplicationprogram encryptthecleartextpasswordbeforecomparingittothestored encryptedpasswordaspartofitsauthenticationprotocol.This methodpreventsunauthorizedusersfromusingthepasswords becausethecleartextversionisntstoredinthedatabase. Anapplicationgeneratorshouldautomaticallygeneraterolebased securityforyourapplication.Itshouldusetheusernameand passwordfieldsinyourdatabase,andnotrequireanyspecialtables createdusingthetool.Usingthetool,youshouldbeabletoquickly andconvenientlybuildapplicationsontopofyourexisting database,usingexistingusernamesandpasswords,andaddingthe codetoencryptthepasswordsshouldbehighlyautomated.
HandlingSQLInjectionAttacks
SQLinjectionistheactofenteringaparticularlyoddlooking stringintoatextboxorquerystringinordertohavepotentially maliciousSQLcodeexecute.Forexample,ifyouhaveanASPpage thatacceptsasaquerystringparameteranIDfield,andthisIDfield isthenusedtogenerateadynamicSQLquery,thenyourapplication maybesubjecttoanSQLinjectionattack.
118
Anapplicationusermayenteraquerystringlike:
1; DELETE FROM Orders (or some other malicious SQL statement)
Withthiscode,theSQLwillbeexecutedandyourdatabasetable deleted!Youcancombatthisparticulartypeofattackbystrictly enforcingdatatypevalidationofinputfields. Applicationsgeneratedbyanapplicationgeneratorshouldbe completelysafefromSQLinjectionattacks.Theyshouldensure yourapplicationissafebyensuringthatalldatathataffectsthe constructionofSQLstatements(andstoredprocedureparameters) goesthroughatleastoneabstractionlayerthatproperlyencodesor interpretsthedata. Whileitispossibleforadevelopertodesignanapplicationthat bypassesthissecurityandallowscustomcodeand/orenduser inputtounsafelyaffecttheSQLgeneration,doingsoshouldrequire anapplicationcustomizationtocircumventthegeneratedsecurity mechanisms. Moreover,theapplicationgeneratorshouldincorporatefiltersinto dataentryfieldsandtables.Thesefiltersshouldtrapandreplace stringinputsfromtheuser,andcompletelypreventtheuserfrom runninganymaliciousSQLcommand(suchasdeletetable).
119
120
Althoughanapplicationgeneratorcreatesarunningapplication whenitgeneratescode,noonecanexpectanuncustomized, automaticallygeneratedapplicationtohavetheexactlookandfeel orfunctionalitythatisdesiredforaproductionapplication. IronSpeedDesigner,forexample,providesawealthoftoolsand techniquesthatmaketheprocessofcustomizingbothan applicationspresentationandapplicationlayereasier.Some customizationsaredonewithwizardsandallowthedeveloperto easilymodifytheapplicationgenerationprocess.Otherchangesand extensionscanbemadebyextendingthecodethatisautomatically generated. Developerscommonlymakeseveraltypesofcodeextensionsto generatedapplications,including: Addingspecialized,domainspecific,datavalidation routines Addingcustomcalculatedfieldvaluesusingdatafromthe database Integratingwithotherapplicationprograms Integratingwithwebservices
Whilenoapplicationgeneratorcananticipateeverypossible extensionandenhancementtoeverygeneratedapplication,itshould createtheapplicationinawaythatmakestheseextensionseasy. Inpractice,generatedapplicationsareeasiertoenhancethanthose writtenbydevelopers.Humanprogrammers,becausetheyre human,dontalwaysorganizetheirworkinaconsistentfashion. Butthemethodical,mechanizedapproachtakenbyanapplication generatoralwayswritesandorganizesthecodeitcreatesthesame way.Itrepeatsthisapproach,dayafterday,applicationafter application,withnovariance. Inadditiontothismechanicalconsistency,applicationgenerators consistentlycreateeveryapplicationwithacompletestateoftheart ntierarchitecture.Becauseofitsautomatedapproach,an applicationgeneratornevercutscorners,andalwaysfollowsallof thebestpracticesthathavebeenbakedintoitsapproach. Assuch,applicationgeneratorsbringalevelofpowerand functionalityhistoricallynotassociatedwithquickanddirty applications.Armedwithapplicationgenerators,youcanprovide unprecedentedfunctionality,security,androbustnessevenfor
121
applicationscreatedanddeployedonshortnotice,andwithvery smalldevelopmentteams.
StandardsforGeneratedCode
Ofcourse,theresultsyouachievewillvarywidelywiththe applicationgeneratoryouchoosetoemploy.Illformedcode generators,inthepast,haveproducedcodewithoutmuchregardfor consistency,organizationandcoherence,allofwhichare requirementsforcreatingenhancementsanddownstream maintenance.Onebadexperienceusingapoorlydesignedtoolcan causedeveloperstoresist,orevenswearoff,thewholeideaofusing anapplicationgenerator. Ifyouvehadsuchanexperience,restassuredthattodays commercialgradeapplicationgeneratorshavemadegreatstridesin producingcodethatmeetsdeveloperexpectationsinthisregard. Letsexplorehowtodaysmodernapplicationgeneratortools approachtheproblem,andcreatecodethatseasytounderstand, extend,andmaintain.
WellorganizedCode
Mostapplicationgeneratorsgenerateyourapplicationssourcecode andrelatedfilesinawellorganizedfilesystemhierarchy.Each applicationisgeneratedwithexactlythesamehierarchicalstructure, makingiteasytomodifyandextendgeneratedapplicationsonce youcomeuptospeedonthearchitectureofthegenerated application. InthecaseofIronSpeedDesigner,allsourcecodefortheapplication canbefoundintheCustomfolderwithinadirectorynamedafter theapplication.ThegeneratedASPXpages,associatedclasses,and thegeneratedsourcecodefilesassociatedwithaspecificdatabase table,areallstoredinafoldernamedafterthetable.Withineach tablefolder,thecodeisfurtherseparated.
122
<Application 1>
<Application 2>
<Application 3>
<Application 4>
Platform
App
bin
Custom
Library
Theme
Common/Src
Components
Pages
Misc
Deployed
Internal
Source
System.Web.UI.Page (.NET class) BcBasePage (Base class) View_Products_PageSafeClass (Safe class) View_Products_PageGenClass (Generated class) View_Products_Page (ASPX page)
Insidethefiles,IronSpeedDesignercreatesaclass hierarchythatisgranularandpredictable.For example,IronSpeedDesignercreatestwoclassesfor eachwebpage,named<page_name>SafeClass(the safeclass)and<page_name>GenClass(thegenerated class).Thatis,awebpagenamed View_Products_Pagewillhavetwoclassesassociated withit,View_Products_PageSafeClassand View_Product_PageGenClass.(Thesignificanceof theseparticulartwoclasseswillbediscussedlater whenwediscussmodifyingthecode.)IronSpeed Designergeneratesclassesforallobjectsthatyou wouldexpectincludingpages,tables,records,fields, buttons,menus,andsoon.
TheclasshierarchyoftheView_Products_Page Control.
CodeShouldMeetProfessionalStandards
Applicationgeneratorsshouldwritecleancodeandusestandard programmingconstructs.Theyshouldneveraddextralinesofcode thatmightcomeinhandylater.Becauseyoucaneasilyregenerate theapplicationafteryoumakechangestotheattacheddatabase
123
tableschemaandwebpagedesigns,theapplicationgenerator shouldonlycreatetheexactcodethatisneeded. FilesgeneratedbyIronSpeedDesignerforadatabasetablecalledProducts. Found in <AppID>\Custom\Products EditProductsRecord.aspx EditProductsRecord.gen.aspx.vb EditProductsRecord.safe.aspx.vb AddProductsRecord.aspx AddProductsRecord.gen.aspx.vb AddProductsRecord.safe.aspx.vb ShowProductsTable..aspx ShowProductsTable.gen.aspx.vb ShowProductsTable.safe.aspx.vb ShowProductsRecord.aspx ShowProductsRecord.gen.aspx.vb ShowProductsRecord.safe.aspx.vb Database Related Classes Db20001Products.vb ProductsRecord.vb ProductsRecordBaseClass.vb ProductsUtils.vb ProductsUtilsBaseClass.vb Found in <AppID>\Custom\Components Edit_Products_Record.ascx Edit_Products_RecordGenClass.ascx.vb Edit_Products_RecordSafeClass.vb New_Products_Record.ascx New_Products_RecordGenClass.ascx.vb New_Products_RecordSafeClass.vb Table_View_Products.ascx Table_View_ProductsGenClass.ascx.vb Table_View_ProductsSafeClass.vb Table_View_Products_Header_Row.ascx Table_View_Products_Header_RowGenClass.ascx.vb Table_View_Products_Header_RowSafeClass.vb Table_View_Products_Record_Row.ascx Table_View_Products_Record_RowGenClass.ascx.vb Table_View_Products_Record_RowSafeClass.vb View_Products_Record.ascx View_Products_RecordGenClass.ascx.vb View_Products_RecordSafeClass.vb
Thenamesofallthefiles,classes,functions,andsoonarebased upontheassociatedentity.Forexample,foratablecalledProducts, IronSpeedDesignergeneratesthewebpages,safeclasses,generated classes,anddataaccessclasses,asshowninthetableabove. Inaddition,theapplicationgeneratorshouldautomaticallywriteall thedatavalidationcode,exceptionhandling,andSQLqueriesbased, inpart,onyourdatamodel.Forexample,whenafieldisdeclaredas typeDate,IronSpeedDesignerautomaticallycreatesclassesthat inheritthevalidationmethodsthatchecktomakesurethattheuser enteredavaliddate.
AvoidsCodeOrphaning
Oneofthebiggestproblemswithcodegeneratorsofthepastwas orphanedcode.Thiswascodethatoncegenerated,couldnotbe modifiedorextended.IntodayshighpressureITdepartment,there isnoplaceforcodethatcantbeleveragedforbothcurrentprojects andfutureapplications. Toptierapplicationgeneratorsallowyourapplicationtobe regeneratedrepeatedlywithoutrequiringyoutoreintegrateyour externalcodeextensions.Thiscanbeaccomplishedusinga
124
generatedclasshierarchy,whichhasalayerexpresslyforexternal codeintegrationthatisnotaffectedbyapplicationregeneration. Perhapstheprincipalconcerninusinganapplicationgeneratoris understandinghowtoextendandcustomizethegenerated applicationsothatyourenhancementsarepreservedeachtimethe applicationisregenerated.Yourchoiceofapplicationgeneration toolsshouldpreserveallchangesandavoidorphaningthemodified code. Forexample,theclasshierarchiesgeneratedbyIronSpeedDesigner derivefromthebaseclassesinthe.NETFramework.Subclassing allowsyoutointerceptWindowsmessagesgoingtoaformor control,amongotherbenefits.Aslongasyourmodificationsare segregatedinsubclasses,yourapplicationcanberegenerated repeatedlywithoutreintegratingyourcodeextensions.
IronSpeedDesigner generatesa generatedand safeclassforeach page,tablejoin,and databasetableinyour application.Usethe safeclasstoeasily extendandmodify withyourunique applicationlogic.
AnApproachtoGeneratingExtendableCode
UsingyourfavoriteprogramminglanguageincludingVisualBasic, C#orJ#,youshouldexpecttobeabletoextendyourgenerated applicationto: Addcustomapplicationlogic Addadditionalvalidationcode. Integratewithexternalsystems
InmostapplicationswrittenfortheMicrosoft.NETFramework,for example,thefunctionalityandlogicintheApplicationLayerare derivedfromasetofVisualBasic.NET(orother.NETcommon languageruntimelanguage)classesforpagemanagement,database access,anddatavalidation.Theseclassesprovideadvanceduser interfacecontrolsandservermanagement. Addingyourownapplicationlogictogeneratedapplicationsshould bestraightforward.Theyshouldbespecificallydesignedtosupport codemodifications,andyoushouldbeabletoregeneratean applicationrepeatedlywithoutrepeatedlyreintegratingyourcode extensions.Yourapplicationgeneratorshouldalwayspreserveyour extensions. Forexample,usingIronSpeedDesigner,yousimplysubclassthe appropriatepage,controlordatabaseobjectwithyourcode extensionandregeneratetoreflectyourchanges.Oneparticular layerofclasses(theSafeclasses)isexpresslycreatedforcode integration,andisnotaffectedbyapplicationregeneration.Your
125
codeextensionsarenotoverwrittenwhentheapplicationis regenerated.Thisapproachprovidesahighdegreeofflexibilityin makingcodeextensionstothegeneratedapplication.Youcan overrideanyofthefunctionsormethodsinthegeneratedbase classes,orwriteyourownmethodsincombinationwiththeexisting baseclassmethods. Thisisaccomplishedusingaclasshierarchyinthegenerated application,whichhasasetofsafeclassesexpresslyforcode integrationthatisnotaffectedbyapplicationregeneration.This codeissafebecauseitisntoverwrittenwhentheapplicationis regenerated.Forexample,everypage,record,andcontrolhasits ownSafeclassthatisnotoverwritten,allowingthedeveloperahigh degreeofflexibilityinmakingcodeextensionstotheapplication. Theapplicationgeneratorwritestheunderlyingsafeclassesforyour applicationonlyonce,typicallytheveryfirsttimeeachpageis generated.Oncetheindividualsafeclassforapagehasbeencreated thefirsttime,itisneveroverwritten.Thus,itissafetoaddyour owncodetoandmodifythesesafeclasses. Moreover,adevelopercanoverridefunctionsinthepagesbase class.Typicallyyouintegratecustomcodebyeitheroverridingone ofthemethodsonthebaseclass,oryoucanwriteyourownmethods incombinationwiththeexistingbaseclassmethods. Aspreviouslymentioned,Microsoft.NETsupportsseveral programminglanguages,includingVisualBasic,C++,andC#. BecauseallIronSpeedDesignergeneratedapplicationsare.NET applications,codewritteninanyofthelanguagesthat.NET supportscanbeadded.Thisincludesanycodeextensionsyoumake oranypreexistingcodethatyouintegratewithyourapplication.
Example:ChangingthePresentationLayer
Formostapplications,adeveloperwillwanttochangethelayoutof thedefaultpagesautomaticallygeneratedbytheapplication generator,aswellascreateentirelynewpages.Thesechangesmight rangefromchangingtheapplicationslookandfeel(thecolors, fonts,andothervisualelements)tocreatingmorecomplexpage layoutswithmultipledatabaseconnectedtables,fields,andfilter controls.Applicationgenerationtechnologyprovidesanumberof toolstomakethesetypesofcustomizationseasyforthedeveloper, including: Anumberofwizardsthatenableadevelopertospecifythe typesofpagescreatedforagivendatabasetable,the
126
Youarenotrequiredtohaveeither programmingexpertiseor.NETknowledge tousetheseapplicationlayertools. Forexample,thefollowingfewpages describeanexamplethatshowshowIron SpeedDesignerhelpsyoucreatecolumn sortinglinkstosortbyafieldanywhereon thepage.Youcanalsosortbyfieldsthat arenotdisplayedonthepage. Considerthegeneratedpageattheright, andthelayoutpagebelow.
<div align="center"> <GEN:Table Name="Products"> <table cellpadding="5" style="border-collapse: collapse" border="1" bordercolorlight="#C0C0C0" bordercolordark="#C0C0C0"> <tr style="font-family:Verdana; font-size:10px"> <td> <GEN:FieldLabel Name="SortByName" />  <GEN:FieldLabel Name="SortByPrice" /></td> </tr> <GEN:ItemTemplate> <tr style="font-family:Verdana; font-size:10px"> <td> <b> <GEN:FieldValue Name="ProductName" /> </b> <br />Unit Price: <GEN:FieldValue Name="UnitPrice" /> <br />In Stock: <GEN:FieldValue Name="UnitsInStock" /></td> </tr> </GEN:ItemTemplate> </table> </GEN:Table> </div>
127
Example:AddingCustomDataValidationCode
Validation classes for controls generated by Iron Speed Designer.
WebControls:BaseValidator
(.NET class)
BcBaseIronSpeedValidator
(Base class)
WebControls:CompareValidator CompareValidator WebControls:CustomValidator CustomValidator WebControls:RangeValidator RangeValidator WebControls:RegularExpressionValidator RegularExpressionValidator WebControls:RequiredFieldValidator RequiredFieldValidator .NET Classes Base Classes Iron Speed Run-time Classes
Inmanyapplications,itisessentialtoaddyourowndatavalidation logicorextendthevalidationlogiccreatedbytheapplication generator.Thetoolshouldhelpyoucanaccomplishthistaskeasily byoverridingtheappropriatevalidationfunctionsforanyofthe databoundcontrols,suchasarecordcontrol. Thecodegeneratedforeveryfieldvaluecomponentofatablerow cancontainaRequiredFieldValidator,aFieldValueValidator,anda RecordControlCustomValidatorclass. Youcancustomizetheappearanceorbehaviorofanyofthese validatorsbyoverridingthemethodsinBaseRecordControlthat mostdirectlycontaintheFieldValueandvalidatorcomponents.
128
Overridable methods for BaseRecordControl class createForeignKeyValueListItems getContainer getFieldValue getFieldValueDisplayString getFieldValueString getField getFieldListItems getRecord getTable initFieldControl initUI initValidatorControl isCreateMode OnIronSpeedEvent SetDataBoundRecordInfo setFieldValueString setRecordWorkflowState updateData validateCheckSum validateData
129
System.Web.Ui.UserControl
(.NET class)
BaseRecordControl
(Base class)
Edit_Product_RecordSafeClass
(Safe class)
Modify here
Edit_Products_RecordGenClass
(Generated class)
Edit_Product_Record
(ASCX control)
130
Thecodeshown,inthefileEdit_Products_RecordSafeClass.vb, checkstoseeifvalueisanumberandifthepriceisdivisibleby4.If not,anerrormessageforthefieldisset. BecauseIronSpeedDesignerwrites Edit_Products_RecordSafeClass.vbonlyonce,thedevelopercan regeneratetheapplicationasmanytimesasheorshewishes,and thisfunctionwillpersist. Allcodecustomizationsandextensionsaremadeinananalogous fashiontothisdatavalidationexample.Althoughitdoesrequire knowledgeoftheclasshierarchy,changingthecodeinanIronSpeed Designerapplicationisstraightforward.
EveryUsersRequest,Canyouaddabuttonthat?
Anydeveloperwhohasintroducedanynumberofnewapplications toendusershasexperiencedthefollowingscenario:Youvejust completedademoofthesystemthatyouveworkedforweeksor monthstoproduce.Regardlessofhowwelltheapplication implementstheoriginalgoals,theresalwaysarequesttoaddsome sortofspecialfeaturethatwasntincluded. Ofcourse,addingthebuttongraphiciseasy.Butmakingsureit appearsintherightcontext,andactuallydoessomethinguseful whenyouclickonit,requirescarefulprogrammingandtesting. Likemostthingsrelatedtowebapplicationdevelopment, applicationgeneratorscanhelpdevelopersaccommodatesuch requestsquickly.Agoodapplicationgeneratorwillincludethe abilitytoinsertavarietyofprebuiltbuttonsandconfigurethemto domanyofthemostcommonthingsusersrequest. Thenextfewpagesofferanexampleofhowapplicationgenerators canhelpdevelopersaccommodatesuchrequestsfasterthanever before.
CommonButtonActionsandProperties
Buttonactionsdeterminewhatactionistakenwhenabuttonis clicked.Whilethereareseveralbuttontypesimagebuttons,link buttons,andpushbuttonstheysharethesamebindingproperties, whicharedetailedbelow.
131
IronSpeed Designer allows developersto easily configure commonly requested buttonsand their properties.
Usingtheseconfigurationtoolsinanapplicationgenerator,youcan specifyavarietyofbuttonpropertiesandactions.Simpleproperties includethetexttodisplayinthebuttonorlink,theURLoftheimage tobedisplayed,andthetooltipthehelptextthatsdisplayed whentheuserhoversthemouseoverthebutton. Usingtheactionconfigurationsettings,youcaninstructthebutton toperformavarietyoftaskswhenpressed.Someofthese capabilitiesincludedatavalidation,addingordeletingrecords, exportingdata,filteringdata,openinganewwindowwithnew URL,searchingthedatabase,updatingdata,orexecutingcustom code. Further,youcanconfigureeachbuttontospecifyaconsumerofthe eventwhenactivated.Thiseventhandlingmechanismallowsother controlstotakeactionbasedontheevent.Thisishowpagescan changebasedoninteractingwithusers.Examplesofbutton consumersincludethepage,theparent,theparentrecord,andthe parenttable. WhenabuttoneventredirectstoanewURL,itcanpassdataalong usingURLparameters.Thisdatacanbehardcodedordynamic.
132
TheimageontheleftshowsanIron SpeedDesignerexampleofa redirectURLandassociated parameters.Duringconfiguration, valuesfortheparametersidand nameareURLarguments.At runtime,theseparametersare instantiatedwiththevaluesfrom therelevantrecord.Inthiscase,the valuesfortheidandname parametersare444and michaelrespectively.
PassingPrimaryandForeignKeyValuesinURLs
Usinganapplicationgenerator,youcanspecifythebuttontopass multipleparameters,andeachparametercanbepassedoneormore values.Parameterssuchasprimaryandforeignkeyvaluescanbe passedfromonepagetoanotherthroughthedestinationpages URL.However,theparameterspassedaspartoftheURLshouldnt belimitedtotheprimaryandforeignkeys.Youshouldbeableto passanyfieldvalue,aswellasdisplayvalues.Thedisplayvalues mightbedifferentthanthefieldvaluesforexample,forBoolean fields,thefieldvaluemightbe1or0,butthedisplayvaluemightbe TrueorFalse. TheparameterspassedaspartofRedirectURLandURLParameters shouldbeavailableforanyofthebuttonsorlinks.WhenusingIron SpeedDesigner,forexample,theURLParametersfieldspecifiesa commadelimitedsetofargumentsthatcanbepassedontheURL.
133
Developers using Iron Speed Designer use the Redirect URL and Redirect argument parameters to pass primary and foreign key values between pages when a button is clicked.
Intheexampleshownabove,theRedirectURLusesanargument Orders={PK}toindicatetheOrdersparameterwillbeboundat runtimetotheprimarykey(PK)fieldvalue.Thismeansthatthe parameter{PK}willbesubstitutedwiththerecordsprimarykey (PK)value. PassingPrimaryKeyValuesBetweenPagesinURLs PassingprimarykeyvaluesfromonepagetoanotherviaURLsis verystraightforward.Asanexample,inIronSpeedDesigner,you specify: Field Action URL Parameters Redirect URL Value Redirect ID {0}
134
record.Iftheprimarykeyisacompositekey,thecompositekeyis passedasanargument. IftheIDofthefieldisasingleintegervalue,youcanusetheFV RedirectParametertypetopassthevaluetotheURL.However,if youlaterchangetheIdtoamorecomplexkey,yourexistingpages willnotworkcorrectly.Assuch,werecommendalwaysusingthe IDorPKRedirectParametertypestopassprimarykeystoother pages. PassingOtherValuesBetweenPages Asdiscussedearlier,youcanusetheURLParameterstypestopass anyfieldvaluetoapageviaitsURL.Forexample,topassthefirst andlastnamesfromtheemployeerecord,specifytheURLandthe URLParametersasfollows: Field Action URL Parameters Redirect URL PassingParametersinURLs Acomponentcaninteractindirectlywithothercomponentsby interactingwiththepagesHTTPresponseobjectandcausinga clientsideredirecttoadifferentpage(i.e.AdifferentURL).Thisis similartointeractionusingevents,butinsteadofcreatinganevent object,thecomponentredirectstheclientsbrowsertoanewURL. BydynamicallyconstructingtheURL,thecomponentcanchoosethe pagetowhichtheuserwillberedirected.Also,usingURL parameters,thecomponentcanpassdatatothenewpage.The benefitofthisoverinteractionusingeventsisthatitworksevenfor componentsondifferentpages.However,becauseURLsarelimited toabrowserspecificmaximumlength,thequantityofdatathatcan bepassedtoanewpageisfairlylimited.Also,unlikeevents,a redirectwillcausethecurrentpagetostopprocessingimmediately. Therefore,somesituationsmayrequireacombinationofevent interactionandpageredirection. Therearemanycontextsinwhichpassingdatafromonepageto anotherviatheURLisaconvenientmeansoftransferringdata.This examplepassestheIdsoftwoproductstoapagetoshowhow parameterpassingworks.Twoproductsaredisplayedasaresultof thisexample. Value Redirect FV:FirstName,FV:LastName ViewEmployeePhoto.aspx?First={0}&Last={1}
135
Two different products are selected for display by passing their respective primary key values to the generated application page via URL query string parameters. Thefollowingpagesshowthestepsandthecodeusedtocreatethis functionalitywithamodernapplicationgenerator. First,createanewlayoutpageasfollows:
<div align="center"> <GEN:Record Name="Product"> <table cellpadding="5" style="border-collapse: collapse" border="1" bordercolorlight="#C0C0C0" bordercolordark="#C0C0C0"> <tr style="font-family:Verdana; font-size:10px"> <td align="right">Product Id:</td> <td style="font-weight: bold"> <GEN:FieldValue Name="ProductId" /> </td> </tr> <tr style="font-family:Verdana; font-size:10px"> <td align="right">Product Name:</td> <td style="font-weight: bold"> <GEN:FieldValue Name="ProductName" /> </td> </tr> <tr style="font-family:Verdana; font-size:10px"> <td align="right">Unit Price:</td> <td style="font-weight: bold"> <GEN:FieldValue Name="UnitPrice" /> </td> </tr> <tr style="font-family:Verdana; font-size:10px"> <td align="right">Units in Stock:</td> <td style="font-weight: bold"> <GEN:FieldValue Name="UnitsInStock" /> </td> </tr> </table> </GEN:Record> </div>
136
Example:AddingReportingtoaGeneratedApplication
Inmanycustombusinessapplications,thefirstsetofgoalsforthe applicationrevolvearoundgettingaccesstoandfromasetofdata thatsrelevanttothetaskathand.Oncethebasicfunctionalityof deployinganapplicationthatallowsvarioususerrolestomaintain, andgetaccessto,asetofdata,anewsetofrequirementstendto surface.Oncethebasicsareinplace,usersreappearwithadditional requirementsforversion2.0. Acommonexampleofav.2.0enhancementinvolvesintegrating withanotherprogramtoproducechartsandgraphsforpresentation andanalysispurposes. Letsexplorehowageneratedapplicationcanbeintegratedwitha reportingprogram.Thefollowingexampleshowshowtoadda buttontoapage(generatedbyIronSpeedDesigner)topopulatean existingreport(aCrystalReports.rptfile)anddisplayitinapopular documentformat(AdobesPortableDocumentFormat,PDF). Therequiredstepsinvolve: Customizingageneratedlayoutbyaddingacustombutton. Bindingthenewbuttontoacustomevent.
137
Addingcodeforeventhandlingandreportgenerationtoa safeclass.
ThisexampleusesanapplicationthatsbasedontheNorthwind databasethatcomeswithMicrosoftSQLServer.Hereisthepage thatwillbegeneratedinthisexample. Created with Iron Speed Designer, this modified page adds the new Export to PDF button.
HereisanimageoftheNorthwindProductsreportasrenderedin thebrowserbyAcrobatReader.
Letswalkthroughthestepsneededtocompletethismodification withanapplicationgenerator.
138
Then,youdneedtolocateandopenthelayoutfile,e.g.:
\<AppDirectory>\Source\Products\ViewProductsRecords.html
139
Here,youdsetthefollowing: Field Command name Custom command Consumers Value Custom DisplayAsPDF Page
Youcanalsospecifyatooltipifyoulike.Then,youdsavethe bindingsandgeneratetheapplication.
140
Adding the ProductsList.rpt file to the generated application using Visual Studio.
Now,youllneedtoextendthe codetousethereporting engineandreport.Openthe projectinVisualStudioby clickingontheapplications generated.VBPROJfile.Click theShowAllFilesiconat thetopoftheSolution Explorerpanesothatthe applicationscodebehind filesareaddedtotheSolution Explorer. FindtheProductsList.rpt file.Thisdefinesthereport thatCrystalReportswill produce. Next,addthe ProductsList.rptfiletothe projectbyrightclickingonthe ProductsfolderintheSolution Explorerpane,selectingAdd ExistingItem,and navigatingtothe ProductList.rpt. Nowlocateandopenthepagessafeclass,e.g.:
ViewProductsRecords.safe.aspx.vb
141
TheDisplayReportAsPDFfunctionconnectstothedatabase, populatesthereport,andthendisplaysitinthewebbrowser.
' This method handles the IronSpeedEvent produced by the ExportToPDF button Public Overrides Sub OnIronSpeedEvent(ByVal args As IronSpeed.Base.IronSpeedEventArgs) ' Handle the custom "DisplayAsPDF" command, but pass others off to the base class If args.EventType = IronSpeed.Base.IronSpeedEventArgs.EventTypes.Custom AndAlso _ args.CustomEventName = "DisplayAsPDF" Then '' create the report object and produce the report Dim crReportDocument As New ProductsList() DisplayReportAsPDF(crReportDocument) Else ' not the custom "DisplayAsPDF" command, pass it on MyBase.OnIronSpeedEvent(args) End If End Sub ' ' This function creates an instance of the Crystal Report, in PDF format, and displays it ' Sub DisplayReportAsPDF(ByVal reportObject As CrystalDecisions.CrystalReports.Engine.ReportClass) ' Declare the necessary Crystal Reports objects Dim dbTable As CrystalDecisions.CrystalReports.Engine.Table Dim dbLogin As CrystalDecisions.Shared.TableLogOnInfo Dim crExportOptions As ExportOptions Dim crDiskFileDestinationOptions As DiskFileDestinationOptions ' Create a temporary file to hold the report ' -- use the session ID in the filename to avoid process conflicts ' -- use a built-in Iron Speed utility function (and the "MapPath" method) to get the current ' -- application's root path Dim fname As String = Server.MapPath(IronSpeed.Base.Configuration.ApplicationSettings.Current.AppRootPath) _ & "\" & Session.SessionID.ToString & ".pdf" ' define the Crystal Report ouput options crDiskFileDestinationOptions = New DiskFileDestinationOptions() crDiskFileDestinationOptions.DiskFileName = fname crExportOptions = reportObject.ExportOptions With crExportOptions .DestinationOptions = crDiskFileDestinationOptions .ExportDestinationType = ExportDestinationType.DiskFile .ExportFormatType = ExportFormatType.PortableDocFormat End With ' Retrieve DB Connection Info Dim ProductsTable As New CrystalReportsDemo.ProductsAccess()
142
Dim DBConnectionName As String = ProductsTable.ConnectionName Dim DBConnString As String = _ IronSpeed.Base.Configuration.ApplicationSettings.Current.GetConnectionString(DBConnectionName , False) Dim DBConnection As IronSpeed.Base.Configuration.DatabaseConnection DBConnection = IronSpeed.Base.Configuration.DatabaseConnection.Parse(DBConnectionName, DBConnString) ' get the connection's user id and password values Dim uid As String = DBConnection.UserName Dim pw As String = DBConnection.Password ' set the login for all the tables in the report For Each dbTable In reportObject.Database.Tables dbLogin = dbTable.LogOnInfo dbLogin.ConnectionInfo.Password = pw dbLogin.ConnectionInfo.UserID = uid dbTable.ApplyLogOnInfo(dbLogin) Next ' export the document to the temporary file reportObject.Export() ' Create the HTTP Response as PDF and output the file Response.ClearContent() Response.ClearHeaders() Response.ContentType = "application/pdf" Response.WriteFile(fname) Response.Flush() ' Clean up the Response object and delete the temporary file Response.Close() System.IO.File.Delete(fname) End Sub
Localizing(Internationalizing)YourApplication
Aspartoftodaysglobaleconomy,businessapplicationsarebeing askedtospanmultiplegeographies,andsupportusersintheir nativelanguages.Applicationgeneratorsprovidesupportfor
143
Local date formats, currency symbols and character sets are supported by Iron Speed Designer in generated applications. Avarietyoffactors,settings,andparameterscontributetoa localizedapplication: Cultureencoding.Yourgeneratedapplicationshouldhavea culturecodingtoindicatestotheunderlyingplatform(suchasthe .NETframework)howtohandlebasicproperties,likedateandtime formatting,language,etc. Pageencoding.Theapplicationgeneratorshouldcreatethe applicationwithaninternationallyrecognizedpageencoding.For example,IronSpeedDesignersupportsUTF8Unicodeencoding throughouttheapplicationsitgenerates. Dateandtimeformatting.Avarietyofdateandtimeformatsare usedworldwide.Thetoolyouuseshouldmakeiteasytoconfigure yourapplicationtoacceptavarietyofdateandtimeformats. Numberandcurrencyformatting.Somenumberformatsusea decimalpointtoseparatedollarsandcents;otherformatsuse commas.Again,itshouldbeeasytosupportthesedifferentformats. Errortextstringtranslation.Errorandinformationtextmessages shouldbemanagedbythetoolinawaythatmakesthemeasyto translatetotheappropriatelanguagefortheapplication.
144
Summary
Inthelast10years,experimentswithdataandbusinessmodeling softwarepackagesthatgeneratecodehaveresultedinafairly thoroughunderstandingofthecharacteristicsthatanapplication generatormusthavetobeaviablesolution.Newtools,suchasIron SpeedDesigner,makewebbasedapplicationgenerationworth investigatingasapotentialsolutionforanITdepartmentthatneeds todecreasedevelopmentcostsaswellasspeedupits implementationschedule.Developersnolongerneedtoworry aboutwhetherthegeneratedapplicationcanbecustomizedand extendedinatimelyfashion.And,adeveloperneednotbe Microsoft.NETsavvytotakeadvantageofthispowerfulframework.
145
Part9) AutomatingITStrategies
HowITDepartmentsAutomate ImplementationofStandards&Best Practices
146
Nowthatwevedemonstratedhowgeneratedapplicationcanbe modifiedorextended,thischapterwillfocusonhowthese extensionscanbeautomaticallyreusedacrosstheenterprise.As youllremember,inanearliersectionwediscussedhowasoftware developmentmethodologythatembracedapplicationgeneration technologycouldenablecorporatecomputingstandardsin meaningfulandpragmaticways. ThefollowingpagesdescriberealworldexamplesofhowIron SpeedDesignerdeliversonthesepromisesthroughautomatedpage production,codereuse,customcontrols,andcustompage templates.
AutomatingPageProduction
Usinganapplicationgenerator,youcanautomaticallycreate hundredsofwebpagesbasedonyourowndesign,oryoucancreate standardpagesusingpagetemplatesprovidedwiththetool. Automatedproductionofwebpagesimposesorganizationand structureuponthehundredsofpagesthatmaybenecessaryforyour application.Notonlydoesthisstructureallowtheapplication generatortodomostofthework,butithelpsthedevelopmentteam organizeandkeeptrackofwhatpagesareneeded,andthe functionalityrequired. Asanexample,IronSpeedDesignerutilizesthreedifferenttypesof pages. PageTemplatesThesemasterHTMLpagesareusedto automaticallycreatelayoutpages.Thisautomaticlayout pagecreationprocessisenabledbyaspecialsetofcode generationtagsthatareusedtoautomaticallycreatelayout pages.Also,PageTemplatescanincludestandardcode generationtagsthatarereplacedwhentheapplicationis generated. LayoutPagesTheseHTMLpagesareusedbythe applicationgeneratorwhencreatingtheapplication.They includecodegenerationtagsthatarereplacedwith referencesto.NETcontrolswhentheapplicationcodeis written. ASPXPagesCreatedbyIronSpeedDesignertheseActive ServerPagesareusedbytheservertodynamicallycreate anddisplaypagesrequestedbyanendusersbrowser.
147
Layout Pages Can be created by the developer or Iron Speed Designer. Contain HTML & code generation tags
ASPX Pages Created by Iron Speed Designer Contain HTML & references to data-bound .NET controls in place of code generation tags
Contain HTML & code generation tags & special code generation tags used by application generator to automatically create layout pages Typically used to create hundreds of C/R/U/D pages for records and tables.
Anapplicationgeneratorshouldincludevarioussamplepage templatestogiveyouachoiceofapplicationlookandfeelwithout forcingyoutocreateone.Thesepagetemplatesallowyoutocreate standardpagestocreate,review,update,anddelete(C/R/U/D) records.Toolsshouldalsoincludesimilarpagetemplatesfor viewingandeditingentiretables. EachofthepagetemplatesprovidedwithIronSpeedDesigner followsadesigntheme.AdesignthemeisacollectionofPage TemplatesandLayoutPageswhereaconsistentlookandfeelis reflectedinthelayoutofthepages,thecolors,andthecommon elementsacrosspagessuchasmenubars,andsearch,pagination andfiltercontrols. Followingarethreeexamplesofthesamepagecreatedfrompage templatesusingdifferentdesignthemes.
148
A table view page rendered with Iron Speed Designers Alps design theme.
A table view page rendered with Iron Speed Designers Everest design theme.
149
A table view page rendered with Iron Speed Designers Annapurna design theme. Pagetemplatesandlayoutpageswithinadesignthemeutilize panelsforrepetitivepageelementsthatdontchangefrompageto page.Thisapproachachievesaconsistentlookandfeelacross multiplepageswithaminimumamountofwork.Forexample,you onlyneedspecifythebuttonlookandfeelonceanduseitasapanel inalllayoutpagesratherthandescribingthelayoutforeachbutton withineachandeverypage. IronSpeedDesignerincludespredefinedpanelsforeachofthepage templatesitprovides.Inadditiontobuttons,headersandfooters, thepredefinedpanelsinclude: Panel Menu Description A menu panel containing one or more menu items. To add a new menu items, edit the Menu.html. The panel for an individual menu item. This panel is used for the normal display of the menu item. This panel specifies the highlighted state of an individual menu item. The pagination panel containing a number of controls including previous page, first page, next page, last page, a text box to enter the number of records to display and an indicator showing the page you are on currently. The range filter displays two field filters so the application user can
Menu_Item
Menu_Item_Highlighted Pagination
Range_Filter
150
Panel
Search
WhatsinaPageTemplate?
PagetemplatefilesarejustHTMLfilesthathavebeenenhanced withcodegenerationtags.Theyspecifythegraphicsand organizationthelookandfeelthatwillbeusedonlayoutpages andASPXpagesthatarederivedfromthismasterpagetemplate. Eachpagetemplateusesasetofcommoncomponentfilesthatare usedbyotherpagetemplatefilesbelongingtothesamedesign theme.Forexample,thebuttonontheAdd,Edit,andViewpagesof theEverestdesignthemefilesisspecifiedinaseparatecomponent layoutfilecalledButtonEverest.html.(Inafewpages,welldiscuss howthesecommoncomponents,orpanels,areusedtofacilitatecode reuse.) Inadditiontotheregularsetofcodegenerationtags,pagetemplates canalsouseafewspecialcodegenerationtags.Thesespecialcode generationtagshelptheapplicationgeneratortocreatelayoutpages basedonthepagetemplate. AnExamplePageTemplate:AutomatedRecordPages Remember,codegenerationtagsareusedtospecifyplacesonpages wheredatacontrolsappear.Codegenerationtagsspecifythe relevantdata,andatbindingtime,youspecifyhowtheyllbeused. Keepingthisinmind,theAdd,EditandShowRecordgenerated layoutpagesarebasedonexactlythesametemplate.Thebindingof thecodegenerationtagsdetermineswhetherthepagefunctionsas anAdd,EditorShowRecordpage. Theapplicationgeneratordeterminesthetypeofthetemplateusing theGEN:Templatecodegenerationtag. AsimpleexamplepagetemplateforAddRecordisshownbelow. Eachofthecodegenerationtagsishighlighted,anddiscussedin detailfollowingthepagetemplate.
<!-- Start AddRecord.html --> <!-- Template Tag to Specify the kind of page this is to the binder --> <GEN:TEMPLATE TYPE="Add One Record" FILE="Record Panels/Add Record - Label on Side.html" /> <!-- Start Logo Table -->
151
<table cellspacing="0" cellpadding="0" border="0" width="100%"> <tr> <td><GEN:Image Name="Logo" /></td> </tr> </table> <!-- End Logo Table --> <!-- Start Menu --> <GEN:Menu Name="Menu" FILE="../Menu Panels/Menu.html" /> <!-- End Menu --> <!--Start Record Table --> <table cellpadding="0" cellspacing="0" border="0" width="100%"> <tr> <td> <GEN:Record Name="Record"> <!-- Start Dialog Table --> <table cellpadding="0" cellspacing="0" border="0" width="100%"> <tr> <td><GEN:Image Name="DialogIcon" /><GEN:Html Name="DialogTitle" /></td> </tr> <tr> <td> <table cellpadding="0" cellspacing="3" border="0"> <tr> <td> <%= Me.SystemUtils.GenerateEnterKeyCaptureBeginTag(Me.FindControl("V_CancelButton")) %> <%= Me.SystemUtils.GenerateEnterKeyCaptureBeginTag(Me.FindControl("V_OKButton")) %> <!-- Start Actual Table Section --> <table align="center" cellpadding="0" cellspacing="3" border="0"> <GEN:ForEach Name="Record"> <tr> <td><GEN:FieldLabel Name="FieldValueLabel" /></td> <td><GEN:FieldValue Name="FieldValue" /></td> </tr> </GEN:ForEach> </table> <!-- End Actual Table Table --> <%= Me.SystemUtils.GenerateEnterKeyCaptureEndTag(Me.FindControl("V_OKButton")) %> <%= Me.SystemUtils.GenerateEnterKeyCaptureEndTag(Me.FindControl("V_CancelButton")) %> </td> </tr> <GEN:ForEach Name="OneToManyTable"> <tr> <td>
152
<!-- Start of "1" One-To-Many Table View --> <!-- Start Button Bar Table for One-To-Many --> <table cellspacing="0" cellpadding="0" border="0" width="100%"> <tr> <GEN:ForEach Name="ButtonBar"> <td> <GEN:Button Name="ButtonBar" file="../Shared/Button.html" /></td> </GEN:ForEach> </tr> </table> <!-- End Button Bar Table for One-To-Many --> <!-- Start Actual One-To-Many Table --> <table cellspacing="0" cellpadding="0" border="0" width="100%"> <GEN:Table Name="Table"> <!-- Start One-To-Many Table Header Row --> <tr> <GEN:ForEach Name="HeaderRow"> <td><GEN:FieldLabel Name="FieldLabel" /></td> </GEN:ForEach> </tr> <!-- End One-To-Many Table Header Row --> <GEN:ItemTemplate Name="RecordRow"> <!-- Start One-To-Many Record Row --> <tr> <GEN:ForEach name="RecordRow"> <td <GEN:Align Name="AlignTableFieldValue" />><GEN:FieldValue name="TableFieldValue" /></td> </GEN:ForEach> </tr> <!-- End One-To-Many Record Row --> </GEN:ItemTemplate> </GEN:Table> <%= Me.SystemUtils.GenerateEnterKeyCaptureEndTag(Me.FindControl("V_ForEachButtonBar1Button")) %> </table> <!-- End Actual One-To-Many Table --> <!-- End of "1" One-To-Many Table View --> </td> </tr> </GEN:ForEach> <tr> <td> <!-- Start Dialog Buttons (Ok and Cancel) --> <table align="center" cellpadding="0" cellspacing="0" border="0"> <tr> <td> <GEN:Button Name="OKButton" file="../Shared/Button.html" /></td> <td><img src="../Images/Vanilla/space.gif" height="6" width="3" alt=""></td> <td> <GEN:Button Name="CancelButton" file="../Shared/Button.html" /></td>
153
</tr> </table> <!-- End Dialog Buttons (Ok and Cancel) --> </td> </tr> </table> </td> </tr> </table> </GEN:Record> </td> </tr> </table> <!-- End Record Table --> <!-- Start Footer Table --> <table cellspacing="0" cellpadding="0" border="0"> <tr> <td> <GEN:Footer Name="Footer" file="../Header & Footer/Footer.html" /> </td> </tr> </table> <!-- End Footer Table --> <!-- End AddRecord-Vanilla.html -->
154
<GEN:Record Name="Record">
Inthisexample,themostimportantsetoftagsinthepagetemplate aretheForEach,FieldLabelandFieldValuetags.Theapplication generatorasksyoutoselectallthefieldstoincludeonthelayoutfile. ThebeginningandendingForEachtagsarecompletelyremoved fromthelayoutfilecreatedandalltheHTMLandcodegeneration tagswithintheForEachtagsareexpandedandrepeatedasmany timesasthenumberoffieldsspecified.Inthisway,theapplication generatoriterativelywritescodeforeachrecordspecified,anddoes thisuntilcompletionsavingyouhoursandhoursofrepetitive, mindnumbing,work.
<GEN:ForEach Name="Record"> <GEN:FieldLabel Name="FieldValueLabel" /> <GEN:FieldValue Name="FieldValue" /> </GEN:ForEach>
EachrepeatedFieldLabeltagisgivenitsownnamebyaddingthe nameofthefieldasaprefix.Forexample,ifthefieldnameis FirstName,theFieldValuetagiscalledFirstNameFieldValueLabel. AsimilarrepetitionisperformedontheFieldValuetagandthe nameofthetagisderivedfromaddingthefieldnameasaprefixto thenameoftheFieldValuetag.Hereagain,theapplication generatorutilizesthelabelsyouprovide,butwritesallthecodefor you. Afterthesetoffieldlabelandfieldvaluepairs,thepagetemplate allowsyoutospecifyonetomanyormasterdetailtablestobe added,editedorviewedforthepagetemplates.
<GEN:ForEach Name="OneToManyTable"> <GEN:ForEach Name="ButtonBar"> <GEN:Button Name="ButtonBar" file="../Shared/Button.html" /></td> </GEN:ForEach> <GEN:Table Name="Table"> <GEN:ForEach Name="HeaderRow"> <GEN:FieldLabel Name="FieldLabel" /> </GEN:ForEach> <GEN:ItemTemplate Name="RecordRow">
155
<GEN:ForEach name="RecordRow"> <td <GEN:Align Name="AlignTableFieldValue" />> <GEN:FieldValue name="TableFieldValue" /> </GEN:ForEach> </GEN:ItemTemplate> </GEN:Table> </GEN:ForEach>
Sincetherecanbezeroormoreonetomanytables,aForEachcode generationtagisusedtoenclosethecontentsofeachofthedetail tables.Withineachdetailtable,therecanbezeroormorebuttons specified.TheButtonBarForEachcodegenerationtagindicatesthe setofbuttonstodisplay. Thenextsectioncontainsthecodegenerationtagsforthetableitself. First,thetableheaderisdefinedfollowedbyanItemTemplateto describeeachrowofthetable.IncludedintherowisanAligncode generationtagthatallowstheapplicationgeneratortocreatean alignmentattributeforeachTDHTMLtag.Asmentionedbefore, thenamingofthecodegenerationtagisimportantinpage templates.Thesenamesareusedbytheapplicationgeneratorto maptothefieldsfromthedatabaseorbuttons.
<GEN:Button Name="OKButton" file="../Shared/Button.html" /> <GEN:Button Name="CancelButton" file="../Shared/Button.html" />
AutomaticReuseofASP.NETDirectivesinPageTemplateFiles
Mostcommonlyfoundatthebeginningofthepage,ASP.NET Directivescontrolthesettingsandpropertiesofthepage. Sometimes,developersuseASP.NETdirectivestoincludecustom controlsinaheaderorfooterofapage(orboth).Modern applicationgeneratorscaneasilyincorporatethesedirectivesintothe applicationstheycreate.
156
Forexample,inIronSpeedDesigner,youcanplaceASP.NET directivesinpagetemplatesbyinserting@Registerdirectivesatthe verybeginningofthepagetemplatefile.The@Registerdirectives canoccuranywhereinpagetemplatefilesaslongastheyareplaced beforethefirstuseofatagprefix,i.e.,theymustprecedethe <HTML>taginthepagetemplatefile.Thisallowsyoutofreelymix ASP.NETcontrolsinthemefilesbyfollowingthissimplerule. Letsfurtherconsidertheexampleofincorporatinganexistingweb pageheaderandfooterwhichweredevelopedusingVisualStudio .NETaswebusercontrolsintoageneratedapplication.Toinclude theseheaderandfooterwebusercontrols,andpotentiallyotherweb usercontrols,youcancustomizeacopyoftheappropriatepage templatetoincludethesecontrols. Bywayofexample,herethefollowingdirectivesareinsertedintoa pagetemplatefilebeforethe<HTML>tag:
<%@ Register TagPrefix="MyControl" TagName="Header" Src="/20001/Common/Controls/Borders/Header.ascx" %> <%@ Register TagPrefix="MyControl TagName="Footer" Src="/20001/Common/Controls/Borders/Footer.ascx" %>
Wheretheheaderis:
<MyControl:Header id="Header" runat="server"> </MyControl:Header>
andthefooteris:
<MyControl:Footer id="Footer" runat="server"> </MyControl:Footer>
157
APragmatic,YetRevolutionary,ApproachtoCodeReUse
Nowthatyouvebeenintroducedtothenotionofdefiningpage templatestocreatemultiplelayoutpages,youhavean understandingofhowapplicationgeneratorscanbeusedto automate,eveneliminate,theamountoflaborinvolvedincreating typicalpages.Further,weveexplainedhowthosepagescan leverageexistingASP.NETdirectiveswithinpagetemplatestoavoid thelabortypicallyinvolvedwithreusingthatkindofcode. Contemporaryapplicationgenerators,however,takethisideaeven further.Justabouteverysnippetofanypagecanbecreatedasa reusablepanelorcomponent. Forpurposesofthisdiscussion,regardacomponentassimpleand singlepurposeinnature(e.g.,abutton,oralink,oratextbox).A panelisacollectionofcomponentswithasinglepurpose.For example,asearchpanelmighthaveatextboxandagobutton. Oneofthemostpowerfulfeaturesofapplicationgeneratorsistheir abilitytocreateandusereusablepanelsandcomponents.Asinthe ASP.NETdirectiveexampleearlier,aheader,footerandmenupanel canbeincludedoneverypageofageneratedapplication.Reusable panelsallowthedefinitionofthepanelinoneplaceandpages simplyrefertothesepanels.Changesonlyneedbemadeoncetothe panelandwillbereflectedonallpagesthatusethepanel.This allowsyoutoconsolidatethemostcommonaspectsofyour applicationintoonelocationandreusethemasoftenasnecessary. Reusablepanelsaresimplyfragmentsofapageandaregeneratedas ASCXcontrolsinsteadofASPXpages.Justlikearegularpage,they startwithanHTMLlayoutpagefileandareboundwiththe applicationgenerator.Oncecreated,theyarereferredtobyother HTMLlayoutpagesorpanelsbyusingaGEN:Usecodegeneration tag. Reusablepanelsorcomponentscanbeeithercompletely independentortheycanbedependentonthepageorpanelthat includesthem.Forexample,theheaderpaneltypicallyisa completelyindependentpanelcontainingalogo,andotherimages. Tocontrastthis,areusablebuttoncomponentspecifiesits appearance,butthepageorpanelthatincorporatesthebutton specifiestheactualbuttonlabel,theactiontotake,andtheURLtogo towhenthebuttonisclicked.Inthiscase,theimmediateparent providesanyadditionalinformationneededbythedependent component.Forexample,thebuttonlabelwithinafooterpanelcan onlybespecifiedatthefooterpanellevel,butnotatthepagelevel.
158
AutomatingCodeReUsewithPanels&Components
Experiencehasshownthatjusthavingtheabilitytoreusecode thatsorganizedandconfiguredforreusedoesntalwaysensureit happens.Insomesituations,merelytheprocessofincorporating reusablesoftwarepartshasimposedmoredifficultythanjust rewritingthecode.Modernapplicationgenerators,however,pave thewayforcodereusebydramaticallysimplifyingtheprocessas shownbelow. Building&ReusinganIndependentReusablePanel Themostcommonplaceyoullmostlikelywanttoemployan independentreusablepanelisintheheaderofyourapplication. ThefollowingpagesdescribehowyoucanuseIronSpeedDesigner tocreateasimplereusablepanelthatputsacompanylogointhe headerofeverypage. First,createalayoutfileforthereusablepanelcalled HeaderPanel.htmlasshownhere.NotetheGEN:Imagetag.
<table width=100% cellpadding="0" cellspacing="0" style="border-bottom-width: 1; border-bottom-color: #DDDDDD; border-bottomstyle: solid"> <tr > <td><GEN:IMAGE Name="Logo"/></td> </tr> </table>
Nowbindthisfileusingtheapplicationgenerator.SelecttheLogo tagandentertheURLofthelogoandsave.
159
Screen shot of how Iron Speed Designer specifies the path to an image. Thepanelisnowreadytobeincludedinapage.Toincludethis panelonapage: Createasimplelayoutfilethatincludesthereusablepanel.The reusablepanelisspecifiedbyusingtheGEN:Usecodegeneration tag.TheFileattributeofthistagspecifiesthepaneltouse.
<GEN:Header Name="Header" File="../Header & Footer/Header.html"/> this is the rest of the page
160
Screen shot of generated application featuring a reusable header. Thissimpleexampledemonstratesaverypowerfulconcept.Oncea reusablepanelhasbeencreated,ittakesalmostnocodingtoreusethe codeinanotherapplication.Thissimpleconceptcanbeappliedto manydifferentaspectsofapplicationdevelopment.
ButtonPanels
Whilecreatingcustombuttonsthatexecutespecialfeaturescanbe interesting,andevenheroic,merelyenhancingapplicationswith standardbuttonsthatdostandardthingsisoftenatediousandtime consumingtask.Applicationgeneratorscangreatlysimplify,and largelyautomate,thismundanetask. Forexample,IronSpeedDesignersupportsfourtypesofbuttons. ThePushButton,LinkButtonandImageButtonscreatestandard HTMLbuttonsbasedontheButton,ahrefandIMGHTMLtags.A fourthtypeofbuttonsupportedbyIronSpeedDesignerisabutton thatiscreatedusinganHTMLlayoutpage. Usinganapplicationgenerator,youcancreatemanydifferenttypes ofbuttonsusingthesecustombuttonsinyourpagetemplatesand layoutpages.Forexample,youcancreateaRedbuttonandaGreen buttonandusethemmultipletimesonasinglepage. Ofcourse,thebuttonpanelfilecouldcontainthecompletebinding forthebuttonincludingthelabeltext,theURLandthecommandto execute.But,bybindingthebuttoncompletely,thebuttonactually becomesaspecificbuttonandnotreusabletocreatemultiplebuttons withdifferentlabels,URLsandcommands. Toallowreusability,applicationgeneratorscanbindbuttonsmore dynamically,andcanbindsomeaspectsofthebuttonatthepageor panelthatincorporatesthebutton. Thefollowingfewpagesdescribetheapproachtakentoaccomplish thiswithIronSpeedDesigner. Tocreatetworeusablebuttons,youneedtocreatetwolayoutfiles. Oneforaredbuttonandoneforagreenbuttonareshownbelow andonthefollowingpage.
161
<!-- green button --> <style type="text/css"> a { color: #FFFFFF; font-family: Verdana; font-size: 10px; font-weight: bold; text-decoration: none; text-align: center; padding-left: 3px; padding-right: 3px; } </style> <table cellpadding="3" cellspacing="0" border="1" bordercolorlight="#C0C0C0" bordercolordark="#808080" style="border-collapse: collapse" bgcolor="#008000"> <tr> <td><GEN:LinkButton Name="Button"/></td> </tr> </table>
<!-- red button --> <style type="text/css"> a { color: #FFFFFF; font-family: Verdana; font-size: 10px; font-weight: bold; text-decoration: none; text-align: center; padding-left: 3px; padding-right: 3px; } </style> <table cellpadding="3" cellspacing="0" border="1" bordercolorlight="#C0C0C0" bordercolordark="#808080" style="border-collapse: collapse" bgcolor="#FF3300"> <tr> <td><GEN:LinkButton Name="Button"/></td> </tr> </table>
Oncecreated,theselayoutpagescanbeboundwiththeapplication generatorasshownhere.
162
Using Iron Speed Designer to bind a reusable button. Nowyourereadytousethesebuttonsonanewpage.Tomakethat page,createanewlayoutpage,onethatusesthesebuttonsmultiple times,asshownbelow.
<div align="center"> <table cellpadding="8" cellspacing="0" border="0"> <tr> <td><GEN:BUTTON Name="OKButton" FILE="../Shared/Button.html"/></td> <td><GEN:BUTTON Name="SaveButton" FILE="../Shared/Button Button.html"/></td> <td><GEN:BUTTON Name="CancelButton" FILE="../Shared/Button.html"/></td> </tr>
163
</table> </div>
Simple page featuring reusable button panels bound differently for varying purposes.
GeneratingNavigationMenuPanels
Anotherextraordinarilyusefulaspectofthiscodereuseideaisits abilitytodefineamenuforyourentireapplicationanduseiton everypage.Suchmenuscanevenincorporatedifferentmenu choicesbaseduponthecontextofthepage,andyet,theyreonly definedonce. Suchafeaturecansaveadevelopmentorganizationhoursandhours ofbuildingandtestingappropriatemenuoptionsforvariouspages withinanapplication. Thenextseveralpageswalkthroughasimpleexampleofhow reusablemenusarecreatedwithanapplicationgenerator. Inthisexample,themenuisdependentonthepagetodeterminethe currentlyhighlightedmenuitem.Tocreateamenu,wellfirstcreate twolayoutfilesonetodisplaythenormalunselectedstateandthe othertodisplaythehighlightedstate.Next,wellcreateamenu panelthatincludesallofthemenuitemsyouwouldliketodisplay intheapplication,andfinally,wellincludethemenupanelona page. Themenuscanbecreatedusinglinksorimages.Dependingonyour preference,youcanuseeitherofthetwocodegenerationtags. So,thefirststepistocreatethelayoutpageforthenormal unselectedmenuitemasshownhere.
<table width=140 height=14 bordercolorlight="#FFFFFF" bordercolordark="#C0C0C0" border="1" bordercolor="#111111" cellpadding="0" cellspacing="0" style="border-collapse: collapse"> <tr> <td class="NormalMenu" bgcolor="#000080" > <GEN:LinkButton Name="Button"/> </td> </tr> </table>
164
Oncecreated,youneedtobindthelayoutpageusingthe applicationgenerator.
Iron Speed Designer binding a reusable navigation menu panel. Then,youllneedtocreatealayoutpagefortheselectedmenuitem asshownhere,andbindthisaswell.
<table width=140 height=14 bordercolorlight="#FFFFFF" bordercolordark="#C0C0C0" border="1" bordercolor="#111111" cellpadding="0" cellspacing="0" style="border-collapse: collapse"> <tr> <td class="SelectedMenu" bgcolor="#000080" > <GEN:LinkButton Name="Button"/> </td> </tr> </table>
165
font-size: 10px; font-weight: bold; text-decoration: none; text-align: center; padding-left: 3px; padding-right: 3px; } </style> <style type="text/css"> .NormalMenu a { color: #FFFFFF; font-family: Verdana; font-size: 10px; font-weight: bold; text-decoration: none; text-align: center; padding-left: 3px; padding-right: 3px; } </style> <table cellpadding="0" cellspacing="0"> <tr> <td> <GEN:BUTTON Name="Customers" File="Menu_Item.html"/> <GEN:BUTTON Name="CustomersHilited" File="Menu_Item_Highlighted.html"/> </td> </tr> <tr> <td> <GEN:BUTTON Name="Employees" File=" Menu_Item.html"/> <GEN:BUTTON Name="EmployeesHilited" File="Menu_Item_Highlighted.html"/> </td> </tr> <td> <GEN:BUTTON Name="Suppliers" File=" Menu_Item.html"/> <GEN:BUTTON Name="SuppliersHilited" File="Menu_Item_Highlighted.html"/> </td> </tr> <tr> <td> <GEN:BUTTON Name="Products" File=" Menu_Item.html"/> <GEN:BUTTON Name="ProductsHilited" File="Menu_Item_Highlighted.html"/> </td> </tr> </table>
166
Iron Speed Designer binding a reusable menu panel. Theapplicationgeneratorwillpromptyoutobindeachofthemenu item(button)tagsandprovidethemenutext(buttontext),the command,andtheURLforboththenormalandthehighlighted menuitems. Nowthatthemenupanelhasbeencreated,itcanbeincorporated intoapageusingtheGEN:Usecodegenerationtag.Inthefollowing example,thelayoutpagefileincludesaheaderpanel,themenu panel,andtheproductsfromthedatabase.
<GEN:Use Name="Header" File="HeaderPanel.html"/> <br> <table> <tr> <td valign="top"> <GEN:Menu Name="Menu" File="../Menu Panels/Menu.html" Type="Menu" /> </td> <td valign="top"> <GEN:Table Name="Products"> <table cellpadding="5" style="border-collapse: collapse" border="1"
167
bordercolorlight="#C0C0C0" bordercolordark="#C0C0C0"> <GEN:ItemTemplate> <tr style="font-family:Verdana; font-size:10px"> <td> <GEN:FieldValue Name="ProductId" /> </td> <td> <GEN:FieldValue Name="ProductName" /> </td> <td> <GEN:FieldValue Name="UnitPrice" /> </td> <td> <GEN:FieldValue Name="UnitsInStock" /> </td> <td> <GEN:FieldValue Name="Discontinued" /> </td> </tr> </GEN:ItemTemplate> </table> </GEN:Table> </td> </tr> </table>
Oncecreated,yourethenreadytobindthelayoutpagewiththe applicationgenerator.
168
Iron Speed Designer binding the layout page featuring a reusable menu. Now,yourereadytogeneratetheapplication,andpreviewthe page.
GeneratingDynamicContextSensitivePanels
Thisconceptofdefiningpartsoftheapplication,andthenreusing thosepartsoverandoveragain,representsanimportantadvantage ofusinganapplicationgenerator.Asyougainexperienceworking withanapplicationgenerator,youllcontinuallydiscoverhowyou canusethegeneratortoincreasinglyautomatetheproductionofan enterpriseapplication. Nowthatyouveseenthispowerfulapproachappliedtothecreation ofbuttonsandmenus,welllookatanexampleofhowapplication generationcanapplythesameideatoanyaspectoftheapplication throughreusablepanels. Beyondautomatingtheproductionofpagesthatneedthesame functionality,reusablepanelscanalsobedependentontheparent forinformationaboutthecurrentcontentbeingdisplayed.For example,ifyouwouldliketodisplayanEmployeerecordinthe
169
samewayonmultiplepages,thenthebestwayistocreateapanel thatwoulddisplayonerecord.Thispanelcanthenbeusedmultiple timesonapageorevenwithinatable.Notethattheinformation aboutwhichemployeerecordtodisplaywillnotbeavailabletothe panelatdesigntime;butratherprovidedtothepanelatruntimeby thepagethatincludesthepanel. Todemonstratethisidea,thefollowingexampleshowshowto createanemployeerecordpanel,andthenhowtousethatpanelon twodifferentpages.Thefirstpageusesthepaneltwicetoshow informationabouttwoemployeessidebyside.Thesecondpage displaystheemployeepanelwithinatableofemployeerecords. Togetstarted,letscreatetheemployeepanellayoutpagecalled EmployeePanel.html.Oncecreated,andboundtothedatabythe applicationgenerator,itbecomeseasilyreusableonanypage.
<table width=400 cellpadding="5" style="border-collapse: collapse" border="1" bordercolorlight="#C0C0C0" bordercolordark="#C0C0C0"> <tr style="font-family:Verdana; font-size:10px"> <td align="left" valign="top"> <GEN:FieldValue Name="Photo" /> </td> <td align="left" valign="top"> <GEN:FieldValue Name="FirstName" /> <GEN:FieldValue Name="LastName" /><br> <GEN:FieldValue Name="Address" /><br> <GEN:FieldValue Name="City" />, <GEN:FieldValue Name="Region" /> <GEN:FieldValue Name="PostalCode" /> <GEN:FieldValue Name="Country" /> </td> </tr> </table>
170
Iron Speed Designer binding a layout file, and specifying the record ID with a URL parameter value. Werenowreadytogeneratetheapplication,andpreviewthepage withthefollowingURL.
http://localhost/Tutorial/TUTORIAL%20PAGES/PageWithPanels.aspx?Emp1=1&Emp2=2
Page created with Iron Speed Designer, featuring two uses of the same panel for record comparison.
171
Notehoweasyitwastoreusethepanelwithininthesamepage bymerelybindingitdifferentlywithintheapplicationgenerator. Nowthatitsbeencreated,thisEmployeePanel.htmlcanbeusedin otherlayoutpages.Letsusethesamepaneltodisplayatableof employees.Toaccomplishthis,wellcreateapagecalled PageWithPanelsInTable.html.ThispageusestheGEN:Tabletagand theGEN:ItemTemplatecodegenerationtags.TheItemTemplate containsareferencetotheEmployeePanel.htmltagusingthe GEN:Usetag.Notethatthelayoutspecifiesasinglereferencetothe employeepanel.
<GEN:Table Name="Employees"> <table> <GEN:ItemTemplate> <tr> <td> <GEN:Use Name="EmployeePanel" File="EmployeePanel.html"/> </td> </tr> </GEN:ItemTemplate> </table> </GEN:Table>
172
Werenowreadytogeneratetheapplication,andpreviewthepage withthefollowing:
URL.http://localhost/Tutorial/TUTORIAL%20PAGES/PageWithPanelInTable.aspx
Screen shot of page created with Iron Speed Designer that incorporates the employee panel into a table.
173
AutomatingReUseofCustom&ThirdPartyControls
Inmanywebapplicationdevelopmentscenarios,itscommonto incorporatecustomcodeintotheapplication.Thesecustom componentscanbebuiltinternally,licensedfromthirdparties,or acquiredfromopensourceprojects.Regardlessoftheirsource,such componentscanprovidefunctionalityquicklyandeasilywithout imposingadditionaldevelopmentburdens(otherthanintegrating thecode). Someapplicationgeneratorsprovidearichsetofcontrolssuchas tabbedmenus,buttons,filters,andsearchboxes.Inmanycases,this richsetofcontrolscanbefurthersupplementedbythirdparty controlsandcontrolsthatyoumighthavedevelopedforother applications.Theabilitytoincludeothercontrolsandtightly integratethemwiththeapplicationgeneratoritselfisapowerful capabilitythatallowsyoutobuildvirtuallyanytypeofapplication withease. Whenarmedwithsuchafeature,youarenotlimitedtousing controlsthatareprovidedbytheapplicationgenerator,andcaneven utilizetheapplicationgeneratortobetterleverageyourlibraryof softwarecomponents. Addingthirdpartycontrols,grids,andotherfunctionalitytothe webpagesgeneratedbyanapplicationgeneratorshouldbevery easy.Bychangingthelayoutpagefilesorusingcustompanelfiles, youcanincludewhateverHTML,JavaScript,andserversidecode youwantinapageorcompositecomponent,includingapplettags, etc. Thirdpartycontrolscanbeincorporatedasindependentcontrols includedonthepageorascontrolsthatreceivetheirdatafromthe database.Toretrievethedatafromthedatabaseandpopulatea thirdpartycontrol,youshouldbeabletouseanyoftheapplication layerclassesprovidedbytheapplicationgenerator.
174
Example:IntegratingaThirdPartyControl
Includinganindependentthirdpartycontrolwithinapageyou createshouldbefairlysimple.Youshouldbeabletoembedany controlintheHTMLlayoutpageandhaveitpassedthroughtothe generatedpageunaltered.Suchafeaturewouldallowyouto incorporateanyASPXcontrolintoyourlayoutpageorpage template. Inthefollowingsimpleexample,IronSpeedDesigneronlypays attentiontotheGEN:codegenerationtagsandonlyreplacesthose tagswithreferencestotherelevantcontrols.Thiscontrolintegrates intothelayoutpage,butdoesnotuseanydatafromthedatabase, utilizeanycodegenerationtagsoruseanyofthegeneratedclasses. Thethirdpartymenucontrolusedinthisexampleisfrom CyberAKT.Thisthirdpartymenucontrolallowsyoutoincorporate manydifferenttypesofmenusintoyourapplicationwithease. SomesamplemenusandtabsavailablefromCyberAKTareshown below:
175
TheASPNetMenuthirdpartycontrolworksbyputtinganASP controlinyourlayoutpageandspecifyingthelistofmenuitemsina separateXMLfile.Thefollowingstepsdemonstratehowtointegrate thisindependentthirdpartycontrolintopagescreatedwithan applicationgenerator. Asafirststep,letscreateanHTMLlayoutfileforthereusablepanel calledPageWithThirdPartyMenu.html.Thislayoutpagecontainsan @RegisterdirectivetoregistertheASPNetMenufollowedbya referencetothecontrol.TheDLLfortheASPNetMenumustbe placedintheBindirectoryoftheapplication.
<%@ Register TagPrefix="cyberakt" Namespace="CYBERAKT.WebControls.Navigation" Assembly="ASPnetMenu" %> <link href="menuStyle.css" type="text/css" rel="stylesheet" > <!-- This third party control is available at http://www.aspnetmenu.com -- A sample DLL for this menu is placed in the bin folder of this Tutorial -- application. -- The sample DLL is only for demonstration purposes. You will need to -- license the third party library from the CyberAKT - the manufacturer of -- ASPNetMenu. -- The MenuData.xml file contains the menu names and the URL's. For more -- information about the menu control, please visit the ASPNetMenu.com site. -->
Example:IntegratingaThirdPartyControlwiththeDatabase
Amorecomplexandmorepowerfulexampleofathirdpartycontrol isatreecontrolsimilartotheoneusedwithinWindowsExplorer.In thecontextofadatabaseintensivewebapplication,suchatree controlisonlyusefulwhenintegratedwiththeunderlyingdata. Applicationgeneratorsshouldalwaysallowsuchcontrolsto integrateintotheapplicationstheycreate,andmakeiteasyto leveragethatintegrationinnewapplicationsoncethesetupis complete. Thefollowingexampleshowshowtointegrateathirdpartytree controlintoageneratedapplication.Thetreecontrolisinitialized withdatafromthedatabaseandthenavigationURLsaresetbased ontheIdsoftherecordsretrievedfromthedatabase. Theintegrationofthirdpartycontrolscanbeaccomplishedinmany differentways.Inthisexample,theintegrationisaccomplishedby
176
A screen shot of an example application created with Iron Speed Designer & a third party tree control. Tomakethissampleapplication,wellneedtocreatetheASPXfiles necessarytodisplaytheframebasedwindow.Thisfilespecifiesthe topframe,aleftsideframeandtherightframetodisplaythe selectionfromtheleftframe.ThisfileiscreateddirectlyasASPX pages. Ourmaintaskistocreatethepagetodisplaythetreeviewintheleft frame.ThispageiscreatedasaHTMLlayoutfilewithVisualBasic
177
codeasshownbelow.Welldiscussthemostimportantaspectsof thiscoderightafterpresentingit.
<link href="/Designer/Styles/Designer.css" type="text/css" rel="stylesheet"> <%@ Import Namespace="obout_ASPTreeView_Pro_NET" %> <script language="VB" runat="server"> Public Function CreateTree() As String Dim oTree As New obout_ASPTreeView_Pro_NET.Tree() oTree.ShowIcons = False oTree.TreeIcons_Path = "/Designer/Images" oTree.Add(Nothing, "root", "Products by Categories") Dim html Dim catRecords As ArrayList = CategoriesAccess.Instance.GetList( _ Nothing, _ Nothing, _ 0, 20, Nothing) Dim prodCatFk As IronSpeed.Base.Data.ForeignKey = _ ProductsAccess.Instance.TableDefinition.GetForeignKey( _ ProductsAccess.Instance.CategoryIDColumn) Dim catRecord As CategoriesRecord For Each catRecord In catRecords Dim catId As String = "catId" & catRecord.GetString(CategoriesAccess.Instance.CategoryIDColumn) Dim catName As String = catRecord.GetCategoryNameFieldValue() oTree.Add("root", catId, catName) Dim f As New IronSpeed.Base.Data.ForeignKeyValueFilter( _ prodCatFk, _ catRecord.GetID(), _ IronSpeed.Base.Data.BaseFilter.ComparisonOperator.Equals) Dim prodRecords As ArrayList = ProductsAccess.Instance.GetList( _ f, _ Nothing, _ 0, 20, Nothing) Dim prodRecord As ProductsRecord For Each prodRecord In prodRecords Dim prodId As String = prodRecord.GetString(ProductsAccess.Instance.ProductIDColumn) Dim prodName As String = prodRecord.GetProductNameFieldValue() html = "<a href='ViewProduct.aspx?Products=" & prodId & "' target='RightFrame'>" & prodName & "</a>" oTree.Add(catId, "prodId" & prodId, html) Next Next Return oTree.HTML() End Function
178
</script> <table border="0" cellpadding="2" cellspacing="0" style="border-collapse: collapse" bordercolor="#111111" id="AutoNumber1"> <tr> <td> <ASP:Label id="iTree" runat=server text="<%# CreateTree() %>" /> </td> </tr> </table>
Theforeignkey(createdearlier)istransformedintoafilterthatcan beusedtoretrievetheproductsthatmatchthiskey.
Dim f As New IronSpeed.Base.Data.ForeignKeyValueFilter( _ prodCatFk, _ catRecord.GetID(), _ IronSpeed.Base.Data.BaseFilter.ComparisonOperator.Equals)
179
Dim prodId As String = prodRecord.GetString(ProductsAccess.Instance.ProductIDColumn) Dim prodName As String = prodRecord.GetProductNameFieldValue() html = "<a href='ViewProduct.aspx?Products=" & prodId & "' target='RightFrame'>" & prodName & "</a>" oTree.Add(catId, "prodId" & prodId, html) Next
Summary
Thischapterintroducedthenotionofextendingapplication generationtechnologytoautomatetheproductionofcustom, enterpriseclass,webapplications.Welookedatseveralaspectsof howthiscanbeaccomplishedwithreusablepagetemplate,layout pages,andpanels,buttons,menus,components.Wealsoexplored howthisconceptextendstocustomcode,anddemonstratedsome examplesintheformofthirdpartycontrols. Utilizingapplicationgeneratorsmakescodereusepragmaticand easy.Assuch,ITdepartmentscanbegintorealizeproductivity gainsthathavebeenpromisedfordecades.Originalexpectations surroundingcodereusewereloftyonlybecauseofthepragmatic limitationsofdevelopmenttools. Nowthattheselimitationsarebeingremoved,ITisenteringanew eraofincreasedproductivity,improvedresponsiveness,andgreater businessimpact.Inthenextchapter,welldiscusshowyoucan initiatethistransitionforyourorganization.
180
Part10) LookingAhead
ApplicationGenerationProjects WithMaximumImpact
181
SelectingYourFirstProject
Bythispoint,youreprobablyeagertogetstartedonaprojectwith anapplicationgenerator.Inselectingthatfirstproject,itstoyour advantagetochooseaprojectwhereyoucanbuildanddeploy somethingvaluable,anddeliveritquickly.Considerthefollowing attributesoftheapplicationwhenchoosingyourfirstproject. Size&Scope Ideally,yourfirstprojectwillbesmallishinnature,andallowyou tobuildanddeployyourfirstapplicationinacoupleofdays.This meansyourfirstapplicationcouldinvolvejustafewdatabasetables. Further,selectingafirstprojectwithlimitedcomplexityisagood ideabecauseofthemomentumitcancreateforyouandthe technology.Deliveringasolutionwithspeedisexciting,especially sinceitexceedscurrentexpectations,andcontradictspast experience. Thelastthingmostorganizationsexpectisaquicksolutioninthe formofarobustwebapplication.Memoriesofpastexperienceswith webapplicationdevelopmentoftenincludedelays,costoverruns, missedexpectations,andoveralldisappointment.Infact,some organizationstossoutwebapplicationsaspotentialsolutionsto businessproblemsbecauseofthesepainfulpastexperiences. Therefore,ifyoucanstartandfinishasuccessfuleffortquickly, youresuretogeneratepositiveinterestinyourefforts,rekindle positivethinkingaboutcustomwebapplications,andaccelerate broaderadoptionofyourtechniques. ExistingDatabases&Integrity Ifyourfirstapplicationcanbebaseduponanexistingdatabase, youllbeabletorealizethebenefitsofyoureffortsalmost immediately.Further,ifthatdatabasehasgoodqualityandintegrity
182
(meaningthatthedataiscleanandmostlyerrorfree),again,youcan begintorealizethebenefitsofyoureffortswithoutgettingbogged downindatacleansingorrepairefforts. Aspreviouslydiscussed,afirstprojectshouldattainsuccessquickly. Byutilizingexistingdatabases,yourprojectleveragesdatabasework thatsalreadybeendone.Ifthedataisofhighquality,you inherentlyavoidproblemsassociatedwithdatathatsstale, incomplete,orinaccurate.Avoidingtheseproblems,onyourfirst project,isimportantifyouwanttheperceptionofthefirstprojectto beonyouandtheapproachyouused,notnecessarilytheproblems thatneededtobecorrectedanyway. LimitedIntegration/CustomizationWork Whileweveemphasizedthatapplicationscreatedwithapplication generatorscanbeintegratedwithotherapplicationsandextended withcustomfunctionality,manydevelopmentscenariosdont requirethiswork.Insuchsituations,itsentirelypossiblethatyou canbuildanddeployanapplicationthatsolvesabusinessproblem injustadayortwo. Therearemanyexamplesoffirstprojectswheretheprimary objectiveoftheapplicationwasmerelyfindingdatainthedatabase, displayingitviatheweb,andallowingasetofuserstomaintainthat datamorequicklyandeasilythanbefore. Oftentimes,theseapplicationsarecreatedfromlegacyapplications thatwerecreatedwithendoflifetechnology(suchasoldclient serverstyleapplicationsheldoverfromthe1980s)orhave outgrowntheirexistingarchitectures(MicrosoftAccesssystemsthat startedoutbeingusedbyasingleuser,thataresupportinghundreds ofusers). Bothoftheseapplicationsaregreatfirstprojectsbecausetheprimary valuetheyprovideisinfinding,maintaining,andreportingthedata. Theycanbebuiltanddeployedwithgreatspeed,relyonproduction datathatsalreadybeencreated,andtypicallyinvolvenocode extensionsorcustomizations. ClearImpact&Benefit Whilethisisanobviouscharacteristic,itssoimportantthatits worthmentioninghere.Anyapplicationyoubuildshouldmake somethingeasier,faster,morereliable,ormoreconvenientforthe usercommunityoftheapplication. Merelyredeployinglegacydatabaseapplicationsviathewebcan reshapetheimpacttheyhaveuponthebusiness.Evenifsuch
183
applicationsareonlyusedinternally,remoteaccesscanempower employeesthattraveltocustomersitestostillaccessdatabackatthe homeoffice.Oftentimes,however,theseinternaluseonly applicationsarerethoughttoembraceaccessbycustomersand suppliersaswell. Thebenefitsofsharinginformationwithcustomersandsuppliersvia thewebhasbeenembracedbytheindustryanddocumentedin manyothertexts,sotheresnoreasontobelaborthepointhere. Untilnow,however,customenterpriseapplicationshavebeenslow totakeadvantageofthesebenefitsbecauseofthecostsassociated withdevelopingandmaintainingtheseapplications.Application generationtechnologyempowersorganizationstorethinkhowtheir suiteofinternalapplicationscouldberecastaswebapplications,and extendedtobetterservecustomers,suppliers,andothersetsofusers inthecommunity. NeglectedUserCommunity Speakingofusers,letsremembercustomwebapplicationsare expectedfromeverycommunityofuserstouchedbyan organization.Someofthebestfirstapplicationsweveseenarethe applicationsthatITtypicallydoesnthavetimeorresourcesto prioritize.Oncesuchanapplicationisbuiltanddeployed,these userswhohavebeenneglectedthemostcanbecomemost enthusiasticaboutthenewapplication.Sometimes,theylleven becomeproactiveadvocatesandevangelistsforthepersonor organizationthatdeliveredthenewsolution. Havinganenthusiasticusercommunitybehindyourfirst application,evenifitsasmallone,canbeagreatassetwhenyoure readytorolloutthetechnologytoothersinyourorganization.More cautioususercommunitieswillwanttocheckreferences,and understandtheexperiencesofthefirstuserstobenefitfromyour approach.Withsuchreferencesinplace,positivedecisionsabout futureprojectscanbeaccelerated. Keepingthesecharacteristicsinmind,letstakeaquicklookatthree recentexampleswheredeveloperschosetoapplyapplication generationtechnology.
FirstEffortCaseStudy:OtisElevator
OtisElevatorOtisElevatorCo.,awhollyownedsubsidiaryof UnitedTechnologiesCorporation,istheworldslargest manufacturer,installer,andservicerofelevators,escalators,moving walkwaysandotherhorizontaltransportationsystems.
184
TheBusinessApplicationsSystemsManagementdevelopmentteam atOtisElevatorinSydney,Australialooksafterthedevelopmentof allthelocalbusinessrelatedsoftwareapplicationsforalltheoffices inAustraliaandNewZealand.Morethan1,300peoplerelyonthis teamtoprovidethedatabasemanagementandsoftwaresolutions theyneedtodotheirjobsmostefficiently.UsingIronSpeed Designer,twoprogrammersnewto.NETweregeneratingworking, customwebapplicationsinafewhours. Reflectinganevolutionarypathovertheyears,theteammanages applicationsrunningonamyriadofplatformsrangingfrom Natural/AdabastoNT4/APPXtoclientservertontiersystemsusing VisualBasic,ASPandSQLServer.Thelocalteamhaslotsof experienceoptimizingandexpandingapplicationsontheselegacy systems. Beginningin2003,however,whenlookingtomovelegacy applicationstothewebandtheMicrosoft.NETFramework,the teamfacedatrickymigrationchallenge.Theproblemwasthata coupleofinternalapplicationswereneededquickly,andthere wasntmuchtimefortrainingorpractice. Otischosethischallengeastheirfirstapplicationgenerationproject. Wewereveryproductiveusinga4GLrepositorybased developmenttoolbeforewemovedtoWindows,soIknewthe benefitsofcodegenerationcouldbeimpressive.Icheckedout severalcontemporarycodegeneratorsfor.NETandwasencouraged tolearnthatvastimprovementshavebeenmadeintermsof generatedcodequality,theabilitytocustomizetheuserinterface andtoextendgeneratedapplicationssothatmultipleappscanbe connected,theteamleaderexplained.
185
WhatIdidntexpecttofindwashoweasyitistouse.Thatopened myeyestoawholenewtransitionstrategyformyteam.Ratherthan hiringconsultants,Icouldmeetmydeadlinesandkeepthelearning andexpertiseinhouse.Evenifwewereall.NETexperts,itwould stilltakeusthreetimesaslongtolaunchcomparedtousingthis tool,hesaid. Ihavealwaysbelievedincodegeneration,buttherewereveryfew productsovertheyearsthatIthoughtgeneratedtheentire applicationwellenoughtobeuseful.Weneedatoolthatvery quicklycangeneratetheinterfaceandapplicationlayerbasedon complexdatabaseschemas.Wewantedlotsofflexibilityandthe abilitytocustomizeeverypartofthegeneratedapplicationwhen required,hesaid.Imgeneratinghighqualitycodethatweare proudof,andallowingmyteamtofocusoncustomcoding,not infrastructure. WeareusingapplicationgenerationforallnewWebbased developmentprojects.OurstrategyistomigratetoourIntranet somekeyfunctionsusedbylargenumbersofusersnowperformed inlegacysystemsovertheWAN.Thistechnologyisinstrumentalin ourachievingthis. Applicationgenerationhelpsuslaunchfasterandwithadded functionality.Werebeingproductiveon.NETwhilemaintaining ouroutputlevel.
186
FirstEffortCaseStudy:LesSchwabTireCompany
LesSchwabTireCompanyoperatesanetworkofover400retail locationsthatgenerateoverabilliondollarsinannualrevenues.The companyisoneofthelargestindependenttirecompaniesinthe UnitedStates. Foryears,everyoneofthestoremanagersandassistantmanagersat eachoftheretailstoresupdatedtheintranetdatabyemailingor faxinginformationtotheITteam,andthenwaitedforthemtohave timetoinputthedata.Sincethiswasjustoneofmanydocument centricactivitiesatthecompany,theITteamwasmovingeverything toIISandthe.NETFrameworkinordertoautomatefunctions, improveservicetostoremanagement,andsavetimeandmoneyon allendsoftheprocess. TheyneededaquickwaytobuildeditableASP.NETformsto transformaclunky,manual(buthighvisibility)performance trackingprocessintoasmoothwebbasedapplication. LesSchwabTireschosethischallengeastheirfirstapplication generationproject. Theychosetheirapplicationgeneratorandendedupwiththeforms, alltheSQLandtherestoftheapplicationinacoupleofhours.The productionwebapplicationlaunchedadaylater,muchtothe delightofuserslocatedinhundredsofdifferentoffices. WewereusingVisualStudio.NETEnterprise,andIquickly realizedthatbuildinganeditabledatagridwashard,theteamlead said.Iwentlookingforahelpfultoolandfoundanapplication generator. Idownloadeditandsawimmediatelythatthiswasmuchmore thanjustlimitedcomponents,thiswasreallytheanswer,hesaid. Heusedtheapplicationgeneratortoquicklycreateanentirecustom applicationthatlinkedtohiscurrentSQLServerdatabase.Sinceit wasaprettysimpleapplicationinvolvingjustthousandsofrecords, acoupleofmultitablejoinsandoneeditableformwithvarious reportviews,thewholeapplicationwasgeneratedinafewhours. Nocodeextensionswereneeded.Thedevelopershowedittothe restofthedevelopmentteamthatsamedayandlauncheditto employeesthenext.
187
IstartedoutthinkingIjustwantedanonlineform,thelead developersaid,Ifoundalotoffunctionalityinthetoolthat enhancedouroriginalgoalbycreatingnewdatabasetables, changingthepagecontrols,sortingandfiltering,andaddingcustom controlsontheviewreportpage.Apainful,fourstep,manual processisnowonestep,andautomated! WebasicallydeployedtheVisualBasic.NETcodethatthetool generated.Thegeneratedcodeissmoothandsophisticatedandfit rightintoournetwork.Weveryquicklysolvedahighvisibility challenge,and,infact,madeamanualprocesssimplerandmore effectiveforeveryoneinvolved. Likemanydevelopers,thisteamevolvedfrommainframerootsto applicationdevelopmentonthe.NETFramework.Astheshophas movedtoadoptmodernmethodologies,severalcodegenerationand componenttoolshavebeenevaluatedandabandonedalongthe way.Thesystemwasproprietaryortoocomplexorthegenerated codewasbulkyandslow,andhardlyuseful,theteamleadsaidof someoftheothertoolstried.Wearelookingforadvancedfeatures. Weneedtoolsthatworkinourcurrentenvironment. Ihavethreecriteriaforanytool,hesaid.Ithastoworkwithmy othertoolsandplatforms;ithastobeabletodeploywhatis promisedinworking,qualitycode;andIneedtobeabletogethelp fromthevendorifandwhenIneedit. Gettinganythingsophisticatedonthe.NETFrameworkisgreat,but whatwereallyneedonthegroundrightnowaretoolsthatmake .NETmoreusable.
188
FirstEffortCaseStudy:OpenLatitude
OpenLatitudeenablesconsumerproductscompaniesandtheir partnerstoimproveontimedeliveryandoutofstockperformance byhelpingtheircustomerteamsmanagefulfillmentacrossthe extendedenterprise.UsingOpenLatitudemPower,customerteams canidentifypotentialcustomerserviceissuesearly,assesstheeffect ofthoseissuesonkeycustomers,andtakecoordinatedactionacross departmentsandtheextendedenterprisetoresolveissues. Here,theteamleadisaprofessionaldeveloperwhowriteslarge scale,missioncriticalwebbasedapplicationsforcompanies developingCRMandsupplychainproducts.WhatIliketofocus onisbuildingapplicationsthatthecustomerwillwanttouse,he said. Inearly2003,thedevelopmentteamfacedatightdeadlinetodeliver arobustproductrelease.OpenLatitudechosethisprojectastheir firstapplicationgenerationproject. Usingtheapplicationgeneratorreallycompressedour developmentcycle,hesaid. Theapplicationgeneratorgaveusalotofutilitieswithnoruntime drag.Wegotsearch,pagination,navigationandotherstandard pagecontrols,transactionmanagementandalltheSQLstatements forfree.Itsavedusweeksofnothavingtoworryaboutbuilding thosefeatures.
189
Thestandardtemplateuserinterfacecanbeeasilycustomizedand thatsavedusalotofwork.Weputinourownstylesheetandare usingthisasourfinaldesign.Muchsimpler,andmuchmoreflexible thandoingitallbyhand,theteamleadsaid. Alotofworldclassapplicationsandproductsarebeingdeveloped, butnoonecanaffordtospendayearormoreondevelopment anymore.Youhavetobefastindevelopinganddeploying.And, youhavetobeveryresponsivetocustomerneeds. Whenyouuseacodegenerator,youcanconcentrateyoureffortson buildingthebusinesslogic,hesaid.Usinganapplication generatorfreedustomakeourproductevenmorerobustand relevanttoourcustomersneeds. Healsofoundthatgeneratedcoderelievedhimandtheteamfrom thepressuresofcodefreeze.Sure,onceyouknowthedesign, buildingsomethingisprettystraightforward,hesaid.Butin productdevelopment,therequirementsareconstantlychanging. Thetimeittakesforustoturnaroundandaddsomethingbackinis incalculableandusedtospelldeathforontimedelivery. Applicationgeneratorsreducetheoveralltimeline,buttheyalsolet megoback,makechangestopagecontrols,layoutsandfeaturesand quicklyregenerate.Inthepastsixmonths,theapplicationgenerator hasallowedustogothroughanumberofengineeringdesign
190
FirstEffortCaseStudy:TexasYouthCommission
TheTexasYouthCommissionisastateagencyinDallasthathelps protect,rehabilitateandguideyoungpeopleinthejuvenilejustice system. TheITteamhelpsTexasstateemployeesworkmoreefficientlyby automatingmanualsystemsandprocesseswitheasytouseweb basedapplications. Folksareusedtowhatevermanualprocesstheyhavebeendoing. Awebapplicationhastodomorethanjustdeliverfullfunctionality andsavetime.Ithastocomfortthemearlyintheprocesssothat theybuyinandsupportthedevelopmentanddeployment,the teamleadsaid. TheITteamhelpsemployeesinthefinancedepartmentmakesense andactupondatathatcomesfrommultiplestateandexternal systems.With14facilitiesthroughoutthestate,andhighly confidentialinformationbeingpassedintraagencyandthrough otherstateagencies,ITmustincorporateallthedataintoacommon, missioncriticalsetofapplicationsthatservesadiversesetofusers. Iuseanapplicationgeneratortoquicklygeneratetheentire transactionalsideoftheapplication,aswellasaddpagecontrolsand filtersforreports,theteamleadsaid. FirstthingIdoisgenerateasampleapplicationusingthedefault screensthatthetoolgenerates.Thisisjustafewquicktableswith simplefunctionality.Ittakesmeabout15minutestogeneratethem. Butitsaworkingapplication. Iapproachedapplicationgenerationwithcaution.Iusedcode generatorsyearsagoandwasneversatisfied.Withtheapplication generator,Ivestoppedworryingaboutthegeneratedcode.Im focusedinsteadontheothereightapplicationsonmyplatethatit canhelpmebuild,hesaid. IveusedeveryfacilityIcan:customizingtransactionmanagement andSQLstatements,linkingtomultipledatabases,formatting,child
191
tables,detailededitrecordforms,preselectingfieldvaluesina detailspage,insertingtables,multitablejoins,addingbuttons, searchingcategories,variousreporting,codeextensionsitsall there,hesaid. Itwouldhavetakenmemaybetwomonthstodothisrightto makeitenterpriseclass.Usingtheapplicationgenerator,itwas abouttwodays,includingmycustomizations,hesaid. ImaonemanteamandIreallyneededthehelp.Imuptomy neckinitnow.Imabletotacklemoreprojects,confirmeventight projectscheduleswithmoreconfidenceandbemorecreative.
OrganizationalRolloutofApplicationGenerationTechnology
Onceyouvebuiltanddeployedyourfirstapplication,andyouve createdanenthusiasticendusercommunity,youllbereadytoroll outapplicationgenerationtechnologytoothersinyourorganization.
BasicRolloutEssentials
Whenenteringthisphase,thereareafewbasicassetsyoucancreate tohelpotherdevelopersinyourorganizationbenefitfromyour experiences.Considercreatingthefollowingassetsfortherollout: CaseStudies Casestudiesdocumentyourexperiencebuildingtheapplicationand helpotherdevelopersunderstandwhatyouvedone.Typically,a casestudydescribestheproblemstheapplicationaddresses,details thetechnicalapproach,anddocumentstheimpact.Casestudiescan becreatedinavarietyofformatsincludingwhitepapers, presentations,evenvideos.Whatevertheform,capturingthefacts thatsurroundthefirstsuccessisanessentialstepinrollingoutany newtechnology.Sometimes,thevendorofatoolortechnologythat wasusedincreatingtheapplicationcanprovideassistancein creatingthesecasestudies. GuestAccounts Sincethisnewtechnologyinvolveswebbasedenterprise applications,itsoftenquiteeasytocreateaspecialguestaccountfor developersthatareinterestedinseeingthesoftwareyouvecreated. Withasmallamountofeffort,youcancreateauserrolethatcan grantothersaccesstoyourapplication,allowthemtoseewhat youvedone,andstillrestrictthemfromhavinganyactualimpact upontheproductiondata.
192
ResourceWebPage Anotherassettoconsidercreatingisaresourcewebpageforyour project.Linktoresourcesyoufoundhelpfulinlearningabout applicationgenerationandcreatingyourfirstapplication.Sucha resourcepagecansaveotherdevelopershoursofeffort.Suchpages arealsoagreatplacetosharecasestudypapers,presentations,and videos.Theycanalsodescribehowtoapplyforaguestaccount,or includesourcecodefortheapplicationyouvecreated. InternalUserGroupPresentations Ifyourprojectgeneratesalotofinterestwithinyourorganization, youmightconsiderforminganapplicationgenerationusergroup. Suchanorganizationcanfacilitateinteractionbetweenpeople interestedinthetechnology,andletparticipantslearnfromeach other. Theseassetswillhelpdevelopersthroughouttheorganization understandandadoptapplicationgenerationtechnology.Thiseffort laysthefoundationforadvantagesreservedforthoseIT organizationsthatfullyadoptthetechnology.
AdvancedPlatformPossibilities
Oncedevelopershavebeenintroducedtothenotionofapplication generation,andhavehadthechancetobuildanddeployan applicationortwo,yourorganizationwillbereadytointroduce companyspecificassetsthatpromisecanmakeITdevelopmenteven moreefficient. UserInterfaceStandards Usingpageandlayouttemplatesthathavebeencustomizedforyour organization,youcanstronglyencourageuserinterfacestandards compliancethroughapplicationgeneration.Aspreviously mentioned,oncethesefileshavebeencreated,itsactuallyeasierto complywiththestandardthantodeviatefromit. DatabaseStandards Applicationgeneratorshelpalleviatebottlenecksassociatedwith buildingdataintensivewebapplications.Implicitly,theyenforce integrityforSQLqueries,andcanexplicitlyenforcepreferencesfor customSQLstatementsanddatavalidationlogic.Whenusinga properlyconfigured,highqualityapplicationgenerator,database administrationresponsibilitiesinsupportofwebapplication developmenteffortsisgreatlysimplified.
193
CodeReUse Onceanapplicationgeneratorhasbeenconfiguredtoincorporate customcode,allfutureapplicationsthatitcreatescanincludethis customcodeaspartofthegenerationprocesswithnoadditional work.Againthisapproachmakesitmucheasierfordevelopersto reusecodethantorewriteit. ArchitecturalStandards Sinceapplicationgeneratorsshouldermostoftheburdenofcreating anapplication,theydeliverapplicationsthatconformtoaconsistent andstateoftheartarchitecture.Asthenumberofapplicationsbuilt increases,maintainingaconsistentandstandardarchitectureacross allapplicationswillreducecomplexity,andholddownenduser supportandtrainingexpenses.
EnablingaNewKindofDevelopmentTeam
Onceinplace,applicationgeneratorsthathavebeenfinetunedto theneedsoftheorganizationcanempowermorepeople,evenwho havenottraditionallybeeninvolvedindevelopment,andenable thosepeopletomakearealcontributiontothedevelopmenteffort. Intheearlydaysofpersonalcomputing,thefirstnondeveloper developersweresimilarlyempoweredbyVisiCalc.Forthefirst time,professionalsthathadnotbeentrainedascomputerscientists wereabletocustomizethefirstspreadsheettoolforaspecific purpose.Later,toolslikeLotus123andMicrosoftExceltookthese initialcapabilitiestonewandextraordinaryheights.Today,these spreadsheetpoweruserscancreateapplicationsthatdo extraordinarythingswithoutwritinganycodeotherthanmacros. Developmentofenterprisewebapplicationsisonasimilarpath. Today,whileitsstillnotquitepragmaticfornonprogrammersto buildanddeploydatabaseintensivewebapplications,itscertainly possible.Applicationgeneratorsdramaticallysimplifythe developmenteffortassociatedwiththistask,andautomatemuchof theeffort.Asaresult,businessanalysts,softwarearchitects, marketingstaffers,andothersarenowabletocreateanddeploy basicwebapplications. Organizationsthatrecognizethisfundamentalshiftinhowsuch projectscanbestaffedwillbeabletoorganizetheireffortsinanew way.Theyllleveragenontechnicalprofessionalsearlyinthe developmentprocessbyarmingthemwithapplicationgeneration technology.ThisnewclassofdeveloperwillenableITtocaterto moreneedsofmoreusers.Insteadofmerelygatheringrequirements
194
TheNewReality: CompetitiveAdvantageRequiresUbiquitousCustomSoftware
AsITdepartmentsempowerlesstechnicalprofessionalsto contributesignificantlytoapplicationdevelopmentprojects,they willbeabletoscaletheirefforts.Thisstreamlined,productive,and powerfulsoftwaredevelopmentcapabilitywillenableITtoonce againmeetincreasinglyhigherexpectationsfromeveryonewho interactswiththebusiness.
TheRiseofNanoApplications
Inrecentyears,theusercommunityofonlinebusinessapplications hasdramaticallyincreased.Backintheolddays,client/serverstyle applicationswerereservedforinternalemployees.Eventheiruse wasrestrictedtoparticularroleorpurpose. Inthe1990s,duringthelastdaysoftheclient/serverera,the emergenceofubiquitousnetworkconnectivityandprotocol standardsfacilitatedanunprecedentedexplosionofnetwork connectedbusinessapplications.Inthespanofjustafewyears,the internetrevolutioncombinedwithY2Krelatedupgradestorecast nearlyeveryaspectofITstrategiesandpriorities.Everyones expectationsabouttheubiquityandpotentialofwebbased applicationsskyrocketed. Butalongwiththeseexpectations,developmentcostsalso skyrocketed.Eventually,ITmanagers(ortheirbosses)realizedthat itcostanextraordinaryamountofmoneytobuildandmaintain theseapplications.Asaresult,theycutspending,andmostnever realizedthoseloftyoriginalexpectations. Thelessonslearnedwerepainfulbutcommonplace.Usingthe developmenttoolsandtechniquesofthelastcentury,dataintensive webapplicationstooktoolongtobuild,costtoomuchmoney,and weretoohardtomaintainandenhanceovertime.Oncefacedwith thisreality,developmentplanswereshelvedforallbutthemost criticalapplications,andeventhen,conservativeROIanalysis becameastrictprerequisiteforeveryproposeddevelopmenteffort.
195
Butnow,itstimetorevisitthoseplans. Today,developersarenolongershackledwiththedevelopment toolsandmethodologiesofthepastcentury,andcanreliablydepend onapplicationgenerationtechnologytoshouldermostofthe developmentburden.Asaresult,awholenewclassofenterprise webapplicationisabouttoemerge. Thisnewclassofapplicationswillbetransactionintensive,automate aspecificbusinessprocess,andchangeinstepwiththebusiness. Andtherewillbethousandsofthem. Businessuserswilldrivethedevelopmentpriorities,anddevelopers willcatertotheirneedsquicklyandeasily,anddiscoverimproved businessprocessesalongtheway.Interactionbetweenbusiness usersanddevelopers,andthespeedwithwhichtheycollaborateto improvebusinesssoftwaresystems,willbecomethecentral competitiveissueoftheday. Enabledbynewtechnology,small,specialized,andubiquitousthis newclassofapplicationspromisestobethesoftwareequivalentof nanotechnologyhencethetermnanowebapplications. Nanowebapplicationsareeconomicallyfeasibleprimarilybecause ofapplicationgenerationtechnology.Itwonttakeweeksormonths tobuildtheseapplicationsbutonlydays.Stilltheyllbefeature rich,stable,andsecure. Asorganizationsbecomeadeptwiththenewtechnology,ahuge waveofspecialpurposeapplicationswillappear.Yesterdayseraof costly,big,monolithic,centralized,ITprojectswillmorphintoa distributed,efficient,networked,everdynamicuserdrivenage.The originalvisionofinternetapplicationsbeingavailabletoassistin automatingeverybusinessprocesswillberesurrected,realized,and evenexpandedupon. Earlierinthischapter,wediscussedseveralexamplesofapplications thatareindicativeofthisimpendingseachange.HereatIronSpeed, wevealreadyseenhundredsofothernanowebexamples.Bythe timeyoureadthis,therewillbethousands,orhundredsof thousands,more. Ofcourse,theresponsibilitiesformanagingthistransitionwillfall ontotodaysITdepartmentsanddevelopers.Duringthetransition, theywillstillfacedemandsfrominternalusers,andwillalsoneedto findwaystoaccommodateincreasingdemandsfromcustomers, employees,andevensuppliers.Further,eachofthesedistinctuser
196
groupswillneeddifferentkindsofaccesstodifferentkindsofdata, andtheirneedswillbeconstantlychanging. ThesechallengeswillrequireITtoadoptdevelopmentstrategies, methodologies,andtoolsthataredesignedtosupportanalways onenvironmentthatsconstantlychanging.Armedwith applicationgenerationtechnology,ITwillnotonlycopewith,but leadthetransition. Thosewhoareslowtoadoptthenewtechnologywillstruggle.The commonhistoricalapproachofbuyinganofftheshelfsoftware package,andthencustomizingitinatraditionalfashion,wontbe adequate.Bythetimesuchsoftwareisinstalled,configured,and customized,itwillbetypicallyobsolete(evenwiththesupportofa wellintentionedandcapablevendor).Downstream,whenthe vendorsdevelopmentpathdivergesfromyourrequirements(orif theygooutofbusiness),suchanapproachbecomesevenmore untenable.
TheApplicationGenerationFuture
Asapplicationgeneratorsproducemoreandmoresuccessfulcustom applications,ITdepartmentswillincreasinglyopttoregaincontrol ofthesourcecodepoweringtheirorganization.Byadopting applicationgenerationtechnology,theseorganizationswillbuild anddeploymoreandmoredatabaseintensivewebapplications, bettercatertogrowingusercommunitieswithconstantlychanging requirements,anddoitallfasterthaneverbefore.
197
ContactIronSpeed
Youcangetstartedwithapplicationgenerationtechnologytoday withfreeevaluationsoftwarefromIronSpeed.Todownloadthe software,visitourwebsiteatwww.ironspeed.comorcontactusvia emailatinfo@ironspeed.com. Wewelcomeyourcommentsonthisdocumentaswellasideasfor futuretopics.Pleaseemailusateditor@ironspeed.com. IronSpeed,Inc. 1953LandingsDrive MountainView,CA94043 16502152200 email:info@ironspeed.com
198
AbouttheAuthor
AlanFisherisanotedexpertincommercialsoftwaredevelopment andasuccessfulentrepreneur.Currently,hesChairmanofIron Speed,Inc.,aninnovativeproviderof.NETprogrammingtools.The companysflagshipproduct,IronSpeedDesigner,iswidely recognizedasoneoftheleadingapplicationgeneratorsavailable today. PriortocofoundingIronSpeed,FisherwasaGeneralPartnerat OutlookVentures,aventurecapitalfirm.Whilethere,Fisherled earlystageinvestmentsinavarietyofsoftware,infrastructure,and ecommercestartups.Today,FisherservesontheBoardof DirectorsofInfodataSystemsInc.,(NASDAQ:INFD),anelectronic documentmanagementconsultingservicescompanyandpreviously servedontheboardsofOnsale(N:ONSL),EggheadSoftware (N:EGGS),andFatbrain(N:FATB). BeforejoiningOutlookVentures,FishercofoundedOnsale,Inc.,and wasitsChiefTechnologyOfficer.Asthefirstauctionstylee commercebusinessontheinternet,Onsaleexperiencedmeteoric revenuegrowthcompletedasuccessfulpublicofferingin1997, acquiredEggheadSoftwarein1999,andwaseventuallyacquiredby Amazon.Duringhistenure,Fisherledatechnicalteamofovera hundreddevelopersthatcreatedandmanagedanebusiness infrastructurethatmanagedtensofthousandsoftransactionsper day.Atthetime,Onsalewasthelargestecommerceapplication everbuilt. Inthelateeightiesandearlynineties,Fishercofoundedandwas PresidentofSoftwarePartners,Inc,adeveloperandpublisherof awardwinningdesktopsoftwareproducts.Productsbuiltby SoftwarePartnersincludedTimesheetProfessional,andahitseriesof financialservicesapplicationsmarketedundertheStreetSmartbrand byCharlesSchwab. Earlierinhiscareer,Fisherplayedavarietyoftechnicaland marketingrolesatTeknowledge,Inc.,apioneeringdeveloperof artificialintelligencesoftwareproducts.Duringhistenure, Teknowledgecommercializedsomeofthefirstproductsandservices toincorporatefundamentalsoftwareconceptssuchasobject orienteddesign,rapidprototyping,anditerativedevelopment methodology.WhileatTeknowledge,FisherauthoredCASE: ComputerAidedSoftwareEngineering,thefirstbookonthisareaof softwareengineering,in1989.
199
200
Index
.NET Directives .................................................156 .NETcache ......................................................92 @Registerdirectives.....................................156 {0}redirectargument ..................................133 100%AccesstoGeneratedCode..................67 1980s IDEs ...........................................................23 1990s ApplicationServers ..................................24 3tierarchitecture...........................................62 AVeryFirstStep AFunctional,BugFreeApplication ......44 AbouttheAuthor ........................................199 Acknowledgements.........................................3 ActiveDirectoryandLDAP .......................117 Addrecordpages ..........................................34 AddingaNewRecordtoaDatabaseTable .....................................................................81 AddingaReusablePaneltoaPage...........160 AddingThirdPartyControlsand Components.............................................174 AdditionalSecurityIssuestoAddress .....116 ADO.NET .................................................85,93 AdvancedPlatformPossibilities................193 AlgorithmicApproach..................................60 AnApproachtoGeneratingExtendable Code..........................................................125 Application Signin ......................................................114 Applicationgeneration .................................13 ApplicationGenerationFuture..................197 ApplicationGenerationProcess ..................82 Applicationgenerators .............26,55,92,101 ApplicationIntegrationStandardization ...21 Applicationlayer ...........................................63 ApplicationLayerGeneration .....................84 ApplicationLogicErrors ..............................89 Applicationserver .........................................16 Applicationservers .......................................24 ApproachestoApplicationGeneration......60 ArchitecturalStandards..............................194 ASP.NET .........................................................37 Directivesinpagetemplatefiles...........156 ASPX.......................... 65,67,70,72,82,83,122 AutomateC/R/U/DPageCreation ............. 32 Automated,YetRobustUIBrings ApplicationPowertoLight .................... 54 AutomaticDataValidation&Display....... 39 AutomaticReuseofASP.NETDirectivesin PageTemplateFiles ............................... 156 AutomaticSignout .................................... 116 AutomaticSQLGenerationforDatabase ConnectedControls ................................. 90 AutomatingApplicationSecurity ............ 107 AutomatingCodeReUsewithPanels& Components............................................ 159 AutomatingDevelopment AHistoricalPerspective.......................... 22 AutomatingITStrategies........................... 146 AutomatingPageProduction ................... 147 AutomatingReUseofCustom&Third PartyControls......................................... 174 AutomationinAction CommonProblemsSolved ..................... 31 AvoidsCodeOrphaning............................ 124 BasicRolloutEssentials.............................. 192 BonusAutomation(EvenMoreCodeYou DontHavetoWrite ................................ 85 BoostYourCompanysROI ........................ 55 Browserclienttier......................................... 15 Building&ReusinganIndependent ReusablePanel........................................ 159 BuildingReusablePanelsandComponents .................................................................. 158 Businesslogic ................................................ 52 Buttonactionsandproperties ................... 131 ButtonPanels............................................... 161 ButtonTags.................................................... 70 Buttons ......................................................... 161 Adding..................................................... 131 C/R/U/Dpages ...................................19,32,64 cache ................................................55,104,105 CASE............................................................... 23 CaseforAutomation .................................... 12 CaseStudies................................................. 192 ChallengesofWebApplication Development ............................................ 14 CharacteristicsofGoodGeneratedCode .. 47 ClearImpact&Benefit............................... 183
201
clientsidescripting .................................67,83 CodeCompleteness&Organization...........45 Codegenerationtags.....................................68 FieldValue..................................................72 Image ..........................................................70 ItemTemplate ............................................74 Table ...........................................................74 Use ............................................158,161,164 CodeGenerationTags.......................61,67,69 CodeOrphaning ..........................................124 CodeReUse .................................................194 CodeShouldMeetProfessionalStandards ...................................................................123 CodingExamples Displayatablewithmultiplefields withinasortablecolumn...................127 Columns Sortable.....................................................127 CommonButtonActionsandProperties .131 ComplexDisplays..........................................35 Complex,YetBoring,Development ...........19 ComponentBindingProcess........................77 Componentinteraction Pageredirection ......................................135 Compositeprimarykeys ..............................91 Compton,Michael ...........................................3 ComputerAidedSoftwareEngineering ....23 Concurrency Ingeneratedapplications.......................103 Concurrencycontrol......................................91 ConcurrencyControl/Concurrency Handling ..................................................100 Concurrencyhandling ................................100 ConcurrencyHandlinginGenerated Applications.............................................103 ConfiguringSignInPagesforYour Application ..............................................114 ConfiguringYourWebPagesforRoleBased Security.....................................................114 ConnectingWebPagesandDatabound ControlstotheDatabase..........................65 ContactIronSpeed ......................................198 Controls Addingthirdpartycontrols..................174 Cookies............................................................92 Create/Review/Update/Deletepages ....32 CreateHundredsorThousandsofWeb Pages...........................................................64
CreatingUserAccounts ............................. 112 CreatingUserRoles .................................... 113 Cultureencoding ........................................ 144 Cursormanagement..................................... 91 CursorManagement................................... 103 CustombuildtheUniqueAspectsofyour Application ............................................... 51 CustomizingGeneratedApplications ....... 66 DataManagement ...................................... 104 DataRecency ............................................... 104 DataSorting&PageNavigation ................ 87 Datasources Addinganewrecord............................... 81 Parentsrecordorcurrenttablerow...... 79 DataTransmissionEncryption ................. 116 datavalidation ....47,63,82,84,121,124,125, 128,131 Datavalidation.............................................. 40 Addingcustomcode.............................. 128 Database Resultsets.................................................. 37 Storedprocedures .................................... 92 DatabaseCursorsinGeneratedApplications .................................................................. 104 DatabaseExceptionErrors .......................... 89 Databaselayer ............................................... 63 DatabaseLayer............................................ 105 DatabaseLayerGeneration ......................... 85 DatabaseManagementComplexity ........... 18 DatabaseStandardization............................ 20 DatabaseStandards .................................... 193 Databasetableviewpages........................... 33 Databasetables Userrole .................................................. 114 Databasetier .................................................. 16 databaseviews .........................................96,97 Databaseviews.............................................. 91 DatabaseViewsProvideDataConsolidation .................................................................... 96 Dateandtimeformatting .......................... 144 DBA .....................................................65,91,94 Declarativeapplicationgenerators............. 60 Declarativemethodapplicationgenerators .................................................................... 62 DeclarativeMethodPhilosophy ................. 60 DeleteRecordButton ................................... 34 DeliveringaCommonRequest ExportingApplicationData ................... 40
202
Designthemes..............................................147 Everest ......................................................148 Kilimanjaro ..............................................148 Matterhorn...............................................148 McKinley..................................................148 Shasta........................................................148 Vanilla ......................................................148 Displayatablewithmultiplefieldswithina sortablecolumn.......................................127 Editrecordpages ...........................................34 Embeddingcontrols ....................................175 EmergenceofIterativeDevelopment .........29 EnableCorporateComputingStandards ...53 EnablingaNewKindofDevelopmentTeam ...................................................................194 Errorreporting ...............................................88 Errortextstringtranslation........................144 Errorvalidation..............................................88 EveryUsersRequest,Canyouadda buttonthat?.........................................131 EvolutionofAutomatedSoftware Development .............................................23 Example AddingCustomDataValidationCode128 AddingReportingtoaGenerated Application .........................................137 ChangingthePresentationLayer .........126 IntegratingaThirdPartyControl.........175 IntegratingaThirdPartyControlwith theDatabase........................................176 ExamplePageTemplate AutomatedRecordPages ......................151 Examples Displayatablewithmultiplefields withinasortablecolumn...................127 ParameterpassinginURLs ..........133,135 PassingprimarykeyvaluesinURLs ..134 exceptionanderrorhandling.......................47 ExceptionandErrorManagement ..............88 ExistingDatabases&Integrity ..................182 ExportTableWizard .....................................40 Exportingapplicationdata...........................40 ExtendingandCustomizingApplications ...................................................................120 ExtendingtheCodeGeneratorItself (AutomatedCodeReuse).........................45 Externalapplications.....................................52 FieldDisplayTags .........................................70
FieldValidationTypes ................................. 40 Fields Datavalidation ......................................... 40 Displaying................................................. 40 FieldValuecodegenerationtag .................. 72 FilterTags ...................................................... 70 filtering..........................................63,69,78,91 Filters Specifyingincode .................................. 179 FirstEffortCaseStudy LesSchwabTireCompany ................... 187 OpenLatitude......................................... 189 OtisElevator ........................................... 184 TexasYouthCommission ..................... 191 foreignkey ........................................76,99,100 Foreignkeyrelationships .................91,98,99 ForeignKeyRelationshipsPermitMulti TableJoins................................................. 98 Foreignkeys .................................................. 98 Explicit....................................................... 99 PassingvaluesinURLs ........................ 133 Virtual........................................................ 99 Forward............................................................ 9 Frames .......................................................... 177 Generatedapplications ......................... 177 GatherFeedbackEarly&OftenintheCycle withRealSoftware................................... 49 GeneratingDynamicContextSensitive Panels....................................................... 169 GeneratingNavigationMenuPanels....... 164 GeneratingRoleBasedApplicationSecurity .................................................................. 108 GeneratingStoredProcedures .................... 95 GeneratingtheWebBasedPresentation Layer .......................................................... 63 GetList .......................................................... 179 Goals&BenefitsofAutomated Development ............................................ 42 GroupingandIterationTags....................... 70 GroupingFieldValueTagswithRecordTags73 GuestAccounts ........................................... 192 Gustafson,Paul ............................................... 3 HandlingSQLInjectionAttacks ............... 118 HowAutomatedDevelopmentWorks...... 59 HowCodeGenerationTagsWork ............. 68 HTML ................................23,61,62,67,70,83 IDEs ............................................................... 23 Imagecodegenerationtag .......................... 70
203
ImageTagAHelloWorldExample..........70 ImplicationsforDevelopmentMethodology .....................................................................48 ImpliedSecurityfromanNTier Architecture .............................................116 Import&ExportFacilities ............................87 Inline(Embedded)SQL...............................94 InputstoGenerateYourApplication .........62 IntegratingBusinessLogic ...........................52 IntegratingExternalApplications ...............52 InternalErrors ................................................88 InternalUserGroupPresentations............193 Internationalization .....................................143 Internationalizing(Localizing)Your Application ..............................................143 IronSpeed,Inc. ................................................9 ItemTemplatecodegenerationtag..............74 KeepDevelopmentInhouse........................56 KeyBenefitsofApplicationGeneration Methodolgy ...............................................52 LayoutpageFiles Embeddingcontrols ...............................175 LayoutPages ..................................................67 LayoutTags ....................................................70 LDAP.............................................................117 LimitedIntegration/CustomizationWork ...................................................................183 LinkingDatabaseTables,ViewsandQueries toanApplication ......................................75 Localization ..................................................143 Localizing(Internationalizing)Your Application ..............................................143 LocationoftheSQLStatements...................94 LookingAhead ............................................181 Lostpasswords ............................................115 MDA..........................................................27,60 MDA/UMLPhilosophy ................................60 Meeting&ExceedingUserExpectations ...91 Menupanel...................................................150 Menupanels .................................................164 Menu_Itempanel.........................................150 Menu_Item_Highlightedpanel .................150 Menus Thirdpartycontrols ...............................174 Miller,Stephanie..............................................3 Modeldrivenarchitecture............................27 ModernRequirements ..................................25 Mohiuddin,Razi ..............................................3
MoreComplexDataDisplays TableTags&DataGrids ......................... 74 MultipleRoleAuthentication ................... 110 Multitablejoins ............................................ 98 navigation .............................63,69,91,95,127 Navigationmenubars................................ 164 NeglectedUserCommunity...................... 184 NETapplicationdevelopment.................... 61 Ntierarchitecture..................................62,116 Numberandcurrencyformatting ............ 144 Onsale,Inc. ...................................................... 9 OptimisticConcurrency............................. 102 OrganizationalRolloutofApplication GenerationTechnology ......................... 192 orphanedcode............................................. 124 Pageencoding ............................................. 144 PageRedirection ......................................... 135 Pagetemplates Addrecordpages..................................... 34 ASP.NETdirectives ............................... 156 Creatingandcustomizing..................... 147 Databasetableviewpages...................... 33 Definition ................................................ 151 Deleterecordfunction............................. 34 Editrecordpages ..................................... 34 Exporttabledialog................................... 40 Recordpagetemplates .......................... 151 Viewrecordpages ................................... 34 Paginationpanel ......................................... 150 Panels............................................................ 158 Addingreusablepanels ........................ 160 Button ...................................................... 161 Menu.................................................150,164 Menu_Item.............................................. 150 Menu_Item_Highlighted ...................... 150 Pagination ............................................... 150 Range_Filter............................................ 150 Recordinformation................................ 169 Reusable .................................................. 159 Search....................................................... 151 PanelsRequiringRecordInformation ..... 169 PassingdataviatheURL............................. 73 PassingOtherValuesBetweenPages ...... 135 PassingParametersinURLs .................... 135 PassingPrimaryandForeignKeyValuesin URLs ....................................................... 133 PassingPrimaryKeyValuesBetweenPages inURLs................................................... 134
204
PasswordStorage ........................................117 Passwords Lost ...........................................................115 PessimisticConcurrency.............................102 PlacingRoleInformationinYourUsers Table .........................................................114 Pragmatic,YetRevolutionary,Approachto CodeReUse ............................................158 Presentationlayer ..........................................63 Changing..................................................126 Generation .................................................63 PresentationLayerGeneration ....................83 PrimaryKeyRelationshipsPermitRecord Editing ........................................................97 Primarykeys ..................................................97 Querystringparameters...............................73 Range_Filterpanel.......................................150 RecordPageTemplates...............................151 RecordTags ....................................................70 Redirection....................................................135 Reporting Addingtoageneratedapplication.......137 ResourceWebPage .....................................193 Resultsets .......................................................37 ReusableComponents ................................158 ReusablePanels............................................158 Addingreusablepanelstoapage ........160 BuildingIndependentPanels................159 Buttons .....................................................161 Menus .......................................................164 Usingrecordinformation ......................169 Rolebasedsecurity .....................................114 RoleBasedSecurityOverview ..................108 RPGII ..............................................................23 Scalability........................................................55 ScalabilityComplexity ..................................18 search...................................................63,91,96 Searchpanel .................................................151 SearchTools....................................................86 Securingwebpages.....................................108 Security ActiveDirectory......................................117 Configuringwebpages..........................114 LDAP ........................................................117 Ntierarchitecture...................................116 Rolebased................................................108 Userroles .................................................113 SecurityComplexity......................................19
SecurityYourGeneratedWebApplication .................................................................. 111 SelectingYourFirstProject........................ 182 Signinpages................................................ 114 Signoutpage............................................... 114 SigningIntoYourApplication&Managing LostPasswords....................................... 115 SimpleSigninAuthentication.................. 109 SimplifySoftwareMaintenance.................. 51 SingleRoleAuthentication........................ 110 Size&Scope ................................................ 182 SourcingFromParentsRecordorCurrent RowinaTable .......................................... 79 SpecifyinganApplicationsBasic FunctionalitywithCodeGenerationTags .................................................................... 61 SpeedDevelopmentandReduceTesting Time ........................................................... 52 SQL55,65,73,76,78,82,85,91,92,94,95,99, 103,104,105,124 Efficiency................................................... 91 Inlinestatements..................................... 94 Locationofstatements........................91,94 Storedprocedures .................................... 94 SQLEfficiency ............................................... 91 StandAloneFieldValueTag ....................... 72 StandAloneFieldValueTagExample....... 72 StandardsforGeneratedCode.................. 122 StandardsMakeApplicationGeneration Possible...................................................... 20 StartingfromScratch TheApplicationSpecificDataModel ... 44 storedprocedures ..................85,93,94,95,96 Storedprocedures......................................... 92 StoredProceduresEnhancePerformance& Maintainability ......................................... 94 Summary...........................41,89,105,145,180 Tabbars........................................................ 164 Tablecodegenerationtag............................ 74 TableComponentTags ................................ 70 Tabledisplay ............................................... 127 TableTagDisplayingTabularData ........ 74 TableTags ...................................................... 70 Tableviewpages........................................... 33 TheNewReality CompetitiveAdvantageRequires UbiquitousCustomSoftware .......... 195 TheRiseofNanoApplications ............... 195
205
Thirdpartycontrols ....................................174 CyberAKTASPNetMenu.......................175 Independentthirdpartycontrol...........175 Menus .......................................................174 ThreeTieredArchitectureComplexity ......15 Today ApplicationGenerators............................26 Transactionmodel .........................................91 TransactionModelandTransaction Management..............................................92 UML...........................................................27,60 UML&MDAPoorAlternativesforMost Developers .................................................27 Universalmodelinglanguage......................27 URL Parameterpassing...........................133,135 Parameters .................................................73 UseBusinessAnalyststoDevelop Prototypes ..................................................50 Usecodegenerationtag..............158,161,164 useraccesscontrols .......................................47 Useraccounts creating.....................................................112 Userauthentication .....................................114 UserInputValidationErrors .......................88
UserInterfaceComplexity........................... 16 UserInterfaceStandardization ................... 20 UserInterfaceStandards............................ 193 Userroles ..................................................... 113 UserSignInPage........................................ 114 UserSignOutPage .................................... 114 Usertables.................................................... 114 UsingDataGridstoManageLargeResult Sets ............................................................. 37 UsingDeclarativeMethodstoSpecifyan Application ............................................... 67 UsingtheFieldValueTagtoDisplayData 72 Viewrecordpages ........................................ 34 VisualBasic.......25,66,82,83,94,95,125,126 VisualBasic.NET.......................................... 93 webpages .......61,62,64,66,68,104,124,127 WellorganizedCode ................................. 122 WhatDeclarativeMethodApplication GeneratorsCreate .................................... 62 WhatShouldanApplicationGeneratorDo? .................................................................... 43 WhatsinaPageTemplate? ...................... 151 Wizards Exporttable............................................... 40
206