Archive

Posts Tagged ‘Web Services’

.NET Uri, database not found, and encoding

I ran into an interesting issue when trying to debug some code a while back.  I had written a dynamic that would allow a person to authenticate and then pick a database in which to perform their operations.  For the most part, this system worked well and allowed me to keep things simple.  The part that was trick was that I had written my reporting and dashboard engine to use a single Razor .cshtml file to handle all requests.  It in turn pulled the report definition or dashboard definition XML files from the database.  The problem came when one of the SQL Server databases that the system was deployed was not the default instance but a “named instance“.

In my code, I would simply construct an Uri object and pass in the string that represented the parameters that I needed for the given page.  However, since a named instance uses the ‘\‘ character, this caused some problems as my simple string representation was not encoding the character and thus when the server received the request it was not a valid server name.  I spent hours thinking that it was a problem with the configuration with SQL Server.  It wasn’t until I debugged the .cshtml file that I realized that the name of the server was not coming across correctly and that I was not encoding the name properly.  Here is what I finally came up with to correct the issue:

string address = string.Format("../PreviewReturnSetupBillDesigner.cshtml?
Key={0}&ServerName={1}&DatabaseName={2}",
  101,
  HttpUtility.UrlEncode("monticello\test"),
  HttpUtility.UrlEncode("sample"));

Uri uri = new Uri(address, UriKind.RelativeOrAbsolute);

Previously, I was just passing in the server and database names without encoding them. This worked for all default installations of SQL Server but once you had a named instance in place, all bets were off.

Hopefully this will help anyone from spinning their wheels if they are doing anything similar…