You are on page 1of 13

ADO .NET Hints ADO .Net Architecture Ado.net object model consists of two fundamentals: .

.Net Data provider Data Set

A .Net Data Provider is generally composed of 4 main objects. Connection Command Data Reader DataSet

.Net Data data providers SQL Server .NET data provider Sqlserver 7 and above. System.data.sqlclient OLE DB .NET data provider - all OLE-DB complaint data source. System.data.oledb. sqlserver 6.5 or earlier. ODBC .NET data provider Oracle .Net Data provider

Storing Connection strings in a configuration file. .Net uses XML formatted text files for maintaining configuration information. File must be named as web.config. To use a .NET configuration file for a connections strings, you need to adda a new <add> element as a child of the <app settings> element for each connection string in the application.

Classes for accessing the configuration file can be found in the system. configuration namespace Connection Events State change is fired whenever the state of the connection changes from open to close or vice versa. Info Message is fired whenever .NET data provider sends a warning or an informational message to the client. Connection Pooling in the Data Providers It is the practice of keeping a permanent set of open database connections to be shared by sessions that use the same data source , avoiding the need to create and destroy connections at all time. Each connection pool is associated with the connection string. Command Property o CommandType. Text SQL statement o CommandType.Table Direct The name of a table whose columns will all be returned. o Commandtype.storedprocedure name of a stored procedure. Executing the command DATA READER Calling NextResultset() immediately on a newly returned data reader with multiple result sets skips the first result set. Accessing the data in a Typesafe manner: Eg dim Orderid as object = reader(orderId) Execute Non query executing operation that do not return resultset. Will be Insert, Update and delete) Execute Reader - returns a data reader object . Execute scalar returns an object representing the first column of the first row in the resultset. Returning aggregate values. Execute XML Reader() should contain an sql command with a valid FOR XML clause.

dim Orderdate as object = reader(orderDATE) best way use ordinals & correct data types is faster than using column name a s objects. dim Orderid as integer = reader.getint32(0) dim Orderdate as datetime = reader.getdatetime(1) if u r using sql server, use sql server types dim Orderid as sqlint32 = reader.getsql32(0) dim Orderdate as sqldatetime = reader.getsqldatetime(1) COMMONLY ENCOUNTED EXECEPTIONS Indexout ofBound -> when an attempt is made to access a column that doesnot exist in the data reader. InvalidoperationException : when an attempt is made to do something with an object that conflicts with its internal state. DBConcurrencyException : Dataadapter raises this by default if it detects inconstistent data during the update process.

DATA READER PERFORMANCE CONSIDERATIONS : 1. use Column ordinal rather than column name. 2. Use type safe access rather than type un safe. DATASET It is an in memory representation of a complete set of data including tables, relationships and constraints. It is a centerpiece of a disconnected , data driven application. Dataset object model : Dataset o Tables dataTable Columns Rows Constraints Relations Datarelations Extended properties

Merging Dataset Dataset.Merge(myotherdataset) Dataset.Merge(myotherdataset,true) preserves values of target dataset Dataset.Merge(myotherdataset,true, missing schemaaction.add) merging two data sets with different schemas.

Performance: DATA READER streams one record at time, there is performance gain over bringing all the records into a dataset. DATA READER cannot be cached. By caching DATASET, we are bringing more data into our application at once and reducing network traffic and database connection. Caching a DATASET is not always the best solution a

Namespace : system.web.caching.cache Eg Cache(cacheddataset) = mydataset Cache.add(cachedDataset,mydataset) Cache.Insert(cacheddataset, mydataset) <%@page inherits=cacheddatasetex src=cacheddatasetex.aspx.vb %> DATA ADAPTER It contains logic for updating data source as well as reading it. It provides the basic facilities for constructing a disconnected data access mechanism to fill dataset object and update s data source. It is a bridge between dataset and data source. Use dataset for more complex queries. Filling dataset object with just a few records, is to avoid lot of time for retrieving the records and filling the data set object.

Field Value Version :

Each field in a DATAROW object may have on of the following 3 value versions, which come from the system.data.datarowversion enumeration. Current The current value of the field. When the record is loaded from database, the version is identical to the original version but it can change over the course of an application. Original The value that was recently loaded from the database Propose The value to be assigned to the field as a result of the d current operation. Managing Concurrency There are two common models for dealing with concurrency control The pessimistic model The optimistic model

Pessimistic model is valid in ADO .net. This is useful in application such as an internal customer contact system, where you dont want your sales representatives to compete against other. If one sales rep is looking up a customer to prepare for a presentation, you dont want others to call the same customer at the same time. Optimistic model - 2 types First In wins In this strategy , the first update will be accepted, but subsequent requests to update the same data will be rejected. Last Man standing in this strategy, most recent update request always overwrites previous updates.

Points to remember. ADO Supports both pessimistic and optimistic. In ado, A recordset can use server side cursor and maintain connection to the database. ADO .NET Uses optimistic model. It Uses a more disconnected architecture. The only time u use a server side cursor with alive database connection is when you use a data reader to retrieve daa , because a datareader is forward only and read only, to read data doesnt require locking. The optimistic model is the natural choice. DataAdapters have built in support optimistic

concurrency management through the work of the command builder objects. Last man standing standing strategy can be performed by checking field value version (current , original & proposed) in the source code manually. ContinuUpdateOnError property to true , which instructs the data adapter to ignore the problematic record and carry on. Wherenever possible Strongly typed dataset should be used o Eg console.writeline(mydataset.customers(0).firstname)

Building Typed Dataset use graphical tool provided within Visual Studio .net use command line utilities and compiler arguments o xsd /d /l:vb bookdataset.xsd o vbc /r:system.dll /r:system.xml.dll /r:system.data.dll typedsetdem.vb bookdataset.vb

XML namespace provided by the Microsoft Codegen -> contains set of attributes that directly affect the code generation of a dataset. Msdata ->to control behaviour of a dataset. It concerned with definition, naming control of keys & constraints. TRANSACTION is a set of operations where all of the operations must be successful or all of them must fail to ensure consistency to correct behaviour within a system. Properties of Transaction : Atomicity : All the transaction should succeed or fail together. Consistency :the transaction takes the underlying database from one stable state to another. Isolation : one transaction should not affect any other transaction running at the same time. Durability : changes that occur during the transaction are permantely stored on some media.

Transaction can be split into 2 Local Transaction : single database holds all the data involved in a transaction. Distributed Transaction : spanning multiple transaction aware data resources, distributed transactions may need to read messages from message queue server , retrieve data from a sql server data base and write to other databases.

Transaction Model Manual : allows to use explicit instruction to begin and end the transaction, to control the transaction boundary. Automatic Transaction : If yr transaction span multiple transaction-aware resource manager (sql server, MSMQ, ) then this is the best option.

Transaction Vocabulary: Begin , Commit, Rollback

Transaction Class OLEDB, SQL Client , Oracle Client and ODBC Isolation level : Is a measure of the extent to which changes made outside transaction are visible inside that transaction. a

Dirty Read: a dirty read is a condition when a transaction reads data that has yet to be committed. Non-repeatable read : transaction A reads from a table. Transaction B alters or deletes the record and commit the changes. Now if Transaction A tries to re-read the record, it will be either be a different version or will not be available at all. Phantom read : Transaction A has some criteria for record selection. Transaction A say, 100 rows matching these criteria. Now transaction B inserts some rows that match the selection criteria of Transaction A. If transaction A rerun the query, it will receive different set of rows.

Possible Isolation levels in ADO.net Chaos

Readuncommitted Shared locks Readuncommitted Repeatable read Serializable Unspecified

Points to remember ADO.Net supports transactions Unnecessary use of transaction must cause performance penalties. Use transaction only when your operation requires one.

Transaction Techniques DBMS transaction need to code in Tsql ADO.Net Transaction easy to code COM+ Transaction transaction spans multiple transaction aware resource managers.

SQL AS keyword To map the short names to long name or some meaningful names for use in your application. The new mapping mechanism, introduce the objects by using mapping when filling the dataset. Difference between SQL method and the ADO.net method The mapping objects allow developers to manage dataset data and schemas that have been created using XML documents and XML schemas. SQL as keyword, we can use the aliased column names only when you deal with that database and records. DAL (DATA APPLICATION LAYER) It is one layer within an n-tier application that encapsulates data access. DAL is n-tier architecture.

Deploying DAL :

There are 2 categories of assemblies Private : located within an applications directory structure. /bin. Shared : used by multiple application. Located in Global Assembly cache (GAC). Global Assembly Cache : Is accessible from an ASP.net application, windows form application, a web service or any other application running on the machine. Components are located in a centralized location. Components are secure Side by side versioning. Before install a component into the GAC, assembly must be strongly named assembly.

Strong Name Utility : Sn.exe k <out path for snk file> Add an attribute to our assembly to use the specified file. This is done using the assemblykeyfile attribute class. <assembly:assemblykeyfile(path of snk file)> Put this code in the assemblyinfo.vb file & rebuild the assembly. Now ready to install the assembly in the GAC.

-k outfile

Generates a new key pair and writes it to a specified file -v assembly Verifies the strong name for an assembly -e assembly Extracts the public key from an assembly & stores it outfile in the specified file -? Display all command syntax for sn.exe

Gobal Assembly Cache Utility : gautil.exe This is used to manipulate the contents of the global assembly cache to install, uninstall and list assemblies. GAC is located at c:\winnt\assembly. Installs an assembly into the GAC Uninstalls an assembly from the GAC List the contents of the GAC

/I assembly /u assembly /l

/cdl /?

Deletes the contents of the download cache Display all commands.

Eg gacutil.exe I <path of dll > WEB SERVICES It exposes an interface for invoking a method on one system from another system through three protocols HTTP GET, HTTP PUT, and SOAP. Once the web service method is invoked, any data that needs to be returned is serialized as XML and returned, either as raw XML or as XML in the body of SOAP. Technologies used XML Extensible Markup Language When a web service method is invoked, the data returned, whether it is a string, an integer, a dataset or a custom object is serialized as XML and sent back to the consumer. Simple Object access Protocol Is an XML based message protocol. Web services can use SOAP as the carrier for the XML data that is being exchanged between the web service provider and web service consumer. Sterilized as XML in the SOAP message body. Web Service Description Language Is an XML based description of a web service. WSDL is contract that a provider and consumer agree on. WSDL describes the interface of a web service, how the messages are to be formatted when using HTTP GET, HTTP POST or SOAP protocols. Web service Discovery Is the process of locating the WSDL file associated to a web service. This process is used by tool Visual studio .Net Universal Description Discovery Is an industry effort to enable business to quickly , easily and dynamically find web services and interact with one another. UDDI community includes Microsoft, IBM, sun micro systems, Ariba and many others.

SOAP

WSDL

DISCO

UDDI

Web service work by exchanging data between two primary entities The web service provider

The web service consumer The provide application expose the WSDL that the consumer must comply with to use the web service. The consumer discovers the web service either by finding it in the UDDI registry or some other means of discovery. Once the consumer understands the web service via the WSDL document, a method can be invoked using any of the three protocols HTTP GET, HTTP POST, or SOAP. When the web service is invoked , the provider returns the data to the consumer in the form of an XML document either as a web response or embedded in a SOAP message. The data exchange can be protected either with SSL or by encrypting the XML payload. Namespace system.web.services.webservice. Methods that we are exposing as web service methods (using the webmethod()> attribute must be in a public class.

Eg vbc.exe /t:library xx.asmx.vb /r:system.dll, system.web.dll Protocols HTTP GET Advantages Easy to implement Disadvantages Any input values are passed in the query string Cannot exchange complex data types Easy to implement Cannot exchange complex data types Can exchange Uses more bandwidth complex data types

HTTP POST SOAP

Disco.exe /nosave http://localhost/p/x.asmx To view the project assembly in the Microsoft Intermediate Language Disassemble (ILDASM.exe) Proxy Client Is a local object that simulates the functionality of a remote object. Web Service security Windows authentication SOAP based authentication

Windows authentication: Use network credential class to provide password based authentication schemas such as basic, digest NTLM and Kerberos authentication. DiffGram : XML format to identify current and original version of data elements. Dataset uses diffgram. Security Concerns: The most common ways of securing an application involve either using the code access security (CAS) system or using an encryption schema or SSL (Secure Socket Layer) encryption for web sites. Administrator defines a set of code groups. Identifies all Assemblies whose zone is Intranet Identifies all Assemblies whose zone is Internet Identifies all Assemblies from the untrusted Zone Identifies all Assemblies from the Trusted Zone Identifies all Assemblies built with the Microsoft public key Identifies all Assemblies built with the ECMA public key. ECMA is a standard body that stands for the European Computer Manufacturers Association. Identifies all Assemblies residing on your computer

Code groups Local Intranet Zone Internet Zone Restricted _Zone Trusted Zone Microsoft_Strong_na me ECMA_strong_name

My_computer_zone Permission Sets Full Trust Skip verification Execution Nothing Local intranet

Gives complete and unrestricted access to all protected resources. Grants the matching code the right to bybass security verification Allows the code to execute Denies the code all rights, including the right to execute The default set of permissions granted to code on your local intranet

Internet Everything

The default set of permissions given to internet applications Allows complete unrestricted access to all resources that are governed by the built in permissions.

You might also like