Tuesday, September 15, 2009

Convincing Visual Studio 2005 that SqlClient is a valid namespace

While getting a project started to connect and use an SQL Server database from a mobile device, I ran into the same problem apparently many others have, too. You had to force Visual Studio to include some framework components so you were allowed to use them. I happened to be using Visual Studio 2005 (aka Visual Studio 8.0) to build an application for a .NET Compact Framework 2.0 platform that exchanged data with a Microsoft SQL Server 2005 database over a wireless network.

To execute a query directly against the remote database without using the SQL Compact (aka SQL Mobile aka SQL CE) SDK and without using dataset objects, required SqlConnection, SqlCommand, SqlParameter, and several other classes that existed in the System.Data.SqlClient namespace. Unfortunately you couldn't just type your using statements and have VS magically link them to your application. You expected Microsoft to make it automatic? No way. That's where the Add Reference... feature is needed and was a source of confusion (days!) in my early development with the VS .NET IDE.

Without adding a proper reference, the statement:

using System.Data.SqlClient;

caused the following compilation error and would not complete the build:

The type or namespace name 'SqlClient' does not exist in the namespace 'System.Data' (are you missing an assembly reference?)

Part of the problem is the multiplicity of .NETCF versions. As is standard with Microsoft, things get moved, renamed, and otherwise mangled between versions. In .NET CF 2.0, SqlClient is part of the System.Data namespace and the System.Data.dll library file; in later versions, there is a separate System.Data.SqlClient.dll. To allow this necessary namespace to be used in your project, you must add a reference to the System.Data.SqlClient component. The trick is learning a couple things about a listed component on the .NET tab: the "Runtime" column identifies the framework version it belongs to, not the "Version" column, that is for the version of the component itself. Also the "Path" column refers to the component as used by the IDE, not by the target device. The path does not even exist on the target device. There were a few clues, but putting them together to arrive at a coherent solution took experience or lots of trials & errors.

At the time I wrote this, the SqlClient namespace for .NET CF 2.0 was added by referencing the component named System.Data.SqlClient, version 3.0.3600.0, runtime version v.0.50727, whose (IDE) path was C:\Program Files\Microsoft Visual Studio 8\SmartDevices\SDK\\SQL Server\Client\v2.0\System.Data.SqlClient.dll. And before you point out my "typo", yes, that was the real path.

Adding this component as a reference finally allowed me to compile without VS coughing up the error.

No comments:

Post a Comment