70-433 - Table Value Constructor

Filed under: , , by:

Table Value Constructor is a new feature within SQL Server 2008, and also can be part of existing features like INSERT or MERGE, which allows for new syntax only available within T-SQL (maybe that's another reason I decided to write about TVC after having studied Oracle SQL, which doesn't have this feature). So Table Value Constructor is nothing else than a T-SQL syntax that allows multiple rows of data to be specified in a single DML statement. TVC can be used only within the following DML statements:

  • INSERT statement
  • USING clause of MERGE statement
  • inline view or derived table in FROM clause
It can only be used to construct 1000 rows of data. The syntax is the same as the VALUES clause within INSERT statement, with the difference that TVC allows providing a list of values separated by comma.
[Table Value Constructor within INSERT statement]

[Table Value Constructor as DERIVED TABLE]

As far as table value constructor within MERGE statement, I'll demonstrate that in the next post , which will be dedicated entirely to MERGE statement as it is also a brand new feature in SQL Server 2008 and it is a little different than the one in Oracle. So it is really important to revisit it before the test.

70-433 - Exam

Filed under: , , by:

After having passed the 1Z0-047 Oracle Database SQL Expert Exam, I decided that it would make sense to take 70-433 (Microsoft SQL Server 2008, Database Development Exam) as my next exam. First of all, I have taken 70-431 (Microsoft SQL Server 2005 - Implementation and Maintenance) exam before, so it would make sense to update it to current version of SQL Server, plus I practices writing a lot of queries to the Oracle exam (even though the syntax sometimes can be so much different) and finally it would make sense to take this exam before I start studying to the .NET 4.0 exams, which based on my experience from previous exams might have a few questions regarding SQL Server 2008. So as always before starting studying to the exam, I try to learn about the exam as much as possible from those who have taken the exam.


There isn't much of very useful information, however one can find that MCTS Self-Paced Training Kit book doesn't even come close to covering topics in the exam, so if you go for the test without a considerable amount of SQL2008 and other version experience or training you are going to be in trouble when you take the exam. One interesting point I found was that "when you seat for the real test, Microsoft will try to "kill" you with really strange T-SQL options and queries that you barely see in real world". As far as Real MCTS Server 2008 70-433 book, it can help a lot but it's not quite enough to actually pass the exam (like no information about Service Broker). Dave mentioned some things that are either new or not very well known that each test taker should know like (filtered index, using APPLY operator to run Table Value Function against all rows in the table, or that an indexed view needs to use WITH SCHEMABINDING, and as a consequence the index must be UNIQUE CLUSTERED). The Best Study Guide for 70-433 site mentions only that to continue preparing with the SQL 2005 materials if you have as SQL 2008 added *new* things to SQL 2005, but there’s nothing in SQL 2005 that won’t be valid knowledge in SQL 2008, and then focus efforts on the *new* things in SQL2008 using SQL Server Books Online.
So based on the information as above, my study plan is to use the following books:
One might ask why some many books on SQL Server 2005. The answer is very simple: because I already own them so I don't feel like spending all the money on the same books for 2008, which will contain only few pages that are not in the previous books. That's why I will use SQL Server 2008 Books Online to learn new features that I could not find the books I already have. As far as posts are considered, I'll probably try to write about the new features introduced by SQL Server 2008 or maybe about some syntax that is typical to T-SQL like Output clause or recursive CTE.

70-561 - Passed

Filed under: , , by:


This week I finally took the 70-561 exam. Finally because originally I scheduled it last month but because I couldn’t make it, I had to reschedule it. Unfortunately, if you don’t show up on the exam, Prometric doesn’t allow for rescheduling it so basically you’ll have to schedule it from scratch and pay for it again. Don’t even bother appealing – they don’t understand that there was an accident and you couldn’t make it or you were on call and you had to stay at work. The worst thing in it is that currently they are allowing for retaking the exam for free if you have failed, but if you didn’t show up, you have to pay again. The only good thing about it is that I had a month more to study. Actually, I have started learning to the next and final exam, which is the 70-565 exam – MCPD Designing and Developing Enterprise Applications Using the Microsoft .NET Framework 3.5 – so I would assume that it should take me about 2 months to get prepared for that exam. But as far as the 70-561 exam is considered, there are 46 questions and 170 minutes for answering them. I think the percentages, indicating the relative weight of each major topic area on the exam, that are shown on the 70-561 exam skills measured page, are pretty accurate. I had 5 questions on the Entity Framework, 5 questions on the Microsoft Sync, quite a few questions on typed DataSet, even more questions on DataSet, DataTable, DataRelation, which is generally the Core ADO.NET. One disappointment was that I have no questions on LINQ to SQL. I had maybe 2 questions on LINQ queries but no LINQ to XML. I remember that in one review to the 70-561 exam training kit book someone wrote that he hadn’t had any XML whereas someone else in another review to the same book wrote that he had found chapters on XML very helpful as he’d had some questions about XML on his exam. I can confirm that I had questions about XML, which in my case was ADO.NET XML api.. Generally, I didn’t find the exam very difficult as I scored 970 out of 1000, but only because I’d had a lot of experience with ADO.NET. It looks like I made a mistake in one question on the Entity Framework – probably because that’s something I have been doing for a short time. About study materials, I would recommend the Programming Entity Framework book, Pro Sync Framework book (make sure you are familiar with all classes and how to use them so anyway I would recommend reading the help file that comes with Microsoft Sync Framework - SyncSDK_v2.chm), ADO.NET 2.0 Core Reference and Advanced Topics and ADO.NET 3.5 Cookbook and maybe something for LINQ. As always the most important thing is to read the questions carefully and make sure that your answer meets ALL the requirements from the question. It is especially important when you have a question in which you think more than one answer can be correct (unless it’s multiple choice question). Plus as always be prepared to have a question that requires out of scope knowledge, which covers other Microsoft technology like T-SQL, SQL Server, Windows OS, Power Shell, WCF, etc. It may even have sense as at the end of the day you’re not working only with ADO.NET but also with .NET, Windows OS, databases, some tools like Power Shell, etc. and you need to know how to react during integration problems like how to tell in ADO.NET that SQL Server is down or that the given T-SQL query will error out and will return the SqlException object. I am really happy that I have taken 70-441 exam – MCTS SQL Server 2005 – it did help me with some of the questions on my exams. I’m telling you, the more exams you have taken, the easier it will be on the next one.

70-561 - Participating in ambient transactions

Filed under: , , , by:

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.

[Product.cs]

[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.

70-561 - Querying a text file

Filed under: , , , by:

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 - Handle special data types

Filed under: , , , , by:

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.

I, however, have focused on .NET code that would "handle special data types", primairly by writing code that would demonstrate how to read and write data stored by special data types. I have combinec BLOB with Filestream as BLOB is commonly used by developers so I didn't think it would deserve a separate attanetion. The code will use a sample database created in SQL Server 2008 with filestream enabled. Note that specified filestream folder must not exist during creation of the database.
[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.

70-561 - Oracle Data Provider for .NET

Filed under: , , , , by:

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):

Here is the description of the created table to show that it contains the same columns as the original one:
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");
else
client.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.

70-561 - "Manage exceptions"

Filed under: , , , by:

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.

However, usefulness of this class and its properties can only be noticed after having gotten a good understanding of error handling mechanism of MS SQL Server. From my experience developers usually have problems with 2 things in that class - Class and State. State property can be used to store a unique number for different locations in which the same user-defined error can be raised, and in the result helping to find which section of code is raising the errors. Class property is used to show Microsoft SQL Server error severity. Severity can be a value from 0 to 25. Severity level from 0 to 10 indicates that error message is informational, which indicates problems caused by mistakes in the information you have entered. Severity levels from 11 through 16 are generated by the user, and can be corrected by the user.Severity levels from 17 through 25 indicate software or hardware errors. When a level 17, 18, or 19 error occurs, you can continue working, although you might not be able to execute a particular statement, whereas an error with level 20+ causes closing a database connection. Only system administrators (users in sysadmin role) can raise error (issue RAISERROR) with a severity level from 19 through 25 and it must be issued with "WITH LOG" option . Below is a chart with definition of each error severity within Microsoft SQL Server.
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());
else
Console.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());
else
Console.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());
else
Console.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());
else
Console.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);
}
}
}
}
}
}
And below is the output window:
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.

70-561 - "Professional ADO.NET 3.5 with LINQ and the Entity Framework"

Filed under: , , , , by:

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).

70-561 - Working with disconnected data - searching and filtering

Filed under: , , , , by:

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.


Now it should be easier to remember that Find method in DataView class returns and index of the found first record that matches the search criteria, whereas Find method in DataRowCollection class returns the searched record. Below is the small console application that demonstrates those methods / properties in action. Personally I'm a big fan of LINQ, since I can use the same syntax to filter or search no matter if I work with DataSet, DataContext, ObjectContext or other classes. Of course there are some additional methods to better work with each of those classes, but the query syntax is always the same - it's not that you have to remember if Find method is in DataView or DataRowCollection class and if it returns an integer value or a data row and if it looks up by primary key or sort key. But unfortunately most production applications use ADO.NET 2.0 API rather than LINQ or Lambda expressions - plus the 70-561 exam test both ADO.NET 2.0 and ADO.NET 3.5, therefore a professional developer should remember all the above solutions.


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();
}
}
}

70-561 - ADO.NET Webcasts

Filed under: , , , by:

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.

  1. ADO.NET
  2. Sync Framework
  3. Data Services
  4. Entity Framework

70-561 Exam

Filed under: , , , by:

My last exam before MCPD Enterprise Application Developer 3.5 (70-565) is the 70-561 exam, which is Microsoft .NET Framework 3.5, ADO.NET Application Development. ADO.NET is part of almost every exam for .NET developers (70-505, 70-562, 70-564) but this exam covers a lot more material than it is required by other exams. As always, I have started my preparations by looking for some guidelines from people who have already taken the exam and by looking for some good books that I can use for my studying. When it comes to blogs, it is a lot harder to find something as this exam is not very popular so there's not many people who have taken it so far. I could only find those two:
Passed 70-561
Finally, Passed 70-561 Exam
But the only useful information I have found was that there isn't much that can prepare you for this exam besides some real world implementation experience; because it is so new there do not yet seem to be little practice exams. Since I haven't taken the exam, I can't really tell if this information is useful or not. It is generally agreed that having real world implementation experience is the best way to pass the exam. Now there's a few good books that cover all the material mentioned by the exam objectives. I have also found two websites with the exam study sheet:
Exam 70-561 Study Sheet
70-561 Microsoft .NET Framework 3.5, ADO.NET Application Development - Section I - Connecting to Data Sources
However, those study sheet are not complete, hence they can't really be considered to meet their purpose as they would if they were complete. And that's where books come in handy and MSDN. I will use the following books to study for the exam:
Programming Microsoft ADO.NET 2.0 Core Reference
Programming Microsoft ADO.NET 2.0 Applications: Advanced Topics
ADO.NET 3.5 Cookbook
Professional ADO.NET 3.5 with LINQ and the Entity Framework
Pro Sync Framework
Pro ADO.NET Data Services: Working with RESTful Data
So there's a couple of books for ADO.NET 2.0 that I have bought for my previous exams (I have aso Core Reference and Advanced topics books for ASP.NET 2.0 and I have found them very useful at the ASP.NET exams so I'm expecting that these ones will get me prepared well to the exam as well). The rest of books are specifically ADO.NET 3.5. It seems that I will have to pay a lot of money for those books but to be honest, I buy them used so ie. Pro Sync Framework will cost me only $4 and Pro ADO.NET Data Services - $12. The most two expensive are ADO.NET 3.5 Cookbook and Professional ADO.NET 3.5 with LINQ and the EF - each costs $30. I have this comfort that I get reimbursed for the books, otherwise I would buy the books, study and then sell them losing maybe $10, or maybe buying one every pay check. As you see there is no MCTS Self-Paced Training Kit (Exam 70-561) book. After having read the reviews I decided that I would be better off buying the aforementioned books. I have found this book reviews very useful and helpful not only because the book is not worth buying but because I could learn more about the exam from people who had taken it and had used the book. Here are some of the opionions people shared about the exam:

  • Study database connections and structuring principles
  • Study SQL dependencies and notifications
  • Even if one has mastered ADO 2.0 API (DbConnection, DbDataAdapter, DateSet, DbCommand, DbDataReader, etc.), it will not be enough to pass as those topics take only 60% of the exam (70% is needed)
  • Knowledge about Entity Framework and Sync Framework is required and those topics take 26% of the exam
  • Linq To XML - there are conflicting opinions - the exam objectvies don't mention Linq To XML and some poeple said it would be a waste of time to study this topic - at least when studying to this exam is considered. However, someone said that a question on it did turn up on his exam. My opinion is that if you've never worked with LINQ to XML, then you should try it - the learning curve is really low and having experience with this topic does pay off, which you can find out next time you're going to work with XML
One could say that anyone can arrive to the same conclusions only by studying the exam objectives but on the other hand it's always good to know what topics are more likely to appear on your exam. Unfortunately none of the opionions go into details but even though you can learn to practice sql notifications and dependencies or connecting to different databases. Besides, Microsoft exams are not open book exams and that's why they can be used as an evaluation means of one's IT skills.