Pet Shop 3.0

download Pet Shop 3.0

of 18

Transcript of Pet Shop 3.0

  • 8/8/2019 Pet Shop 3.0

    1/18

    . NET Questionnaire

    Gregory LeakeMicrosoft Corporation

    James Duff Vertigo Software, Inc.

    May 2003

    Applies to:

    Microsoft .NET Framework 1.0 and 1.1Microsoft Windows 2000 and Windows Server 2003Microsoft Internet Information ServicesMicrosoft SQL Server 2000Oracle 9i Database

    Summary: Version 3.x of the .NET Pet Shop addresses the valuable feedback given by reviewers of the .NET Pet Shop 2.0 and was created to ensure that the application is aligned with the architectureguideline documents being produced by the Microsoft. (20 printed pages)

    Download the Pet Shop 3.0 Installer.msi code sample .

    Contents

    Abstract What is the Java Pet Store? Microsoft .NET Pet Shop Business Requirements Application Data Model .NET Pet Shop 2.0 Architecture .NET Pet Shop 3.0 Architecture Conclusions Appendix A: Changes between Versions 2 and 3

    A b s t r a c t

    The purpose of the original .NET Pet Shop study was to take Sun's primary J2EE blueprintapplication, the Sun Java Pet Store, and implement the same application functionality with Microsoft.NET. Based on the .NET implementation of Sun's J2EE best-practice sample application, customerscan directly compare Microsoft's .NET technology to J2EE-based application servers across a varietyof fronts while learning about the similarities and differences in the recommended design patternsfor building Web-based applications. The .NET Pet Shop application is now in its third revision and isdesigned to show the .NET best practices for building enterprise n-tier applications which may needto support a variety of database platforms and deployment models. The .NET Pet Shop 3.0 has beenre-architected based on community feedback on the .Net Pet Shop 2.0 to comply with Microsoft'sPrescriptive Architecture Guidance as published on MSDN. The third revision is also fully compliantwith the Middleware Company Application Server Benchmark Specification, and will serve asMicrosoft's entry in the upcoming Middleware Application Server Benchmark this spring: a secondround of testing by the Middleware Company to compare the scalability of .NET and the J2EEplatforms for building and hosting enterprise Web applications.

    W h a t i s t h e J av a Pe t St o r e ?

    The Java Pet Store is a reference implementation of a distributed application according to the J2EEblueprints maintained by Sun. The sample application was originally created to help developers andarchitects understand how to use and leverage J2EE technologies, and how each of the J2EEplatform components fit together. The Java Pet Store demo includes documentation, full source codefor the Enterprise Java Beans (EJB) architecture, Java Server Pages (JSP) technology, tag libraries,

    1

    http://microsoft.com/downloads/details.aspx?familyid=e2930625-3c7a-49dc-8655-a8205813d6db&displaylang=enhttp://c/Documents%20and%20Settings/Administrator/Desktop/petsh_topic1#petsh_topic1http://c/Documents%20and%20Settings/Administrator/Desktop/petsh_topic2#petsh_topic2http://c/Documents%20and%20Settings/Administrator/Desktop/petsh_topic3#petsh_topic3http://c/Documents%20and%20Settings/Administrator/Desktop/petsh_topic4#petsh_topic4http://c/Documents%20and%20Settings/Administrator/Desktop/petsh_topic5#petsh_topic5http://c/Documents%20and%20Settings/Administrator/Desktop/petsh_topic6#petsh_topic6http://c/Documents%20and%20Settings/Administrator/Desktop/petsh_topic7#petsh_topic7http://c/Documents%20and%20Settings/Administrator/Desktop/petsh_topic8#petsh_topic8http://c/Documents%20and%20Settings/Administrator/Desktop/petsh_topic9#petsh_topic9http://c/Documents%20and%20Settings/Administrator/Desktop/petsh_topic9#petsh_topic9http://c/Documents%20and%20Settings/Administrator/Desktop/petsh_topic8#petsh_topic8http://c/Documents%20and%20Settings/Administrator/Desktop/petsh_topic7#petsh_topic7http://c/Documents%20and%20Settings/Administrator/Desktop/petsh_topic6#petsh_topic6http://c/Documents%20and%20Settings/Administrator/Desktop/petsh_topic5#petsh_topic5http://c/Documents%20and%20Settings/Administrator/Desktop/petsh_topic4#petsh_topic4http://c/Documents%20and%20Settings/Administrator/Desktop/petsh_topic3#petsh_topic3http://c/Documents%20and%20Settings/Administrator/Desktop/petsh_topic2#petsh_topic2http://c/Documents%20and%20Settings/Administrator/Desktop/petsh_topic1#petsh_topic1http://microsoft.com/downloads/details.aspx?familyid=e2930625-3c7a-49dc-8655-a8205813d6db&displaylang=en
  • 8/8/2019 Pet Shop 3.0

    2/18

    . NET Questionnaire

    and servlets that build the application. In addition, the Java Pet Store blueprint applicationdemonstrates certain models and design patterns through specific examples.

    The full Java Pet Store contains three sample applications:

    Java Pet Store : The main J2EE Blueprints application. Java Pet Store Administrator : The administrator module for the Java Pet Store. Blueprints Mailer : A mini-application that presents some of the J2EE Blueprints design

    guidelines in a smaller package.

    The original version of the Java Pet Store was designed to work with the following databases:Oracle, Sybase, and Cloudscape. IBM has created a DB2 port of the application. The application ispublicly available at the Java 2 Platform Enterprise Edition Blueprints . The premise of the mainapplication, the Java Pet Store, is an e-commerce application where you can buy pets online. Whenyou start the application you can browse and search for various types of pet from dogs to reptiles.

    A typical session using the Java Pet Store would be:

    Homepage This is the main page that loads when the user first starts the application.

    Category View There are five top-level categories: Fish, Dogs, Reptiles, Cats, and Birds. Eachcategory has several products associated to it. If we select Fish as the category, we might see"Angelfish" etc.

    Products If you now select a product the application will display all variants of the product.Typically the product variant is either male or female.

    Product Details Each product variant (represented as items) will have a detailed view thatdisplays the product description, a product image, price, and the quantity in stock.

    Shopping Cart This allows the user to manipulate the shopping cart (add, remove, and updateline items).

    Checkout The checkout page displays the shopping cart in a read-only view.

    Login R edirect When the user selects "Continue" on the checkout page, they are redirected tologin page if they have not signed in yet.

    Verify Sign I n After being authenticated onto the site, the user is then redirected to the creditcard and billing address form.

    Confirm Order The billing and the shipping addresses are displayed.

    Commit Order This is the final step in the order-processing pipeline. The order is now committed

    to the database at this point.

    2

    http://java.sun.com/j2ee/blueprints/index.htmlhttp://java.sun.com/j2ee/blueprints/index.html
  • 8/8/2019 Pet Shop 3.0

    3/18

    Provide data on how many users a typical, well-designed application can support whenimplemented in .NET and in J2EE.

    Figure 2. .NET Pet Shop

    The overall logical architecture of the .NET Pet Shop is given in Figure 3. The main focus of the

    design was to use ASP.NET Web Forms for the presentation tier which communicate to C# businesscomponents in a logical middle tier. In turn the business components access a back end databasethrough ADO.NET and a SQL Server helper class known as the Data Access Application Block (DAAB)

    . NET Questionnaire

    3

    Figure 1. Java P et Store

    Microsof t .NET Pe t Sho p

    The goal of the .NET Pet Shop was to focus solely on the Java Pet Store (the administration andmailer component were not implemented in .NET). In addition to reproducing the functionality of theJava Pet Store application, two additional objectives were added:

    Compare and contrast the code and code size of a real world, best-practice applicationbetween .NET and J2EE.

  • 8/8/2019 Pet Shop 3.0

    4/18

    . NET Questionnaire

    4

    for more information on the DAAB and to download the full DAAB source code. Data Access is fullyabstracted into a Data Access Layer (DAL), separate from the business logic layer (BLL). New withthe .NET Pet Shop 3.0, we have introduced a DAL layer for both Oracle 9i and SQL Server 2000databases. Class loading of the appropriate DAL layer occurs dynamically at runtime based on anapplication configuration setting in Web.Config. Note that .NET Pet Shop 3.0 uses two backenddatabases, and the order process involves a distributed transaction across these two databases.Using simple Web.Config application settings, users can deploy the .Net Pet Shop to work with singleor multiple backend databases, and can freely mix SQL Server and Oracle backend databases withthe distributed transaction handled by .NET Serviced Components using COM+ Enterprise Services.

    Figure 3. .NET P et Shop high-level logical architecture

    Figure 4 shows how the Microsoft .NET Pet Shop might be physically deployed. In this case inboundnetwork traffic is split between the two application servers using Network Load Balancing, NLB, orperhaps hardware load balancing. Once a network request has reached one of the machines in thecluster, then all the work for that request will be performed on that particular machine. The businesslogic and data access components will be installed as assemblies on both servers, which in essencewill be identical clones of one another. If the load-balancing software is configured to use "stickyIps," then each server can have its own session-state store, because a second request will beguaranteed to return to the server where the first request was fulfilled. For a more fault-tolerantsolution, the two application servers can share a common session-state store such as SQL Server ora dedicated session server (Not shown on diagram). The type and location of the session-state storeis determined by the values in the 'sessionState' child node of the 'system.web' element in the'web.config' file for each Web site.

  • 8/8/2019 Pet Shop 3.0

    5/18

  • 8/8/2019 Pet Shop 3.0

    6/18

    With version 2 of the .NET Pet Shop, the application was modified to create a scenario where adistributed transaction would be required to complete the order process. For the distributedtransaction scenario, the Orders, OrderStatus, and LineItem tables have been split off into aseparate database instance that could be installed on a separate machine. We have kept thisdistributed design pattern in the third version of the .NET Pet Shop.

    Figure 5. .NET P et Shop orders database sch ema

    . NET Questionnaire

    6

    Item Individual product details

    LineItem Order details

    Orders The orders placed by the customer. An order

    contains one or more line itemsOrderStatus Order status

    Product Catalog products, each product may have oneor more variants (Items). A typical variantmight be male or female.

    Profile Customer user profile

    Signon Login table for customers

    Supplier Information concerning fulfillment suppliers

  • 8/8/2019 Pet Shop 3.0

    7/18

    . NET Questionnaire

    Figure 6. .NET Pet Shop accou nts and products database schema

    Wh at Changes Could Be Made to the Pet Shop Table Design?

    There are some changes that could be made to the schema used in the application; however, wehave not made these changes in order to keep in line with the schema provided by the Java PetStore reference implementation. These changes are listed in table 2:

    Table 2. Pos sible improvements to the Pet Shop schema

    Change Reason

    Not storeHTML intables

    You may want to use different clientapplication types, hence by storing only animage file name, rather than an image tag, inthe database you can be more flexible withthe client type you can deploy

    Use a one-way Helps make the application more secure,because if any part of the system is

    7

  • 8/8/2019 Pet Shop 3.0

    8/18

    . NET Questionnaire

    encryptionalgorithmfor customerpasswords

    compromised it will still be difficult to read thepassword. Would require the facility to resetthe password to a new value.

    Encryptcredit cardinformation

    Prevent access to the credit card informationshould the system to compromised. Additionalchanges would be to make the table onlyaccessible with write permissions via a storedprocedure; hence a hacker would need toaccess the database via an alternative set of credentials to read the data.

    . N ET Pe t Sh o p 2 . 0 A r c h i t e c t u r e

    Figure 7. .NET Pet Shop 2 A pplication Architecture

    .NET Pet Shop 2.0 was designed to be deployed in a physical two-tier deployment and tookadvantage of this fact in the implementation of certain parts of the application. The applicationconsisted of a Web tier built with ASP.NET Web Forms which used "code-behind" to separate theapplication HTML from the user interface code. The middle tier contained business components tocontrol the application logic which talked to a SQL Server database through a customized version of

    the Microsoft Database Access Application Block (DAAB). To support distributed transactions, someof the middle tier business components were implemented using Enterprise Services. With Microsoft.NET this is the recommended way to support distributed transactions. However, not all classesextended the ServicedComponent class, as there is a performance overhead of implementing allclasses as Enterprise Serviced Components. When publishing the .NET Pet Shop 2.0, which was usedin the first Middleware Application Server benchmark, we received much feedback on optimizationsthat should be made to the architecture to make it more relevant to large-scale enterprises. Themajor areas of feedback included:

    Creating a completely abstracted data tier with no imports of data-specific classes in themiddle tier.

    Implementing a data access layer for Oracle that works transparently with the samebusiness and UI layers as the SQL Server version.

    Completely abstracting Web session state from the business logic and data layers such thatthe backend components of the application can be physically distributed onto separate computers

    8

  • 8/8/2019 Pet Shop 3.0

    9/18

    . NET Questionnaire

    from the Web server, or reused from other types of clients such as Windows-based clients vs.Webbased clients.

    Fully partitioning application modules into separate namespaces and physical assemblies. Additional feedback across a variety of fronts.

    . N ET Pe t Sh o p 3 . 0 A r c h i t e c t u r e

    Figure 8. .NET P et Shop 3.0 application architecture

    Application Areas

    Table 3. Application areas in the Pet Shop solution

    Area P urpose .NET I mplementation

    UserInterfaceComponents

    Capture data inputfrom the user anddisplay data returnedby the backendsystem. They alsohandle simplenavigation. Refer toUser InterfaceComponents.

    ASP.NET Web Forms,user controls, andserver controls. Theseconstructs allow forclean separationbetween designer HTMLand UI code such asevent handlers forbuttons

    UserInterfaceProcessing

    Controls usernavigation andprocess flows withbackend businessobjects. Also handlesmanagement of usersession data. Refersto User ProcessComponents.

    These are implementedas C# classes. Thesession statemanagement is handledby ASP.NET.

    Business Components that These are implemented

    9

  • 8/8/2019 Pet Shop 3.0

    10/18

    . NET Questionnaire

    Components

    implement thebusiness logic for anapplication

    as C# classes

    BusinessEntities

    Thin data classes forpassing databetween tiers of theapplication. Refer tobusiness entitycomponents.

    These are implementedas C# classes with eachfield exposed as aproperty. Each class ismarked as "serializable"to enable inter-processtransfer.

    Data AccessLayer

    Components

    Handle theinteraction with back

    end data stores,including databases,messaging systems,etc.

    These handle theinteraction with

    backend data stores,including databases,messaging systems,etc. Implemented asfour C# projects:

    A set of interfaceclasses for each dataaccess method wewant to expose.

    An implementationof the interfaces forSQL Server.

    An implementationof the interfaces forOracle 9i.

    A set of factoryclasses to load the

    correctimplementation,either SQL Server orOracle.

    Microsoft Visua l Studio .NET Solution

    Figure 9 shows the Microsoft Visual Studio .NET solution layout for the .NET Pet Shop application.Each element or tier of the application was given its own project to make the solution manage andclearly define where new classes used in the application should be placed or old ones can be found.

    10

  • 8/8/2019 Pet Shop 3.0

    11/18

    . NET Questionnaire

    Figure 9. Visual Studio .NET application solu tion

    The purpose of each project is listed in Table 4:

    Table 4. Visual Studio projects in the Pet Shop solu tion

    Project Purpose

    BLL Home for business logic componentsConfigTool Administration application used to encrypt

    connection strings and create event logsource

    DALFactory Classes used to determine which databaseaccess assembly to load

    IDAL Set of interfaces which need to beimplemented by each DAL implementation

    Model Thin data classes or business entities

    11

  • 8/8/2019 Pet Shop 3.0

    12/18

    . NET Questionnaire

    OracleDAL Oracle specific implementation of the PetShop DAL which uses the IDAL interfaces

    Post-Build Project to run post compile actions such asadding assemblies to the GAC or COM+

    Pre-Build Project to remove assemblies from the GACor unregister assemblies from COM+

    SQLServerDAL Microsoft SQL Server specificimplementation of the Pet Shop DAL whichuses the IDAL interfaces

    Utility Set of helper classes including a wrapper forthe DPAPI

    Web Web pages and controlsSolutionItems

    Miscellaneous items used to build theapplication such as Pet Shop.snk key fileused to sign application assemblies

    Database Portability

    One of the key requirements for this version of the Microsoft .NET Pet Shop was to provide animplementation of the application that supported both Oracle and SQL Server databases. Whendesigning the database access mechanism for the application, we had a choice as to which databaseproviders we should use; we could either use the generic OLE-DB managed provider or thedatabase-specific, performance-optimized .NET managed providers, such as the SQL Server andOracle managed providers provided with the .NET Framework 1.1. One of the key requirements forthe application was to create a high-performance solution, so we chose to build the application usingthe database-native .NET managed providers. For an analysis of the difference in performancebetween the managed providers and the generic OLE-DB providers, readers should refer to Using.NET Framework Data Provider for Oracle to Improve .NET Application Performance , which showsthat the vendor-specific providers can perform two to three times better than the equivalent OLE-DBprovider. The tradeoff that we made when choosing to go with a database-specific access class wasthat we would need to write a separate data access layer for each database platform we wanted tosupport and hence the application would contain more code. While the two data access layers sharemuch common code, each is clearly targeted for use with a specific database (Oracle or SQL Server2000).

    In order to simplify the use of the database access classe,s we elected to use the Factory DesignPattern as outlined by the GoF, with reflection being used to dynamically load the correct dataaccess objects at runtime. The factory is implemented as follows: a C# interface is created with amethod declared for each method that must be exposed by the database access classes. For eachdatabase that we want to support, we create a concrete class that implements the database specificcode to perform each of the operations in the interface or "contract." To support the runtimedetermination of which concrete class to load, we create a third class which is the factory itself andreads a value from configuration file to determine which assembly to load using reflection. With thereflection namespace in .NET, you can load a specific assembly and create an instance of an objectusing that assembly. To make the application more secure and provide improved support forversioning, we can add "evidence" about the assembly file to load in the application configurationfile, in this case, web.config. This means that the .NET Framework will only load the assembly thatwe have signed during compilation and has the correct version number. Figure 10 shows how thebusiness logic, factory, and databases access classes interact with each other. The key advantage of the solution built is that the database access class can be compiled after the business logic classesas long as the data access class implements the IDAL interfaces. This means that should we want to

    create a DB2 version of the application, we do not need to change the business logic tier (or UI tier).The steps to create a DB2 compatible version are:

    12

    http://msdn2.microsoft.com/en-us/library/ms973871.aspxhttp://msdn2.microsoft.com/en-us/library/ms973871.aspxhttp://msdn2.microsoft.com/en-us/library/ms973871.aspxhttp://msdn2.microsoft.com/en-us/library/ms973871.aspx
  • 8/8/2019 Pet Shop 3.0

    13/18

    . NET Questionnaire

    1. Create the database access classes for DB2 which implement the IDAL interfaces.2. Compile the DB2 access classes into an assembly.3. Test and deploy the new data assembly to a running server.4. Change the configuration file to point to the new database access classes.

    No changes or recompiles need to be performed on the business logic components.

    Figure 10. DAL factory implementation in .NET Pet Shop

    Stored procedures

    Normally we would recommend to customers that they use stored procedures to access tables in the

    database. There are several reasons for this:

    Stored procedures provide a clean mechanism to encapsulate queries. Changing a query can be done without changing the data access code. A DBA can easily see what SQL statements are being executed. Stored procedures are typically more secure, and it is easier to control database access. By using stored procedures you can avoid round trips to the client by issuing more than one

    request in the stored procedure. Stored procedures usually offer the best performance compared to middle-tier-generated

    SQL. Stored procedures offer an excellent way to encapsulate XML queries and XML input

    parameters.

    The disadvantage of stored procedures is they tend to be proprietary and are not portable acrossplatforms.

    However, to make the best use of the financial investment that you have made in your databasesoftware and hardware, developers will tend to optimize the SQL used in their applications for theirspecific database engine regardless of whether the SQL is in a stored procedure or generated in themiddle tier. A good example of this is generating unique numbers or identity numbers, as alldatabases support their own particular mechanisms for doing this, and so the SQL used to generatethe unique number tends to be specific to the database being used. There are always alternatives,but they do not perform as fast as the proprietary solutions.

    With the .NET Pet Shop we took the conscious decision not to use stored procedures in the

    application as this might be seen to be an unfair advantage for the .NET solution in the MiddlewareBenchmark. In reality the difference in performance is small because the application is relativelysimple and most of the SQL statement execution plans are cached in the database. However, for

    13

  • 8/8/2019 Pet Shop 3.0

    14/18

    . NET Questionnaire

    purposes of the Middleware Benchmark specification, which disallows the use of stored procedureseven to wrap simple SQL statements, the .NET Pet Shop 3.0 uses no stored procedures.

    Caching

    One of most effective ways to improve the performance of a database-driven applications is to

    eliminate accessing the database for every request. ASP.NET offers a variety of caching mechanismsthat boost performance in most applications. The two main ways to use caching in ASP.NET areoutput caching and data caching.

    .NET Caching Option s

    Page-level output caching takes the response from an ASP.NET Web page and stores the full page ina cache. The page cache is designed to work between the Web tier and the middle tier and cachesthe results/data of middle-tier methods, or the results of database calls in the case of two-tier apps.The first .NET Pet Shop distribution was offered in a page-level output-cached version and anoncached version. Version 3 only supports data caching but can easily be modified to supportoutput caching. With Windows Server 2003 and IIS 6.0, certain output cached pages (those withVaryByParm="none" and the directive to Cache 'Anywhere') can also be kernel-level cached, witheven faster access from Internet clients. Regardless, any output-cached page (kernel or nonkernelcached) is served extremely quickly by the Windows application server with much less resource(CPU) consumption, since no processing is actually occurring to recreate the page.

    ASP.NET Output Caching

    The original .NET Pet Shop application, version 1.5, also used a variation on page-level outputcaching, partial page caching or fragment caching to cache different regions of page. For instance,the header information that appears on the top of every page is cached. However, the headerinformation is dependent on the user signing in (so two different versions of the page have to becached). ASP.NET easily allows this by using the VaryByCustom attribute on the 'OutputCache'directive. Using VaryByCustom requires overriding the GetVaryByCustomString method to get acustom cache for the header.

    ASP.NET Data and Object Caching

    The object cache (Cache API) allows you to store the results of a method call or database query inthe internal caching engine with the .NET Framework. Since you have gone further through more of the application pipeline, the data cache may not offer the same performance boost that outputcaching yields, since HTML pages still must be dynamically constructed on each request. However, itdoes offer a good compromise between fully dynamic pages and reducing the load on the databaseby storing nonvolatile data in the middle tier. For example, you may want to display the same pieceof data differently in two Web pages, or use the cached objects or data differently in various pagesof the same application.

    ASP.NET Cache Monitoring

    There are several ways to monitor what is happening in the ASP.NET caching system. The foremostmethod is to use Perfmon but you can also use a SQL Server trace to check when database access isoccurring or not occurring as the case may be. To monitor the cache in Perfmon, select the OutputCache Entries and Cache API Entries counters under the ASP.NET Application performance objectand add them to the Perform graph. It is also possible to monitor the turnover rate and the hit ratewithin Perfmon to detect whether the item is being used in the cache.

    Table 5. Summary of caching option s in .NET

    Type of Caching

    Benefits Limitations

    OutputCaching Offers bestperformance Entire page output iscached

    14

  • 8/8/2019 Pet Shop 3.0

    15/18

    . NET Questionnaire

    FragmentCaching

    (Cache user

    controls)

    Simple toimplement. Entirepage output iscached

    Limited to timeinvalidation

    Cache API Different usercontrols on a pagecan have differentcache timeouts

    Cached controls canbe shared acrosspages. Need to cacheeach user controlindividually

    Pet Shop Middlew are Benchmark Caching Rules

    The Middleware Company has defined strict rules for the benchmark application as to what can be

    cached and how it can be cached. Basically, page-level output caching is disallowed, but middle-tierdata caching is allowed in certain places in the application. The following data was allowed to becached; it does not need to be refreshed from the database on each request: category information,product information, item information (excluding inventory data), and some account information. Interms of inventory data, the current quantity in stock should reflect an up-to-date value wheneveran item is added to the cart or a user navigates to the 'ItemDetails' page. For the accountinformation the username and password has to be validated on every single login attempt, and theaddress used for billing information should always be refreshed from the database to ensure that itis up to date during a checkout process. The implication of this is that the results for most productssearches and browse operations can be cached in the middle tier using a data/object cache set toexpire on a given interval.

    The second rule for the benchmark is that page level output caching should not be allowed; the webserver should always be required to recreate the rendered HTML for a page. The reason for this is to

    test the ability of the application servers to generate dynamic pages, not how fast the server couldpull HTML from a cache.

    Pet Shop 3.0 Caching Imp lementation

    For this version of the application, we used data caching in the code behind of the ASPX pages tocache the results of middle tier (business logic tier) requests. The following sample code shows howone would access the ASP.NET cache API to retrieve information from the cache. The example isbased on the category query, category.aspx.cs, in the Pet Shop application. In the Pet Shop a usercan select one of the five predefined categories of pet and view a list of animals in that category.The first thing the code does is to check to see if the data has already been cached by using thecategory id as a key to look up an element in the data cache. If this element does not exist, eitherbecause the data has not yet been cached, or the current cache has expired, it will return null. If theelement exists, the data from the cache is pulled and cast to the appropriate type. If the data is notin the cache, the middle tier is invoked to query for the data. The results from the middle tier queryare then added to the cache with an expiry time of 12 hours from now. Alternatively, we couldexpire the cached based on a fixed time of day, a dependency on another cache item, or bysupplying a callback function which could be used to clear the cache.

    Copy Code

    // Get the category from the query string string categoryKey =WebComponents.CleanString.InputText(Request["categoryId"],50); // Check to seeif the contents are in the Data Cache if(Cache[categoryKey] != null){ // If thedata is already cached, then used the cached copy products.DataSource =(IList)Cache[categoryKey]; }else{ // If the data is not cached, // then create anew products object and request the data Product product = new Product(); IListproductsByCategory = product.GetProductsByCategory(categoryKey); // Store theresults of the call in the Cache // and set the time out to 12 hoursCache.Add(categoryKey, productsByCategory, null, DateTime.Now.AddHours(12),Cache.NoSlidingExpiration , CacheItemPriority.High, null);

    15

    http://c/Documents%20and%20Settings/Administrator/Desktop/javascript:CopyCode('ctl00_LibFrame_ctl05');http://c/Documents%20and%20Settings/Administrator/Desktop/javascript:CopyCode('ctl00_LibFrame_ctl05');
  • 8/8/2019 Pet Shop 3.0

    16/18

    . NET Questionnaire products.DataSource = productsByCategory; } // Bind the data to the controlproducts.DataBind();

    Conc lus ions

    The architecture of the .NET Pet Shop has been enhanced to provide a more flexible solution interms of deployment options and the application is more readily customizable and adaptable to thechanges in business models. Despite all these changes, the performance of the Pet Shop hasremained roughly the same as the 2.0 implementation, and shows that the Microsoft .NETframework offers a viable alternative to J2EE for Enterprise solutions. Using the .NET Pet Shop andJ2EE Pet Store, architects and developers can compare .NET and J2EE side by side using functionallyidentical reference applications that illustrate best coding practices for each platform. The upcomingMiddleware Benchmark will test the new .NET Pet Shop 3.0 implementation to compare itsperformance to two new J2EE implementationsone based on CMP 2.0 and one based on a pureJSP/Servlet architecture with no EJBs. The testing will be conducted by the Middleware Companyand published on the ServerSide with a variety of J2EE application servers. A panel of J2EE expertshas been established and is overseeing this benchmark to ensure fairness across tested productsand adherence to specification/best practice for all implementations. In addition, the major J2EEapplication server vendors have been invited, along with Microsoft, to participate by commenting onthe specification, providing implementations to be tested, and being on site for tuning/optimizations

    and the testing process. Microsoft has opted to fully participate in this second round of testing.

    A p p e n d i x A : Ch a n g e s B et w e e n Ver s i o n s 2 a n d 3

    I tem Description Reason

    1 Created a databaseaccess layer (DAL).

    Allows clean separation of business logic from databaseaccess code, hence we canchange database vendor

    without changing the businesslogic code.

    2 Created a commonproject for all thindata classes(models).

    The model project only containsthin classes for holding dataand would be used in each tierof the application as a containerto transport data in. All themodel classes supportserialization through the

    [Serializable] tag to addimproved support for clusteringand any future changes wewant to make to physicaldeployment.

    3 Removed referencesto System.Web inComponents project.

    Good design practice as itallows middle-tier componentsto be used with different typesof UI.

    4 Changed some of The header and banner controls

    16

  • 8/8/2019 Pet Shop 3.0

    17/18

    . NET Questionnaire

    the custom servercontrols to Web usercontrols; howeverthe Pager control

    was left as a customserver control.

    contain a lot of HTML/UIcontent hence they are easierto maintain if they areimplemented as web user

    controls. The Pager controldeals with the manipulation of the query string and using datain viewstate, and so it is bettersuited being a custom servercontrol.

    5 Created animplementation of the DAL for Oracle.

    To support an Oracle databasewe created a specific OracleDAL that would take advantageof an Oracle specific driver

    6 The DAL layer nowimplements afactory [GoF] to loadthe appropriatevendor specific DAL.

    To hide which database we areusing on the back end, we usea Factory method to return aninterface to the DAL layer wewant to use.

    7 All public fields inthe model class

    were converted toproperties.

    This allows the field storagemechanism to be hidden and

    provides a good place to addbreak points in code if you wantto see what functions modifycertain data.

    8 Created a databaseaccess layer (DAL).

    Allowed clean separation of business logic from databaseaccess code, hence we canchange database vendorwithout changing the businesslogic code.

    9 Changed all staticmethods to instancemethods.

    Response to review feedback

    10 Fixed the versionnumber inassemblyinfo.cs to aspecific version to

    match deployment.

    Allows for specifying evidencewhen loading an assembly inthe DALFactory objects.

    11 Added pre- and This enables for running gacutil

    17

  • 8/8/2019 Pet Shop 3.0

    18/18

    . NET Questionnaire

    post-build steps tothe Visual Studio.NET solutions.

    and regsvcs utilities on certainassemblies once the project hasbeen compiled.

    12 Renamed orderbusinesscomponents basedon the function theyperform rather thantheir implementationmechanism.

    More intuitive for otherdevelopers to understand whatthe components do.

    13 Created aconfiguration tool to

    aid applicationsetup.

    The application event logsource needs to be created by a

    member of the administratorsgroup. The easiest way toensure that this was done wasto provide a simple tool to dothis that could be run postdeployment.

    14 Modified code toallow different DALsto be used for the

    accounts andproducts databaseand the ordersdatabase.

    Response to user request to beable to use a mixed-databasedeployment model.

    15 Page output cachingis added to thepages; however thiswill be removed forbenchmarks.

    Request of for demonstration of how the VaryByCustom functioncan be overridden to enablepages such as the header andbanner controls to be cachedwithin pages such asdefault.aspx.

    16 Added process flowcontrol classes toWeb application.

    Response to review feedback asit provides a single location tocontrol navigation and statemanagement for a Web domainsuch as accounts or shoppingcarts.

    18