1 / 29

Dr. Rathindra Sarathy

MSIS 5133 Advanced MIS - E-Commerce Spring 2003 Lecture 4: DotNet Technologies - Part 6 Developing Applications – Part 2. Dr. Rathindra Sarathy. Application Level Considerations. 2-tier vs. 3-tier – Making applications 3-tier Adding Reusable Components Transactions E-Commerce pipelining

Download Presentation

Dr. Rathindra Sarathy

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. MSIS 5133 Advanced MIS - E-CommerceSpring 2003Lecture 4: DotNet Technologies - Part 6Developing Applications – Part 2 Dr. Rathindra Sarathy

  2. Application Level Considerations • 2-tier vs. 3-tier – Making applications 3-tier • Adding Reusable Components • Transactions • E-Commerce pipelining • Transaction Servers and their roles

  3. Application-Level Considerations All the e-commerce applications must make use of the support offered by today’s technologies that support enterprise-level architectural considerations such as: • Transactioning • Performance (response-time) • Scalability • Reliability • Fault-tolerance • Reusability • Portability • Integration with existing systems • Security • Remote Systems Connectivity and others… This requires a knowledge of building 3-tier applications

  4. 2-tier and 3-tier construction • In a 2-tier construction, the web page contains all the logic to interact with a database. This may be appropriate for some applications (An admin page that interacts directly with a database for maintaining the database) but is inappropriate for situations where several transactions access the same database. • Problems include: • Difficult application maintenance when changes happen in business logic • Changes to database will involve changes to web pages • Difficult to transaction properly and therefore scaling issues arise • Poorer security and chances for rogue client to manipulate databases • Other issues?

  5. 3-Tier & N-tier Architectures Revisited

  6. What the layers do • The presentation services tier is responsible for: • Gathering information from the user. • Sending the user information to the business services for processing. • Receiving the results of the business services processing. • Presenting those results to the user. • The business services tier is responsible for: • Receiving input from the presentation tier. • Interacting with the data services to perform the business operations that the application was designed to automate (for example, income tax preparation, order processing, and so on). • Sending the processed results to the presentation tier. • The data services tier is responsible for the: • Storage of data. • Retrieval of data. • Maintenance of data. • Integrity of data.

  7. Some advantages of 3-tier architectures • Thin Client and multiple versions of interface • Reduces the danger of “rogue” clients directly manipulating the database • Reusable server components, which are easier to test • Change in storage strategy leaves other tiers unaffected • Business & data services on same server avoid network transmissions • Load balancing possible by shifting processing to other servers • Servers are more secure and trusted than clients • Allows for improved scalability, reliability and transactioning

  8. Making e-commerce applications 3-tier • Except where it is really appropriate (rare), remove all accesses to database from ASP.NET web pages in the presentation tier • Move any code dealing with business logic into reusable components (Create a separate component (VB or C# assembly) that will access the database. Ideally, this component should be a “stateless” object; i.e., it should have no “persistent” properties. • All web pages will only interact with this component (or objects) to access the database • This component (and all other components) will be activated on a JIT (Just In Time) basis, only when needed. Should be managed well in terms of instantiating and “killing”. Fortunately, can be done automatically too with transaction managers where appropriate, but programmer should still incorporate component management in their logic.

  9. Notify Supplr. Check S_Inv Ccard Auth. Request Supply Ship Goods Place Order Building Reusable .NET Assemblies • Visual Basic .NET allows you to create reusable, compiled components (.NET assemblies) that create objects, access databases, and return data • Any application consists of both web pages with a user interface as well as pages that do not have user interfaces. This is especially true of 3-tier applications. • A e-commerce application, for example, contains an order-processing pipleine as shown below. Some components have user interfaces, others do not. Confirm Order by e-mail Notify Supplier by e-mail of order Receive & Process Notif. Obtain Cust. Ccard Auth. Tell Supplier by e-mail to ship Receive & Process Notif.

  10. Creating a Visual Basic .NET Assembly Calling Products.vb from CatMenu.aspx Creating the Products.vb

  11. Transaction • A series of steps that must occur on an all-or-nothing basis. • Requires a sequence of actions, all of which must be completed, otherwise database will be inconsistent • Example: • Deduct from Account 1 • Add to Account 2 • If activity 2 fails for some reason, then whole transaction has to be “rolled-back” i.e., amount deducted from Account 1 must be “added back”. • If all steps are correctly carried out, transaction is committed; else, it is aborted and all previous steps are rolled back

  12. Properties of a Transaction • ACID – Set of Properties for a correctly behaving transaction • Atomicity: Either all of the steps are completed, or none at all • Consistent: The transaction must leave the databases and resources it uses in a valid state • Isolation: Each transaction must act independently of the other; the result of each are hidden (not available) until they are committed. • Durable: Once a transaction is committed, its effect must survive system shutdown or failure • What can be “transactioned” (participate in a transaction)? • Transactioning primarily applies to database access & updates; Anything that implements activities related to database access and updates such as objects, COM components, ASP.NET assemblies etc.

  13. Sample Transaction Code for OLeDB – Manual Transactioning OleDbTransaction Trans = Conn.BeginTransaction(IsolationLevel.ReadCommitted); cmd.Transaction = Trans; try { oReader = cmd.ExecuteReader(); oReader.Read(); dCurrBalance = oReader.GetDouble(0 ); oReader.Close(); if (dCurrBalance < Convert.ToDouble(txtAmt.Text)) { throw(new Exception("Insufficient funds for transfer")); } strSQL = "Update tblAccount set dbalance = dBalance - " + txtAmt.Text + " where AccNumber = '" + txtFrom.Text + "'"; cmd.CommandText=strSQL; cmd.ExecuteNonQuery(); strSQL = "Update tblAccount set dbalance = dBalance + " + txtAmt.Text + " where AccNumber = '" + txtTo.Text + "'"; cmd.CommandText = strSQL; cmd.ExecuteNonQuery(); Trans.Commit(); lbl.Text = "true"; } catch(Exception ex) { Trans.Rollback(); lbl.Text = "Error: " + ex.Message; } finally { Conn.Close(); } }

  14. Transactioning in SQL Server • In .NET Framework, you can define a transaction by using SqlTransaction class. After that, you can use its commit or rollback function to control transaction using BeginTransaction, Commit, and RollBack methods Dim oSqlTrans As SqlTransaction oSqlTrans = oConnection.BeginTransaction() oCommand.Transaction = oSqlTrans ‘ Perform several commands… e.g. oCommand.ExecuteNonQuery() oSqlTrans.Commit() ‘ Or oSqlTrans.Rollback() http://www.able-consulting.com/dotnet/ado/adonet101_files/frame.htm

  15. Transactioning in with SQLTransaction [Web Applicaion in C#] SqlConnection myConnection = new SqlConnection("Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI;"); myConnection.Open(); SqlTransaction myTrans = myConnection.BeginTransaction(); //New a transaction SqlCommand myCommand = new SqlCommand(); myCommand.Transaction = myTrans; try { myCommand.CommandText = "Update Address set location='23 rain street' where userid='0001'"; myCommand.ExecuteNonQuery(); myTrans.Commit(); Console.WriteLine("Record is updated."); } catch(Exception e) { myTrans.Rollback(); Console.WriteLine(e.ToString()); Console.WriteLine("Sorry, Record can not be updated."); } finally { myConnection.Close();}

  16. Notify Supplier Check S_Inv Ccard Auth. Request Supply Ship Goods Place Order Pipelining of Activities in E-Commerce Applications • Pipelining is equivalent to transactioning over several related activities carried out by many components • Example: • Order Processing Pipeline Confirm Order by e-mail Notify Supplier by e-mail of order Receive & Process Notif. Obtain Cust. Ccard Auth. Tell Supplier by e-mail to ship Receive & Process Notif.

  17. Characteristics of the Pipeline • Each piece of the pipeline, called connector, may consist of one or more transactioned components. • The whole pipeline is also considered a transaction • An order may be in process anywhere in the pipeline • At each connector, we need a YES or NO decision • To move through the pipeline, an order may need external stimulus (for example, supplier confirmation of inventory, Credit Card Authorization etc.) • Order may drop out of pipeline at any time (aborted transaction). Further down the pipeline, the more the number of rollbacks. • An audit trail is always maintained as the order moves through the pipeline, to know its status (includes successful commits as well as aborts)

  18. Role of pipeline in the overall architecture User Visit Start New Transaction Order Catalog Order Processor Audit Trail ASP ASP.NET JavaScript HTML DHTML XML Cart Customer Search Product DataBase Access Object CustServ Webdata XML Dept. Others.. Transaction Manager Presentation Data Business/Service

  19. Transaction Managers • Why do we need a “Transaction Manager?” • E-commerce applications use resources in the form of components, assemblies, objects and beans – For example, the order processing pipeline • When we use 3-tier architecture, thousands of users implies • Thousands of assemblies & components taking up memory Thousands of database connections constantly being acquired & released (such as ADO connection objects) • Normally, it is the responsibility of user code to release resources after use – but not good to completely rely on that • Enter…. • Transaction Managers - Take on the responsibility of transactioning, sequencing, pooling and releasing resources • MTS = Microsoft Transaction Server was an example of somewhat older technology – in COM+ it is in-built (COM+ is approx. = COM + MTS)

  20. How do you use the Transaction manager? • Manual Transactioning– Like we did earlier • Does NOT use transaction manager COM+ • A manual transaction allows you to explicitly begin a transaction, control each connection and resource enlistment within the transaction boundary, determine the outcome of the transaction (commit or abort), and end the transaction. Although this model offers measured control over a transaction, it lacks some of the ease built into the automatic transaction model. For example, there is no automatic enlistment and coordination between data stores in a manual transaction. Further, transactions do not flow from object to object, as is the case in automatic transactions. • If you choose to control a distributed transaction manually, you must manage recovery, concurrency, security, and integrity. In other words, you must apply all the programming techniques necessary to maintain the ACID Properties associated with transaction processing. • Automatic Transactioining • Use Page level directive • Use Class-level directives • Explicitly (manually) register the assemblies/applications in COM+. Need administrative privileges on the server

  21. Automatic Transactioning of an ASP.NET Page – page directive • ASP.NET transaction support consists of the ability to allow pages to participate in ongoing Microsoft .NET Framework transactions. • Transaction support is exposed via an @Transaction directive that indicates the desired level of support. • A transaction can be explicitly committed or aborted using static methods of the System.EnterpriseServices.ContextUtil class. Developers can explicitly call the SetComplete or SetAbort method to commit or abort an ongoing transaction. ' Try to do something crucial to transaction completing. If (Not DoSomeWork()) ContextUtil.SetAbort() End If} Required - The page requires a transaction. It runs in the context of an existing transaction, if one exists. If not, it starts one. RequiresNew - The page requires a transaction and a new transaction is started for each request. Supported - The page runs in the context of an existing transaction, if one exists. If not, it runs without a transaction. NotSupported - The page does not run within the scope of transactions. When a request is processed, its object context is created without a transaction, regardless of whether there is an active transaction.

  22. Automatic Transactioning using class-level directives http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconautomatictransactionsasp.asp Instances of a .NET Framework class can participate in an automatic transaction, as long as you prepare the class to do so. Each resource accessed by a class instance, or object, enlists in the transaction. For example, if an object uses ADO.NET to post money on an account in a database, the resource manager for the database determines whether the object should execute in a transaction. If so, it automatically enlists the database in the transaction. Use the following process to prepare a class to participate in an automatic transaction: • Apply the TransactionAttribute to your class. • Derive your class from the ServicedComponent Class. <Transaction(TransactionOption.Required)> Public Class Bar Inherits ServicedComponent '. . . End Class • Sign the assembly with a strong name. To sign the assembly using attributes create a key pair using the Sn.exe utility. sn -k TestApp.snk • Add the AssemblyKeyFileAttribute or AssemblyKeyNameAttribute assembly attribute specifying the name of the file containing the key pair to sign the assembly with a strong name. [Visual Basic] <assembly: AssemblyKeyFileAttribute("TestApp.snk")> • Register the assembly that contains your class with the COM+ catalog. If the client calling instances of your class is managed by the common language runtime, the registration is performed for you. However, if you anticipate that an unmanaged caller may create and call instances of your class, use the .NET Services Installation Tool (Regsvcs.exe) to perform the registration manually.

  23. Automatic Transactioning using class-level directives Public Class client Public Shared Sub Main() Dim accountX As New Account() accountX.Debit(100) Environment.Exit(0) End Sub End Class [Visual Basic] ' ----------------------------------------------------------------- ' TestApp.vb ' Generate a Strong name: ' sn -k TestApp.snk ' Compile the code: ' vbc /target:exe /r:System.EnterpriseServices.dll TestApp.vb ' Run TestApp: ' start TestApp.exe ' ----------------------------------------------------------------- Option Explicit Option Strict Imports System Imports System.Runtime.CompilerServices Imports System.EnterpriseServices Imports System.Reflection 'Registration details. COM+ application name as it appears in the COM+ catalog. <assembly: ApplicationName("TestApp")> 'Strong name for assembly. <assembly: AssemblyKeyFileAttribute("TestApp.snk")> <Transaction(TransactionOption.Required)> Public Class Account Inherits ServicedComponent 'Provides SetComplete behavior in the absence of exceptions. <AutoComplete()> Public Sub Debit(amount As Integer) ' Do some database work. Any exception thrown here aborts the ' transaction; otherwise, transaction commits. End Sub End Class http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconautomatictransactionsasp.asp

  24. What else do Transaction Managers (like MTS/COM+) do? • Transaction Services (already seen) • Just In Time Activation • Deleting Unused Objects • Object Pooling Additionally, in COM+ (= COM + MTS) • Holding State • Component Queuing • Load Balancing • Security

  25. Just In Time Activation • When a client requests a server object, such as an ADO Command object (after being registered in MTS), MTS creates an object “look-alike” called “Context Wrapper” – no instance of the object (in this case ADO) is actually created. • When one of its methods is used by the client such as: • AddCommand.Execute nRows only then is an object (in this case AddCommand) actually created. • This is called “Just In Time” activation, and is carried out by an MTS DLL object called MTS Executive • Prevents bad clients from getting objects too early • Improves Scalability (Context Wrapper objects are much “lighter” than the actual objects being created, because they only implement the interfaces)

  26. Object Pooling • Having too many objects in memory is a strain on resources like memory and affect scalability adversely • On the other hand, creating and deleting objects constantly can be costly in terms of processing, again affecting scalability • Enter…Pooling (again, the objects have to be stateless) • Client A has used an object • Client B wants to use the same object but is not sure of its state • Transaction manager deactivates the object and places it in a pool, but does not actually “kill” it. • When Client B needs the same object, MTS uses it from the pool • The Transaction Manager decides when to delete unused objects

  27. ADO.NET Connection Pooling • Specify pooling characteristics in connecting string • Pooling is implicit, you automatically get it unless you disable it (default is pooling=true) • Always call Close with a pooled connection to release it back into the pool sConnString = "Data Source=(local);" & _ "Initial Catalog=NorthWind;" & _ "Trusted_Connection=Yes;" & _ "Pooling=True;" & _ "Min Pool Size=1;" & _ "Max Pool Size=50;" & _ "Connection Lifetime=30;" & _ "Connection Reset=True;" & _ "Enlist=True;" http://www.able-consulting.com/dotnet/ado/adonet101_files/frame.htm

  28. Name Default Description Connection Lifetime 0 When a connection is returned to the pool, its creation time is compared with the current time, and the connection is destroyed if that time span (in seconds) exceeds the value specified by connection lifetime. This is useful in clustered configurations to force load balancing between a running server and a server just brought online. A value of zero (0) will cause pooled connections to never time out. Connection Reset 'true' Determines whether the database connection is reset when being removed from the pool. Setting to false avoids making an additional server round-trip when obtaining a connection, but you must be aware that the connection state, such as database context, is not being reset. Enlist 'true' When true, the pooler automatically enlists the connection in the current transaction context of the creation thread if a transaction context exists. Max Pool Size 100 The maximum number of connections allowed in the pool. Min Pool Size 0 The minimum number of connections maintained in the pool. Pooling 'true' When true, the SQLConnection object is drawn from the appropriate pool, or if necessary, created and added to the appropriate pool.

  29. Additional Transaction Management Features in COM+ • Uses Message Queuing when the database server is on a remote site – basically an update or a set of updates into a transactional message for a remote server. Your application gets a commit and goes on, and Message Queuing guarantees that the transaction will eventually be committed, even if network currently available (used to be done by MSMQ with MTS prior to COM+) • Load Balancing – Does load balancing at component level among multiple servers • Security – Role-based. You can assign different levels of security for different users for different methods, properties and interfaces within a single component.

More Related