When it comes to implementing transactions in applications, developers seem to do better job nowadays. Most of developers know what the drawbacks are of not using transactions when executing queries modifying data. I also see that more developers use TransactionScope class to make a code block transactional, but unfortunately I don’t see very often classes they build are created in the way that they could participate in transactions or rather take advantage of ambient transaction context, which is automatically managed by a resource manager, whoso actions are coordinated by a transaction manager. Resource managers work in cooperation with the transaction manager to provide the application with a guarantee of atomicity and isolation. Microsoft SQL Server, durable message queues, in-memory hash tables are all examples of resource managers. But I think everyone could find quite a few classes (or even more) that are resource managers but have not been designed to work in cooperation with the transaction manger, hence they can’t participate in ambient transactions and automatically commit changes when TransactionScope has completed or rollback changes when their operation or other participant’s operation has failed. And I think that’s the beauty of TransactionScope class and being managed by transaction manager that all operations are automatic so you don’t have to check if all operations have succeeded to invoke Commit or call Rollback when something failed as those operations are taken care of for you by the aforementioned transaction manager. But in order for a resource to participate in a transaction, it must enlist in the transaction. By enlisting, the resource manager ensures that it gets callbacks from the transaction manager when the transaction commits or aborts. A resource class is required to implement the following interfaces in order to be supported for enlistment: ISinglePhaseNotification and IEnlistmentNotification. Of course one could build a serviced component by inheriting from System.EnterpriseServices.ServicedComponent base class, but that would mean that your class is a COM+ component, which most of the time is not desirable, so ISinglePhaseNotification and IEnlistmentNotification interfaces are the way to go. So below is a simple application that calls some insert query (which is by default managed by transaction manager) and our class that puts some data in the file in the way that if either query or save to a file process has failed, both operations are rollbacked or in other words, the changes are persisted or committed only if both operations have succeeded. The application was created to demonstrate how to use the aforementioned interfaces, hence it's lacking locking or concurrancy detection mechanism but those can be added as required. The insert query I used is a simple insert statement to a table I created as below but it can be any table and any DML query.
[IRepository.cs]
[MSSQLProductRepository.cs]
[FileProductRepository.cs]
[Program.cs]
Personally I have to admit that I love those interfaces. They make building transaction-aware classes a very simple task. Not only does it help a developer in designig and building such classes, but also it simplifies writing code that consumes such classes in client applications as all commit or abort logic happens behind the scene and it is automatically managed for you by transaction manager upon instantiation of TransactionScope class. And having your class participate in ambient transactions is a guarantee of a data atomicity, consistency, isolation and durability, which is a guarantee that transactions are processed reliably, which should be a goal of every thriving software developer.
I truly believe that probably every developer has developed some application that had to work with files. Applications use files for logging, for storing data or for reading data. A few years ago it was more common to store data than it is nowadays. Now developers tend to store everything in a relational database, but nevertheless from time to time a developer has a file with some data that he or she needs to process. It might be a file with some macroeconomic data, or a file with data ready for migration, or a log file for analysis, etc. So most common approach when working with a text file is to write a console application that uses System.IO classes to read a file line by line and parse each line into columns and then proceed according to requirements. This solution is very powerful, yet any change requires recompiling a code and there is almost no reusability - you can't use your method that finds all names within a file that starts with "N" to also find a sum of all expenses within other file, so a developer ends up writing 2 separate methods. Of course, you can import that data into a database and run a SQL query to get your results but that's not always feasible - probably you wouldn't want to import huge log files to database to get a number of null argument exceptions in your application within a range of dates. All you need is a small app that will open a file, scan each log within a given date range, find all argument null exceptions and make a count. You don't want to import the logs into a table and then probably apply some index and then finally run a select statement. Wouldn't it be ideal to be able to run the same select command against a text file without loading it to a database? And that's where data providers like ODBC and Microsoft OLE DB come in handy (working with those providers by the way is one of the exam requirements). Let's do a simple application that will join data from two text files (1 with loan information and 1 with payments) and will show each loan account number with the sum of all payments and the output will be sorted ascending by total payment amount. Also we'll see how to output account numbers of delinquent loans with the date of their last payment. Please note that I put queries in app.config to avoid hard-coding them, but for simplicity I put them in appSettings section whereas normally you would want to create a custom config section in which you would define a query text, parameters, etc. The QueryProvider is a static class that helps reads information from the application configuration file, and class TextFileQuerer is the class that queries the text files and outputs the information as specified.
Text files:

[App.config]
[QueryProvider.cs]
[TextFileQuerer.cs]
[Program.cs]
Here is the application in action:

And it outputs what we wanted with only a few lines of code and using SQL commands that most developers are familiar with and without really hard-coding the logic and without putting a lot of code that would take a line and parse it into columns and track column names and types, etc. Really flexible and powerful solution. I used OleDb but we could also use ODBC provider. Unfortunately, there are some limitations of this solution (or rather the aforementioned text file query providers) like JOIN keyword is not being recognized so you can't do LEFT JOIN. However, for many text-file based operations the text file query providers can provide a very quick and flexible solution that will allow to save a lot of time spent on parsing, writing objects to hold temporary results, hardcoding logic, etc. I will the best way to see the power of text file query providers would be by trying to write the SumOfAllPayments method without using the query, and comparing the total amount of time spent on writing both solutions.
70-561 - Optimistic concurrency in the Entity Framework
In the previous post I wrote about optimistic concurrency control (OCC) and about the obvious benefits of using one in your application (although there's still a bunch of developers who don't seem to see those benefits). And I also presented an example of an application that uses LINQ to SQL as OR/M and how to implement optimistic concurrency using out of the box concurrency conflict resolutions. But that mechanism is only available when using LINQ to SQL in your application, and since of .NET 4.0 the Entity Framework is recommended data access solution for LINQ to relational scenarios (Update on LINQ to SQL and LINQ to Entities Roadmap), I decided to demonstrate how the same example would look like when using the Entity Framework instead of LINQ to SQL. So below is our Address entity:
[Address.cs]
[AdventureWorksLTEntities]
[Program]
When I first compared the mechanism of resolving concurrency conflicts within the Entity Framework and LINQ to SQL, I thought that now it couldn't be simpler. In Entity Framework all you do is to decided whether you want to keep your changes or keep someone else's changes, which you do by selecting an appropriate refresh mode, which by the way are very descriptive and in my opinion less confusing that it took place in LINQ to SQL, as you choose whether ClientWins or StoreWins. Could it be simpler?! One additional remark - To ensure that objects on the client have been updated by data source-side logic, you can call the Refresh method with the StoreWins value after you call SaveChanges. The SaveChanges method operates within a transaction. SaveChanges will roll back that transaction and throw an exception if any of the dirty ObjectStateEntry objects cannot be persisted. I really hope that more developers will grasp the benefits of having in their application a mechanism of resolving concurrency conflicts - especially if they have decided to use the Entity Framework for object-relational mapping in their projects. And as far as the 70-561 exam, I hope if there's a question on optimistic concurrency in the Entity Framework, you will know the correct answer, but what's more important is to know the correct answer when working with real life projects.
Optimistic concurrency control (OCC) is a concurrency control method that assumes that multiple transactions can complete without affecting each other, and that therefore transactions can proceed without locking the data resources that they affect. Before committing, each transaction verifies that no other transaction has modified its data. If the check reveals conflicting modifications, the committing transaction either rolls back or user manually resolves the conflict by deciding if what changes should be discarded and what changes should be kept. It seems that all production systems should use transactions and have some sort of concurrency control mechanism implemented. However, I have seen a few systems in productions (even fairly recent) that did not have any concurrency control, which was causing a lot of troubles only because someone decided that 2 people would not use the same data, which the assumption, sooner or later, is almost always proven wrong and cost of implementing a concurrency control first place would've been always lower than the cost of fixing the problems in production. Moreover, implementing OCC is very straightforward and really shouldn't take much time. That's why I decided to demonstrate how one can take advantage of optimistic concurrency in LINQ to SQL.
LINQ to SQL has a built-in detection mechanism of optimistic concurrency. When submitting changes, ChangeConflictException is thrown when a conflict has been detected and each conflict can be resolved using Resolve method in ObjectChangeConflict class. Below is a very simple example that uses LINQ to SQL to map Address table in AdventureWorksLT database, but any database and any tables can be used.
[Address.cs]
[AdventureWorksLTDataContext.cs]
[Program.cs]
The main logic of resolving the concurrency conflict has been implemented within partial class AdventureWorksLTDataContext, which class is the LINQ to SQL DataContext class, in Save method that calls SubmitChanges method to submit the changes and also checks for ChangeConflictException and provides the code to resolve the conflict. An important thing about Save method is that it contains a recursive call, which is required because after user has chosen the mode of resolving each conflict, the changes must be submitted again to the database, which can again cause the concurrency conflict. Recursion could also be replaced with do ... while loop. Also I took advantage of the fact that data context class in LINQ to SQL is a partial class so Save method that allows user resolve the concurrency conflict I added to the partial class I created with the same name as my data context, but I could use extension method or other helper class.
Below are the results of resolving the conflicts using all three different refresh modes, of which understanding is required to properly resolve the conflict.
So for example, both users start with the same address (AddressLine1=Line1, AddressLine2=Line2, City=City) and User2 made changes in AddressLine2 and City (Line2 by User 2 and City by User 2 ) and commits his changes. Next, User 1 tries to submit his changes, which touch AddressLine1 and City (Line 1 by User 1 and City by user 1). Each of them made changes in 2 properties in the Address entity - 1 different (AddressLine1 and AddressLine2) and 1 the same (City). During submitting changes of User1, a concurrency exception is thrown and as depicted by the chart if user selects RefreshModel.KeepChanges, Address entity will contain all changes of User 1 plus the changes of User 2 that were not overwritten by User 1, which means changes in AddressLine2.
As one can see, implementing optimistic concurrency in LINQ to SQL is fairly simple and shouldn't cost a developer a lot of time and there's definitely a lot of benefits of being able not only to detect a concurrency conflict but also to be able to provide a user a mechanism to resolve it in the most adequate fashion in oder to fully meet business requirements regarding change conflicts. I think everyone agrees that every application should be implemented to be able to resolve concurrency conflicts and maybe not only by showing an error message of a change conflict and refreshing data (and aborting some of the changes made by a user) but also by providing a granular mechanism to present a user the changes that happened in the meantime and prompt how to resolve each change. I think I will never forget one of the applications that did not have a concurrency mechanism implemented and a person who claimed that he entered some data to the system (it was even confirmed with the message "Update successful") but they were gone because someone else made his changes in the meantime and as a result no records were updated, but that was never detected and never presented to the user. I know only one - it took a while to find that bug and even more to implement it in that enterprise application (hundreds of thousands lines of code). So any developer that cares about Quality of Service should remember that simple and small things like that make your application robust and make you a thriving developer.
One of the abilities being checked on the 70-561 exam is the ability of handling special data types: Binary Large Objects (BLOBs), Filestream, Spatial, Table Value Parameters. From my experience I can tell that developers more of less are familiar with Large Objects whether it's BLOB (Varbinary (Max)) or CLOB (Varchar(Max)). But filestream, spatial (comprehensive support for geography and geometry) and table value parameters are new features of Microsoft SQL 2008, and as such they're still fairly new for most .NET developers. And if to look closely at those new features, they can very useful for all developers working with MS SQL 2008 database. Below are the links to the information on those new features from the SQL Server 2008 perspective.
[Database script]
The script creates a database with 3 tables - TABLE_FS will be used to demonstrate filestream by inserting a photo; TABLE_SPATIAL will be used to demonstrate spatial types - geography and geometry; USERS will be used to store username and hashed password to demonstrate using table type parameters.
[Reading Filestream]
[Writing Filestream]
[Reading Spatial]
[Writing Spatial]
[Testing table type parameters]
After having looked at the code, you can notice that there's a few things a developer needs to remember when using the aforementioned special data types. For example, table with filestream requires column with uniqueidentified type and also reading and writing data to filestream requires a transaction context. If you go to a filestream folder, you will see there files - without extensions. If you copy it and change extension, you will get an identical copy of the file you wrote to database. As far as spatial types, I used a linestring object, which represents a line connecting a sequence of points, and function STLength to demonstrate diffrences of the line in geography and geometry realm. Table type parameter was used within user defined function that checked if given username and password are correct by comparing it with the records in USER table. It uses DataTable to store records to pass to the function. Password is hashed with salt using private key and SHA512 algorithm. So there is not really a lot to remember or a lot of new things a developer have to learn - most of them are straightforward, however there are few important things that you have to remember like using transaction context, uniqueidentifier column, or using BinaryReader to get a value from a stream of a spatial data type column, but I don't think this topic now will be a killer on the exam.
When I was writing a post about error handling when working with SqlClient, I wrote that OracleClient is not as rich as SqlClient when it comes to getting information about database exceptions. But then I realized that you can get the same functionality if you switch from built-in System.Data.OracleClient to Oracle.DataAccess.Client, which is the Oracle Data Provider for .NET (ODP.NET). It can be downloaded from the following Oracle Technology Network Web Site. One thing you need to be aware is that the installation comes with the Oracle database client, so any connection to Oracle database will be done by this client, therefore you need to remember to update tnsnames.ora file to point to the right host and database instance. This ODP.NET greatly enhances capability of Oracle Client - mostly by bringing support for Oracle bulk copy operations and array binding - plus having aforementioned additional parameters in OracleException class (OracleError collection similar to SqlError collection in SqlException class) . This functionality even outweighs SqlClient due to the fact of having array binding, which allows in one server round trip to execute a command (ie. update, insert, delete or stored proc) as many times as value of ArrayBindCount parameter in OracleCommand class. This feature allows controlling batch size and enhancing the speed as the array of row data is copied into SQL engine. Usually when a developer has to run ie. delete command against a few rows, he would take all PK ids of rows to delete and run in a loop single delete commands passing one by one all ids as a value of a parameter, which would cause n database round trips. Or he would implement PL/SQL stored proc to accept a table as an input parameter and then withing the stored proc a delete statement would be executed in some sort of loop to delete each single row with the given id. ODP.NET has made it simpler - all you need is 1 (!) DML command with parameter(s) and you need to pass an array of values. Simple and very efficient. As far as Oracle bulk copy, this is done using OracleBulkCopy class that is an equivalent of SqlBulkCopy class in SqlCleint. It also accepts as a parameter Data Reader or DataTable, so you can bulk copy data to a destination table. Below is simple console app that demonstrates how to use 2 features of ODP.NET - OracleBulkCopy class and array binding. The application uses Scott username to connect to database and also it uses EMP table from Scott schema and also EMP_TEST table which is a copy of EMP table needed to demonstrate Oracle bulk copy and created by running the following command (using where clause ensures that a created table will be empty):
The application below will copy all records from original table EMP to the created copy EMP_TEST using bulk copy. Next, it gets id of all employees and it returns all ids as an array. Next, it uses array binding to delete all employees with id from the array, which will delete all records copied first place with OracleBulkCopy.
ODP.NET.cs
using System;using System.Collections.Generic;using System.Linq;using Oracle.DataAccess.Client;namespace ODP{public class OdpNet
{public String ConnectionString { get; set; }public OdpNet(String connectionString){if (connectionString == null) throw new ArgumentNullException("connectionString");
ConnectionString = connectionString;
}
public void OracleBulkCopy_Test()
{try{using (var conn = new OracleConnection(ConnectionString))
{using (var cmd = conn.CreateCommand()){cmd.CommandText = "select * from Scott.EMP";conn.Open();
using (var reader = cmd.ExecuteReader()){if (reader.HasRows){using (var cpy = new OracleBulkCopy(conn))
{cpy.DestinationTableName = "Scott.EMP_TEST";cpy.WriteToServer(reader);
Console.WriteLine("Copying to EMP_TEST successfull");}
}
}
}
}
}
catch (OracleException ex){Console.WriteLine("Oracle error while copying to EMP_TEST: " + ex.Message);}
catch (Exception ex){Console.WriteLine("General error while copying to EMP_TEST: " + ex.Message);}
}
public Int32[] GetEmployeesId(){try{using (var conn = new OracleConnection(ConnectionString))
{using (var cmd = conn.CreateCommand()){cmd.CommandText = "Select EmpNo From Scott.EMP_TEST";conn.Open();
ICollection<int> empId = new List<int>();
using (var reader = cmd.ExecuteReader()){while (reader.Read())empId.Add(reader.GetInt32(0));
}
Console.WriteLine("Getting employee numbers successfull. Total found {0}",empId.Count());return empId.ToArray();}
}
}
catch (OracleException ex){Console.WriteLine("Oracle error while getting all employee numbers: " + ex.Message);}
catch (Exception ex){Console.WriteLine("General error while getting all employee numbers: " + ex.Message);}
return null;
}
public void OracleBindArray_Test(Int32[] employeesId)
{if (employeesId != null && employeesId.Length > 0)
{try{using (var conn = new OracleConnection(ConnectionString))
{using (var cmd = conn.CreateCommand()){cmd.CommandText = "Delete Scott.EMP_TEST Where empno=:1";cmd.ArrayBindCount = employeesId.Length;
var paramEmpno = new OracleParameter{OracleDbType = OracleDbType.Int32,
Value = employeesId
};
cmd.Parameters.Add(paramEmpno);
conn.Open();
var count = cmd.ExecuteNonQuery();
Console.WriteLine("Total employees deleted: {0}", count);}
}
}
catch (OracleException ex){Console.WriteLine("Oracle error while deleting employees: " + ex.Message);}
catch (Exception ex){Console.WriteLine("General error while deleting employees: " + ex.Message);}
}
}
}
}
Program.cs
using System;namespace ODP{class Program{const String ConnectionString = "Data Source = orcl; User ID = scott; Password= tiger;";
static void Main()
{var client = new OdpNet(ConnectionString);client.OracleBulkCopy_Test();
var empId = client.GetEmployeesId();
if (empId == null)
Console.WriteLine("No employees found");elseclient.OracleBindArray_Test(empId);
Console.Read();
}
}
}
The application outputs as follows:
Because the applications I develop work with large databases (i.e. 1 table has 4 billion records) and most databases are Oracle, I always use ODP.NET (Oracle.DataAccess.Client) and I found it more powerful and more efficient than System.Data.OracleClient. I especially like OracleBulkCopy class that allows me to import very quickly large amount of data to a table from DataReader or DataTable. Especially from DataTable, which is very commonly used in .NET applications, as without OracleBulkCopy class a developer would have to either stream data to a file and use sqlloader to import it very quickly or set up OracleDataAdapter class and specify SelectCommand and InsertCommand which wouldn't be as efficient as bulk copy or finally just loop through all rows of DataTable and execute insert query for each of them, which would be a total peformance killer. So as a thriving developer who works with Oracle on a daily basis I would recommend using ODP.NET than a built-in OracleClient provider.
Ability to manage exceptions when selecting or updating data is very crucial from the data integrity standpoint. One could say that it is a very well understood problem and one could hardly find any production application that would not have better or worse exception handling when selecting or updating data when working with databases - whether it's SQL Server, Oracle, DB2 or other database. From my experience I can tell that developers do a pretty good job with catching exceptions as they know that any caught and logged error can help them find the problem and possible eliminate it. But one thing I have noticed is that not many .NET developers have a thorough understanding of databases - they can create tables, views, stored proc but when it comes to understanding a database architecture and its engine, they usually leave it to database administrators. Therefore, I common thing I have noticed is that not many .NET applications that work with Microsoft SQL Server database have been implemented to take a full advantage of error handling mechanism that Microsoft SQL Server offers. I remember a few applications that would catch only System.Exception totally forgetting that there was System.Data.SqlClient.SqlException class that offers a lot more than just a message, so this post is dedicated to that class - probably because almost all .NET developers have worked or work with SQL Server database (especially ASP.NET developers) and that exception classes of other database providers have less to offer, hence their classes are less richer than SqlException class. Below is the diagram of the SqlException class with the new properties in that class, therefore without those inherited from System.Data.Common.DbException class, plus a chart with description of each property.
Raising an error with severity 0 - 10 will not be caught by try... catch clause in the calling application, so to "catch" those errors (informations) one must subscribe to SqlConnection.InfoMessage event. This allows to get a list of info messages (errors) and it will not stop executing the query. Errors with severity 11 - 16 will be caught by try... catch clause and returned as an SqlException, which will stop the query execution. However, this behavior can be overridden by setting SqlConnection.FireInfoMessageEventOnUserErrors property to true, which will not stop executing the query and and will get a list of errors within a method subscribed to InfoMessage event. Query execution will be stopped, even if FireInfoMessageEventOnUserErrors is true, if a raised error severity is more than 19, and the interesting thing is to see that severity of errors reported within a method handling InfoMessage event are differrent than the errors reported by SqlException (ie. severity is 16 wheras an error was raised with severity 24), even though they are triggered by the same error. I have to admit that personally I haven't met a developer that was aware of that fact, even though InfoMessage event has been part of SqlConnection class since .NET 1.1. Below is a simple console app that presents SqlException class aling with SqlConnection.InfoMessage event in action.
using System;using System.Data.SqlClient;namespace SqlErrorTester{class Program{static void Main(string[] args)
{Test_Severity_10();
Test_Severity_16();
Test_Severity_16_With_InfoMessage();
Test_Severity_24();
Console.Read();
}
static String ConnectionString{get
{SqlConnectionStringBuilder cb = new SqlConnectionStringBuilder();cb.DataSource = ".";cb.InitialCatalog = "AdventureWorksLT";cb.IntegratedSecurity = true;return cb.ConnectionString;}
}
static void conn_InfoMessage(object sender, SqlInfoMessageEventArgs e)
{Console.WriteLine("Info Message received: " + e.Message);foreach (SqlError er in e.Errors)
Console.WriteLine("SqlError: Severity: {0} Message: {1}", er.Class, er.Message);}
static void Test_Severity_10()
{Console.WriteLine("TEST SEVERITY 10");using (var conn = new SqlConnection(ConnectionString))
{using (var cmd = conn.CreateCommand()){conn.FireInfoMessageEventOnUserErrors = true;conn.InfoMessage += new SqlInfoMessageEventHandler(conn_InfoMessage);cmd.CommandText = "RAISERROR('my custom error message',10,1);select getdate();";try{conn.Open();
Object date = cmd.ExecuteScalar();
if (date != null)
Console.WriteLine("Date on server: " + date.ToString());elseConsole.WriteLine("Date on server not found");}
catch (SqlException ex){Console.WriteLine("SqlException: " + ex.Message);foreach (SqlError er in ex.Errors)
Console.WriteLine("SqlError: Severity: {0} Message: {1}", er.Class, er.Message);}
catch (Exception ex){Console.WriteLine("Exception: " + ex.Message);}
}
}
}
static void Test_Severity_16()
{Console.WriteLine("TEST SEVERITY 16");using (var conn = new SqlConnection(ConnectionString))
{using (var cmd = conn.CreateCommand()){conn.InfoMessage += new SqlInfoMessageEventHandler(conn_InfoMessage);cmd.CommandText = "RAISERROR('my custom error message',16,1);select getdate();";try{conn.Open();
Object date = cmd.ExecuteScalar();
if (date != null)
Console.WriteLine("Date on server: " + date.ToString());elseConsole.WriteLine("Date on server not found");}
catch (SqlException ex){Console.WriteLine("SqlException: " + ex.Message);foreach (SqlError er in ex.Errors)
Console.WriteLine("SqlError: Severity: {0} Message: {1}", er.Class, er.Message);}
catch (Exception ex){Console.WriteLine("Exception: " + ex.Message);}
}
}
}
static void Test_Severity_16_With_InfoMessage()
{Console.WriteLine("TEST SEVERITY 16 WITH INFO MESSAGE");using (var conn = new SqlConnection(ConnectionString))
{using (var cmd = conn.CreateCommand()){conn.FireInfoMessageEventOnUserErrors = true;conn.InfoMessage += new SqlInfoMessageEventHandler(conn_InfoMessage);cmd.CommandText = "RAISERROR('my custom error message',16,1);select getdate();";try{conn.Open();
Object date = cmd.ExecuteScalar();
if (date != null)
Console.WriteLine("Date on server: " + date.ToString());elseConsole.WriteLine("Date on server not found");}
catch (SqlException ex){Console.WriteLine("SqlException: " + ex.Message);foreach (SqlError er in ex.Errors)
Console.WriteLine("SqlError: Severity: {0} Message: {1}", er.Class, er.Message);}
catch (Exception ex){Console.WriteLine("Exception: " + ex.Message);}
}
}
}
static void Test_Severity_24()
{Console.WriteLine("TEST SEVERITY 24");using (var conn = new SqlConnection(ConnectionString))
{using (var cmd = conn.CreateCommand()){conn.FireInfoMessageEventOnUserErrors = true;conn.InfoMessage += new SqlInfoMessageEventHandler(conn_InfoMessage);cmd.CommandText = "RAISERROR('my custom error message',24,1) WITH LOG;select getdate();";try{conn.Open();
Object date = cmd.ExecuteScalar();
if (date != null)
Console.WriteLine("Date on server: " + date.ToString());elseConsole.WriteLine("Date on server not found");}
catch (SqlException ex){Console.WriteLine("SqlException: " + ex.Message);foreach (SqlError er in ex.Errors)
Console.WriteLine("SqlError: Severity: {0} Message: {1}", er.Class, er.Message);}
catch (Exception ex){Console.WriteLine("Exception: " + ex.Message);}
}
}
}
}
}
As one can see SqlException class is very powerful and contains a lot of valueable information used to trace the root of an error and hence provide a better response based on the error, since it's easier to check for a class number than parse exception message. I have seen a lot of developers build a custom exception class just to find out that the information they needed could be provided by out of the box SqlException class. Even if you use generic data access interfaces (System.Data.Common), it is still worth checking if a database exception is SqlException and take advantage of the information that this class offers, so your code can be debugged easier (more accurate information on errors) and so you don't really have to write extra code and so you can have more time to play golf.
One of the books I have bought to study for the 70-561 exams was Professional ADO.NET 3.5 with LINQ and the Entity Framework . Simply I wanted the book that would present in details LINQ To SQL and Entity Framework. The book was not cheap but that was probably the only one that included both. Unfortunately I can't say that I'm happy with the book. First of all, the title should be LINQ and the Entity Framework, not ADO.NET 3.5 with LINQ and the EF. Second, I bought this book to get more details on LINQ To SQL (I already have other book on LINQ), but LINQ To SQL takes only 40 pages and doesn't even mention ExecuteQuery method in DataContext class, so if you have any other book on LINQ, then don't buy this one. Definitely not for Entity Framework. In my opinion the book does pretty lousy job teaching EF, at least comparing to Programming Entity Framework book. The same price but at least you can be sure that you will get a complete picture of the Entity Framework presented in very good examples. And if you need a book on LINQ and EF, then buy Programming Entity Framework and Professional LINQ . Unfortunately Professional LINQ doesn't go into details on LINQ to SQL but you can very easily get that knowledge for free watching some online videos or reading ScottGu's Blog, or even check the following whitepaper on your computer (about which not many people are even aware of) C:\Program Files\Microsoft Visual Studio 9.0\Samples\1033\LinqSamples\WhitePapers\LINQ to SQL Overview CSharp and VB.doc (first you need to unzip CSharpSamples.zip). You will also find there a lot of good examples on LINQ and Lambda Expressions. Given the fact that there is a lot of free resources about LINQ, I wouldn't be that much disappointed about this book if it cost less than $20. It's definitely not worth $30. Although it has over 500 pages, it's only because of the large font and examples in both C# and VB.NET. Otherwise, there would be 300 pages. But the book could be very good if the author had added way more examples and explained topics using better examples (like Scott Guthrie does in his blog). "Professional ADO.NET" doesn't mean explained with fewer examples and using harder to understand language but rather presenting more details (like ExecuteQuery method).
Almost every application works with some sort of disconnected data and the vast majority of those applications use DataSet and DataTable objects. Selecting, searching and filtering data are the most common operations that are performed on those objects. And from my experience I can tell that even a junior developer can code those operations, so you might think that there's no point to bring up this topic, but I also know from my experience that even some senior developers don't know (or sometimes remember) that you can accomplish the same thing in several different ways. And if I hear word "several ways", I automatically think that you'd better know and understand all those ways because it's more likely that there will be some questions on the exam testing it. That's why I created the chart below to better remember the differences between different ways data can be filtered and searched in an untyped DataTable object.
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Data;namespace Search_Filter_ADO_NET{class Program{static DataTable Create_Person(){DataTable dt = new DataTable("Person");
dt.Columns.Add(new DataColumn("FirstName",typeof(string)));
dt.Columns.Add(new DataColumn("LastName",typeof(string)));
dt.Columns.Add(new DataColumn("Age",typeof(int)));
return dt;}
static void Populate_Person(DataTable dt)
{dt.Rows.Add("Will", "Smith", 35);
dt.Rows.Add("Jack", "Daniels", 40);
dt.Rows.Add("John", "Ripper", 34);
dt.Rows.Add("Alice", "Wonderland", 40);
dt.AcceptChanges();
}
static void DataTable_Select(DataTable dt)
{Console.WriteLine("Select results:");DataRow[] rows = dt.Select("Age<40"); foreach (var row in rows)
Console.WriteLine("First name: {0} Last name: {1} Age: {2}",row[0], row[1], row[2]);
}
static void DataRow_Find(DataTable dt)
{Console.WriteLine("Rows.Find results:");DataRow row = dt.Rows.Find("20"); if (row!=null)
Console.WriteLine("First name: {0} Last name: {1} Age: {2}",row[0], row[1], row[2]);
}
static void DataView_Find(DataTable dt)
{Console.WriteLine("DataView.Find results:");DataView view = dt.DefaultView;
view.Sort = "Age";int index = view.Find(40);if (index>-1)Console.WriteLine("First name: {0} Last name: {1} Age: {2}",view[index][0], view[index][1], view[index][2]);
}
static void DataView_FindRows(DataTable dt)
{Console.WriteLine("DataView.FindRows results:");DataView view = dt.DefaultView;
view.Sort="Age";DataRowView[] rowviews = view.FindRows(40);
foreach (var rowview in rowviews)
Console.WriteLine("First name: {0} Last name: {1} Age: {2}",rowview[0], rowview[1], rowview[2]);
}
static void DataView_RowFilter(DataTable dt)
{Console.WriteLine("DataView.RowFilter results:");DataView view = dt.DefaultView;
view.RowFilter = "Age<40";foreach (DataRowView row in view)
Console.WriteLine("First name: {0} Last name: {1} Age: {2}",row[0], row[1], row[2]);
}
static void DataTable_Lambda(DataTable dt)
{Console.WriteLine("DataTable.Lambda results:");var rows = dt.AsEnumerable().Where(p => p.Field<int>(2) > 34);foreach (var row in rows)
Console.WriteLine("First name: {0} Last name: {1} Age: {2}",row[0], row[1], row[2]);
}
static void DataTable_Linq(DataTable dt)
{Console.WriteLine("DataTable.Linq results:");var rows = from p in dt.AsEnumerable()where p.Field<int>(2) > 34
select p;
foreach (var row in rows)
Console.WriteLine("First name: {0} Last name: {1} Age: {2}",row[0], row[1], row[2]);
}
static void Main(string[] args)
{DataTable dtPerson = Create_Person();
Populate_Person(dtPerson);
DataTable_Select(dtPerson);
DataView_FindRows(dtPerson);
DataView_Find(dtPerson);
DataView_RowFilter(dtPerson);
DataTable_Lambda(dtPerson);
DataTable_Linq(dtPerson);
Console.Read();
}
}
}
While looking for some additional resources for studying to the exam, I came across a very good Microsoft webcasts on ADO.NET. Some of them talk about ADO.NET 2.0 but there's also a few that present ADO.NET 3.5 material (Sync Framework, Data Services, Entity Framework and applications for Microsoft SQL Server 2008). There is also a few MSDN virtual labs that help you get some work experience with those topics. And even though some web parts have been intended for ADO.NET 2.0 and they might seem to be outdated, they contain a great deal of information that's not obsolate and can be still very useful for eveyone who is studying to the exam. What I like about it is not only the fact that I can watch them as TV and learn at the same time, but that they present a lot of different aspects of ADO.NET, which normally to cover that material would require buying at least four books. I hope you'll enjoy them and you'll find them helpful for studying for the 70-561 exam.
- ADO.NET
- ADO.NET Step by Step (Part 01 of 16): Getting Started (Level 200)
- ADO.NET Step by Step (Part 02 of 16): Creating Connections (Level 200)
- ADO.NET Step by Step (Part 03 of 16): Data Commands and the DataReader (Level 200)
- ADO.NET Step by Step (Part 04 of 16): The DataAdapter (Level 200)
- ADO.NET Step by Step (Part 05 of 16): Transaction Processing (Level 200)
- ADO.NET Step by Step (Part 06 of 16): Modeling a Database by Using DataSets and DataRelations (Level 200)
- ADO.NET Step by Step (Part 07 of 16): Using DataTables (Level 200)
- ADO.NET Step by Step (Part 08 of 16): Using TableAdapters (Level 200)
- ADO.NET Step by Step (Part 09 of 16): Using DataViews (Level 200)
- ADO.NET Step by Step (Part 10 of 16): Editing and Updating Data (Level 200)
- ADO.NET Step by Step (Part 03 of 16): Data Commands and the DataReader (Level 200)
- ADO.NET Step by Step (Part 11 of 16): Data-Binding in Windows Forms with the BindingSource Class (Level 200)
- ADO.NET Step by Step (Part 12 of 16): Using ADO.NET in Windows Forms (Level 200)
- ADO.NET Step by Step (Part 14 of 16): Data-Bound and Validation Controls (Level 200)
- ADO.NET Step by Step (Part 15 of 16): Reading and Writing XML and the XmlDataDocument (Level 200)
- ADO.NET Step by Step (Part 16 of 16): Using ADO and ADOX in the .NET Framework (Level 200)
- Virtual Lab: Application Development for Microsoft SQL Server 2008: Let's Write Some Code! - After completing this lab you will be better able to create stored procedures with table-valued parameters, FileStream columns, Sparse columns, spatial columns and date/time columns, write ADO.NET code which uses table-valued parameters, FileStream, sparse columns, spatial types, and date and time columns.
- Sync Framework
- ADO Synchronization Services (Level 100)
- Optimizing Online, Enabling Offline with SQL Server Compact and Sync Services for ADO.NET (Level 200)
- Building Smart Client Applications Using Synchronization Services for ADO.NET (Level 200)
- Drill Down Into the Next Release of the Microsoft Sync Framework (Level 300)
- Data Services
- ADO.NET Data Services Overview (Part 1 of 2) (Level 100)
- ADO.NET Data Services Overview (Part 2 of 2) (Level 100)
- BenkoTIPS Live and On Demand: An introduction to ADO.NET Data Services (Level 200)
- Southern Fried Road Show Presents REST with ADO.NET Data Services (Level 200)
- ADO.NET Data Services for the Web (Level 200)
- Virtual Lab: Introduction to ADO.NET Data Services
- Entity Framework

_1101.png)












