Posts
250
Comments
24
Trackbacks
13
May 2006 Entries
Download details: Authentication and Access Control Diagnostics 1.0 (x86)
Authentication and Access Control Diagnostics 1.0 (more commonly known as AuthDiag) is a tool released by Microsoft aimed at aiding IT professionals and developers at more effectively finding the source of authentication and authorization failures.

These users have often seen behavior from Internet Information Services (IIS) that doesn't seem appropriate or random when users authenticate to the IIS server. The complex world of authentication types and the various levels of security permissions necessary to allow a user to access the server causes many hours of labor for those tasked with troubleshooting these problems.

AuthDiag 1.0 offers a robust tool that offers a efficient method for troubleshooting authentication on IIS 5.x and 6.0. It will analyze metabase configuration and system-wide policies and warn users of possible points of failure and guide them to resolving the problem. AuthDiag 1.0 also includes a robust monitoring tool called AuthMon designed at capturing a snapshot of the problem while it occurs in real-time. AuthMon is robust and specially designed for IIS servers removing any information not pertinent to the authentication or authorization process.

Download details: Authentication and Access Control Diagnostics 1.0 (x86).

posted @ Friday, May 26, 2006 6:13 AM | Feedback (0)
Optimize and reduce the size of your VMWare Virtual Machines...

Invirtus - software to make virtual machines more accessible to more people - Products.

I could use anything to make this process easier; sure you could do many of these steps manually, but to automate it and get it done with little effort would be great.

posted @ Wednesday, May 24, 2006 5:30 AM | Feedback (0)
Check out if you PC/Notebook can Run Vista - Aero check...

Upgrade Advisor

Windows Vista Capable and Premium Ready PCs.

Nice to see that our COO was right, the Toshiba M3’s that were bought 1+ years ago CAN run Aero…  In fact passes all the tests in the Upgrade Advisor…

posted @ Thursday, May 18, 2006 12:25 PM | Feedback (0)
Skype - Voice Calls to Ordinary Phones - Great Quality

How to get calling.

I’ve been using Vonage for about 6 months.  For $25/month the service is pretty good. Nice features with voice mail being saved to WAV files for download and automatic email.

However, today I tried out Skype’s (SkypeOut) where you can from your PC call any other phone.

The sound quality is great and the latency is short.  With this kind of capability, I’m now rethinking what I need vonage for.

 

posted @ Monday, May 15, 2006 1:40 PM | Feedback (0)
Podcast Mentions... Chuck Boyce from SSWUG.org

Here Chuck Boyce, who helps run the SQL Server Worldwide Users Group, mentions a couple of my SQL Related posts.  Chuck is also on the PASS board and runs the Phila PASS chapter.

Thanks alot Chuck…

http://www.sswug.org/sswugradio/pdetails.asp?pid=94 

http://www.sswug.org/sswugradio/pdetails.asp?pid=88

posted @ Monday, May 15, 2006 7:27 AM | Feedback (0)
Article on SQL .NET CLR - Application Configuration Settings Posted to SqlJunkies.com

An article I wrote a couple weeks back has been posted to www.Sqljunkies.com

Accessing Application Configuration Settings from SQL CLR

Recently, one of my peers asked a question regarding the ability of SQL CLR classes to read configuration data from an Application Configuration file. After doing some quick Google searches on the topic, I came up with a couple of links that indicated the potential, but no concrete HOWTO on getting it all wired up.

Now, I don’t want to debate whether this makes good architectural sense to store static settings in the file system when you’re already working inside a database management system that could just as easily save these settings to a table. A scenario that you might leverage this capability is to re-use an existing Application Configuration file, specifically, the <appSettings> element from an already built and working assembly from another application. 

This article also uncoves a bug in the SQL CLR implementation that if you don’t know about it you will have issues reading the settings.

Continue at source…

posted @ Monday, May 15, 2006 5:22 AM | Feedback (0)
SQL Server Service Broker - It's place in the World....

Have Data Will Travel : Where does Service Broker Fit?.

This is a good “perspective” post on where Service Broker, MSMQ, BizTalk, and WCF fit in architectures.

I was at an MGB (Microsoft Global Briefing)* about 2 years back.  So, the presentation I’m sitting in is on Service Broker.  So, another MSFT guy in the audience asks a question regarding product positioning with BizTalk. 

Well, that exchange turned into a great nasty fight between the 2 MSFT folks with applause coming from the audience when the person asking the question had some nice comments.  The presenter handled it so poorly and was quite nasty about it.

Frankly, the whole Service Broker existence is troubling with something like BizTalk available.  Frankly there’s alot of crap I can get done with Service Broker running on SQL Express to the point who Needs BizTalk.

I really think they should be pushing down the availability of BizTalk to more mass market pricing.  Apparently they are (or will be) as I’ve heard there will be aggressive pricing in the $2K range.

* Note these MGB conferences were open only to Microsoft employees; however, Avanade had a special place under Microsoft (we’re about 20% owned by MSFT) we had opportunities to attend.

posted @ Wednesday, May 10, 2006 9:19 AM | Feedback (0)
Fantastic External USB 2.0 Drive Enclosure @ Newegg from SimpleTech

SimpleTech STI-HD2.5/USB2 External Enclosure - OEM at Newegg.com.

This so far is the best external USB 2.0 Drive Enclosure that I’ve used.  Great design with a short USB cable that folds away.  Wish they had 2 other things: Way to get a longer USB cord and power switch.  CORRECTION: They give you a longer USB, I was thinking the built-in USB if it could extend a bit more would be nice.

But, this think looks cool, connects easily and I don’t have to drag around one of those long USB cables to connect it to my notebook or desktop.  And, for power it has a DC connection if you need it (5V/1amp) but fortunately my current Toshiba M3 has enough power on it’s USB bus I dont’ need it. My older crappy Dell C640 couldn’t handle it.

Comes with nice software called StorageSync that does backups.  Unfortunately won’t do a disk clone/copy so I can move from my 60G internal to a 100G drive by first connecting the 100G via USB — probably need Norton Ghost for that.

posted @ Wednesday, May 10, 2006 8:23 AM | Feedback (0)
Microsoft Exception MessageBox - Nice little gem

If you're developing WinForm applications, generally at some point in the project you develop an Exception Dialog box that provides a user friendly interface for error messages.  Usually, it's a generic box that displays parts of the exception stack and perhaps a way to log or allow users to initiate some other action such as proceeding, ignoring, or even reporting the error.  Usually the solution hooks in as the Application or AppDomain unhandled exception handler at startup. Thing is, I don't see much re-use between projects with what should be a re-usable component.

Microsoft Exception Message Box

The other day I was working with some of the downloads included in the Feature Pack for Microsoft SQL Server 2005 - April 2006 and I noticed in that pack an item called Microsoft Exception Message Box.  Here's the text for that download from the Feature Pack page:

The exception message box is a programmatic interface that you can use in your applications for any tasks for which MessageBox may be used. The exception message box is a supported managed assembly designed to elegantly handle managed code exceptions. It provides significantly more control over the messaging experience and gives your users the options to save error message content for later reference and to get help on messages.

More investigation, on the Microsoft MSDN website under Deploying an Exception Message Box Application the following statement appears:

The exception message box is installed by Microsoft SQL Server 2005 and is supported for use in your custom Windows applications to improve exception handling. In SQL Server 2005 SP1 and later releases, the exception message box is also provided as a redistributable installation program that you can distribute and deploy with your application.

It goes on to state:

  • You must include the exception message box redistributable package (SQLServer2005_EMB.msi) in your application setup.
  • Exception message box resources are installed in the global assembly cache (GAC).
  • The redistributable package is available in all supported SQL Server 2005 languages.
  • The exception message box installation does not appear in Add or Remove Programs. You should plan to uninstall the exception message box when your application is uninstalled.

What does this mean?  Well, Microsoft has granted us a license to use and redistribute this Assembly with our own applications as long as we follow the installation rules in the list above.

Sample Solution Files

Sample Solution

So, what does this thing do?

Before we proceed, some background on using the Assembly (Microsoft.ExceptionMessageBox.dll) in your solution.  First you'll need to establish a reference to the assembly.  Although it's installed in the GAC, if you attempt to add a reference in Visual Studio 2005 (this thing is .NET 2.0 Only), it doesn't show up in the Visual Studio .NET Reference Tab[1].  So, you just need to click the Browse Tab and navigate over to the C:\Program Files\Microsoft SQL Server\90\SDK directory.

Once you got the reference set, then you have access to the Namespace types in Microsoft.SqlServer.MessageBox.  There's a good set of steps located on MSDN How to: Program Exception Message Box.

The following set of examples are taken right from MSDN, but there's also shots of the actual MessageBox UI, which is absent on MSDN. So, let's take a look at some of the basic features.

The sample application with this article is located here: Sample Solution.  And a screen shot of the UI is shown below:

Simple OK

The basic ExceptionMessageBox is fairly basic dialog.  Additionally, the code is straightforward.

try
{
    // Do something that may generate an exception.
    throw new ApplicationException("An error has occurred");
}
catch (ApplicationException ex)
{
    // Define a new top-level error message.
    string str = "The action failed.";

    // Add the new top-level message to the handled exception.
    ApplicationException exTop = new ApplicationException(str, ex);
    exTop.Source = this.Text;

    // Show an exception message box with an OK button (the default).
    ExceptionMessageBox box = new ExceptionMessageBox(exTop);
    box.Show(this);
}

What that provides is a simple dialog, but as you'll see there's some additional features, even in the basic ExceptionMessageBox that are quite useful.  Here's the initial Dialog:

What you should notice is the two icons in the lower left.  The first allows copying of the contents of the message box to the user clipboard.  May seem novel, but some background - any windows message box if you do a Ctrl+C you can capture the text of the message box to the clipboard.  What the ExceptionMessageBox does is make the capability explicit and clickable. 

The second icon is a Advanced details button.  If you click that, you get the following:

Hopefully you can see that there's room for additional information that's potentially usable to anyone doing troubleshooting on your application.  As you'll see soon, you can expand this information even further by leveraging a new feature in .NET 2.0's System.Exception class.

Yes / No

This example provides a simple way of replacing a Dialog box and trapping the DialogResult for conditional processing.

// Define the message and caption to display.
string str = "Are you sure you want to delete file 'c:\\somefile.txt'?";
string caption = "Confirm File Deletion";

// Show the exception message box with Yes and No buttons.
ExceptionMessageBox box = new ExceptionMessageBox(str,
    caption, ExceptionMessageBoxButtons.YesNo,
    ExceptionMessageBoxSymbol.Question,
    ExceptionMessageBoxDefaultButton.Button2);

if (DialogResult.Yes == box.Show(this))
{
    // Delete the file.
}

Here the Yes / No option produces the following giving you conditional based processing:

Custom Buttons

Custom Buttons allow you to control the text on up to 5 buttons (Button1 - Button5) in addition to a None option.  Again, useful for conditional processing and providing text beyond the normal Abort, Retry, Ignore options.

try
{
    // Do something that may cause an exception.
    throw new ApplicationException("An error has occured");
}
catch (ApplicationException ex)
{
    string str = "Action failed. What do you want to do?";
    ApplicationException exTop = new ApplicationException(str, ex);
    exTop.Source = this.Text;

    // Show the exception message box with three custom buttons.
    ExceptionMessageBox box = new ExceptionMessageBox(exTop);

    // Set the names of the three custom buttons.
    box.SetButtonText("Skip", "Retry", "Stop Processing");

    // Set the Retry button as the default.
    box.DefaultButton = ExceptionMessageBoxDefaultButton.Button2;
    box.Symbol = ExceptionMessageBoxSymbol.Question;
    box.Buttons = ExceptionMessageBoxButtons.Custom;

    box.Show(this);

    // Do something, depending on the button that the user clicks.
    switch (box.CustomDialogResult)
    {
        case ExceptionMessageBoxDialogResult.Button1:
            // Skip action
            break;
        case ExceptionMessageBoxDialogResult.Button2:
            // Retry action
            break;
        case ExceptionMessageBoxDialogResult.Button3:
            // Stop processing action
            break;
    }
}

This is the UI with Custom Buttons

Exception Additional Data

.NET 2.0 added a new member to the System.Exception base class.  This member is a collection that implements IDictionairy - giving you a collection of key / value pairs that you can add additional state and condition information to an Exception that might be useful for Exception handlers or in our situation additional diagnostic information for the ExceptionMessageBox.

In the following code, again taken direct from MSDN, the ApplicationException's Data member is populated with 3 additional bits of information.

try
{
    // Do something that you don't expect to generate an exception.
    throw new ApplicationException("Failed to connect to the server.");
}
catch (ApplicationException ex)
{
    string str = "An unexpected error occurred. Please call Helpdesk.";
    ApplicationException exTop = new ApplicationException(str, ex);
    exTop.Source = this.Text;

    // Information in the Data property of an exception that has a name
    // beginning with "HelpLink.Advanced" is shown when the user
    // clicks the Advanced Information button of the exception message
    // box dialog box.
    exTop.Data.Add("AdvancedInformation.FileName", "application.dll");
    exTop.Data.Add("AdvancedInformation.FilePosition", "line 355");
    exTop.Data.Add("AdvancedInformation.UserContext", "single user mode");

    // Show the exception message box with additional information that 
    // is helpful when a user calls technical support.
    ExceptionMessageBox box = new ExceptionMessageBox(exTop);

    box.Show(this);
}

This results in additional information if you click on the Advanced Details button.

Here, in the red circle, you can see the additional strings added to the Data collection for the Exception type.  The ExceptionMessageBox has enumerated through the collection and displayed the ToString() for each item.

Summary

While many teams will develop their own Exception Message box and handling process, one thing to consider is whether the one provided here can meet the needs and save you a little time.  Certainly there are limitations to what you can do with this Assembly.  This article has only scratched the surface of what's possible.

Some features not shown here allow trapping of events such as OnCopyToClipboard along with additional property level control over the appearance and behavior.

So, I recommend that you take a look at what Microsoft has to offer here before coding up your own Exception Message box.  Least you can do is abstract and wrap today, and replace as needed in the future.

About

Shawn Cicoria is a Consultant with Avanade (www.Avanade.com) the leading Systems Integration Consultancy focused on the Microsoft Platform. Shawn is also a MCT training instructor with SetFocus (www.Setfocus.com) located in Parsippany NJ. Focused on distributed technologies such as COM[+], J2EE, and for the past 5 years .NET, SOAP, BizTalk, and Database technologies -- and now WinFX..

 

[1] The registry key HKLM\SOFTWARE\Microsoft\.NETFramework\AssemblyFolders controls what .NET Assemblies show up in the Visual Studio 2005 Add Reference .NET Tab.

posted @ Tuesday, May 09, 2006 12:03 PM | Feedback (3)
Pre-Built Virtual Machines - This is another reason why Vmware Rocks..

Virtual Appliances: VMTN Appliances.

VMWare has done a great job of leveraging the community to build ready-to-go Virtual Machines build on Linux core and other open source software.

These are download and start machines that do all sorts of things.  So, if you want to ramp up on some technology this is one way.

Now, for Microsoft, the biggest struggle is the OS licensing cost.  Is really a shame but if Microsoft could get product in trial form out the door and download-able in VM form it would be ideal.  The fact is, they do this already if you’re an MCT (Microsoft Certified Trainer).  I have access to all the learning content as I’m an MCT, but the licensing is always a struggle.  They give us a key, but many MCT’s still have problems.

I think over time the OS license issue will diminish or MSFT needs to find out a way to get pre-built VM’s based on VPC or VS of course out there and usable by those that want to “experiment”.

CORRECTION: thanks to Matt – He points out a CRM 3.0 VM in his post: http://www.simpleviews.net/archives/101 

Only issue is, it expires 12/31/06…

posted @ Monday, May 08, 2006 4:06 PM | Feedback (0)
Scrum for Team System
Scrum for Team System is a free Agile Software Development Methodology add-in for Microsoft Visual Studio Team System, developed by Conchango, in collaboration with Ken Schwaber and the Microsoft Technology Centre UK.
Scrum for Team System provides development teams with deep support for the use of Scrum, when running projects using Visual Studio Team System’s integrated suite of lifecycle tools.

Scrum for Team System.

posted @ Monday, May 08, 2006 1:17 PM | Feedback (0)
Team System Utilities

Looks like the TFS utility aftermarket is begining to grow.  Now, if they can get TDD right….

Here is a short list of some Team System utilties that you may find useful. If you know of a Team System utility that has made your life simpler, please let me know about it and I'll add it to the list.

Digerati Technologies, LLC.

And thanks to Nestor for another great list:

http://accentient.com/widgets.aspx

posted @ Monday, May 08, 2006 1:16 PM | Feedback (0)
Windows Vista Aero support in WPF & WinForms

I’m starting to see more applications leveraging Aero Glass on Vista.  They look quite cool.  Here’s a couple of posts on getting Aero on WinForms and Windows Presentation Manager

Tim Sneath : Windows Vista Aero Pt. 1 - Adding Glass to a Windows Forms Application

Adam Nathan's Win32 to WinFX Blog : Aero Glass inside a WPF Window

posted @ Sunday, May 07, 2006 3:55 PM | Feedback (0)
Add-in for Visual Studio 2005 Available to "faciliatate" Contract First...

Contract first forces you to design your service interfaces in ways that should remove implementation issues that affect that design.  Here’s a Visual Studio add-in that helps you in that quest – it’s from The thinktecture folks.

There has been a lot of buzz around contract-first Web Services design & development lately. A number of people thinks that it is a good thing and that we finally should reach a state where we all can live and breath it. But most people have been complaining about the lack of tool support for the so called 'first step':
Design your contract's data, messages and interface
Generate code from the contract

thinktecture - WSCF.

posted @ Sunday, May 07, 2006 8:27 AM | Feedback (0)
Non-Profits - get a Makeover - Free consulting services from Avanade, Microsoft Technologies, Server and Storage - Valued @ $350,000

Avanade, NPower NY and Microsoft invite local nonprofits to apply for an “Xtreme Techover” organizational makeover, to help transform their community technology centers and administrative systems to better serve their communities.  Organizations can apply online by May 26, 2006 at www.avanadeadvisor.com/xtremetechover.

One nonprofit will receive the grand prize, consisting of:

  • Consulting services worth $150,000 – including two consultants for 4-6 weeks – from Avanade, the leading global integrator specializing in the Microsoft enterprise platform
  • $50,000 in software licenses and $50,000 for physical improvements to a technology center or training from Microsoft
  • Server and storage value of $150,000 from Network Appliances

Second and third place winners will receive an online Microsoft certification course and access to an online library of the latest technical and business books.

All applicants will receive a free one-year membership or auto-renewal to NPower NY, which includes access to discounted or free volunteer resources, software, hardware, workshops and Webinars.  Winners will be announced at a June 20th breakfast for all applicants.

Deadline:        May 26, 2006
Who’s Eligible:  New York/New Jersey metro region nonprofit organizations that are registered as a 501(c)(3), have between 20 and 50 technology users, not affiliated with any school or hospital organization, and currently have an on-site community technology center delivering technology access to its constituents.

posted @ Thursday, May 04, 2006 3:53 AM | Feedback (0)
Excellent Series of posts on building a Custom Transport for WCF

Nicholas Allen's Indigo Blog : Building a Custom File Transport, Part 7: Request Channel.

I was looking at building my own File Transport when I did a search and up comes this excellent series.  Can’t wait till Nick’s all done.

posted @ Monday, May 01, 2006 12:46 PM | Feedback (0)
Accessing Application Configuration Settings from SQL CLR

Recently, one of my peers asked a question regarding the ability of SQL CLR classes to read configuration data from an Application Configuration file. After doing some quick Google searches on the topic, I came up with a couple of links that indicated the potential, but no concrete HOWTO on getting it all wired up.

Now, I don’t want to debate whether this makes good architectural sense to store static settings in the file system when you’re already working inside a database management system that could just as easily save these settings to a table. A scenario that you might leverage this capability is to re-use an existing Application Configuration file, specifically, the <appSettings> element from an already built and working assembly from another application.  One of the blog posts I found from Bob Beauchemin [1] states the same issue and scenario of use. Bob also kind of discuses high level what needs to happen; but, again, no step-by-step wire-up exists.

Turns out, after I sent the links to my peer indicating that it’s possible, I decided to try it out and get a quick sample running. I’m glad I did, as it turns out it wasn’t as straightforward as expected and I encountered a small anomaly that if you don’t know a workaround you’d come to a rapid conclusion that it’s not possible to read <appSettings> from the configuration file after all.

Sample Solution Files

SQL Server Configuration

The first step before you can run any CLR code inside of SQL 2005, you must enable it. You can search MSDN or Books Online for the topic “Enabling CLR Integration”. The following set of commands enables the CLR in SQL 2005:

sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'clr enabled', 1;
GO
RECONFIGURE;
GO

Visual Studio 2005 SQL Project

Now, launch Visual Studio 2005 and startup a new project. Choose “SQL Server Project” which, depending upon your profile settings, is listed under your language of choice and the database folder.

Visual Studio creates a SQL project that allows for debugging directly into the called CLR code by automatically attaching to the SQL process and executing the debug session. I’m not going to go into SQL CLR debugging as it’s covered fairly well in Books Online.

Visual Studio Project File Manual Edit

In order to access the System.Configuration namespace that’s part of .NET 2.0, it’s necessary to close down the solution & project that was just created and edit the project file directly.  Generally, inside of Visual Studio you’d right click on a project, choose “Add Reference”, find the Assembly and you’re done. 

The System.Configuration.dll assembly is on the SQL 2005 Approved assembly list [2]; however, since it was added as approved at the last moment before RTM it’s not possible to add it by using the normal method inside of Visual Studio.  So, to work around the limitation inside of Visual Studio, we're just going to add the reference manually to the Visual Studio project file.

So, close down the project file (shut Visual Studio). Navigate to the folder where the “.csproj” file (or “.vbproj” file) is then open up with your favorite text editor.

Find the first <ItemGroup> element whose sub-elements are <Reference>. Once you have that section, add a new child element as follows:

<Reference Include="System.configuration" />

So, you should end up with the following <ItemGroup> section:

<ItemGroup>
    <Reference Include="System" />
    <Reference Include="System.Data" />
    <Reference Include="System.XML" />
    <Reference Include="System.configuration" />
</ItemGroup>

Now, re-launch your project back in Visual Studio. Check to see that the references are OK and you should see the following:

Next, add a new item to the project and choose “User Defined Function”. Basically, all this does is add a file that has the correct attribute on the method that is part of the template. For our needs the attribute is Microsoft.SqlServer.Server.SqlFunction.

Take a look at the included code for the complete class file. Here’s the complete listing.

using System.Configuration;

namespace CedarLogic.SqlTest
{
    public partial class UserDefinedFunctions
    {
       [Microsoft.SqlServer.Server.SqlFunction]
       public static SqlString GetAppSetting( string key )
       {
           try
           {
               /* The following call is made in order to workaround an "anomaly"
               * where reading an appSettings key value results in the error:
               * "The value of the property 'key' cannot be parsed.
               * The error is: Request failed. (sqlservr.exe.Config line X)"
               *
               * So, just a call to another section alleviates the issue.
               * This error only occurs on the first call to an assembly after
               * it's been loaded by the sqlservr.exe
               */

               int i = ConfigurationManager.ConnectionStrings.Count;

               //here, simply use configuration manager to read the key to
               //a temp variable - doesn't need to be a temp var, but here
               //for simple debugging.
               string s = ConfigurationManager.AppSettings[key.ToString()];
               return "OK: " + s;
           }
           catch( Exception ex )
           {
               return ex.Message;
           }
       }
    }
}

Application Configuration File

If you haven't worked much with .NET, a little background on Application Configuration [3] files is helpful.  .NET provides a Configuration namespace (System.Configuration) that provides the ability to provide runtime configurable application options from an XML based file.  The solution files for this sample contains a "sqlservr.exe.config" file.  The contents are as follows:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
        <add key="MyKey" value="MyValue" />
    </appSettings>
</configuration>

The <appSettings> element provides a simple name-value pair of application settings that the .NET runtime de-serializes into an in-memory object.  These settings are read using a "key" to retrieve the value.

The file is read once by the runtime and to change any value requires restarting the process - or more specifically the Application Domain [4] - but that's another discussion.

In your .NET code, to read the values, simple leverage the System.Configuration.ConfigurationManager type, specifically the static property accessor AppSettings.  This method returns a string object:

string myAppValue = System.Configuration.ConfigurationManager.AppSettings["MyKey"];

The next step is to provide the SQL server instance with an Application Configuration file. Since the CLR is to be loaded inside of the SQL Server process, the name of the configuration file is just the exe name with “.config” appended to it. It’s also necessary to ensure you have the instance’s correct path to put the configuration file in. There are 2 ways to obtain that path. The first is to use SQL Server Management studio, right-click on the connected instance, then check the “Root Directory” setting. This is the base path of the instance. In the \Binn subdirectory is where the “sqlservr.exe” main binary is and this is the directory where the “sqlservr.exe.config” file must go in order for the CLR to load it.

The other way to obtain the Root path is to run the following command in the query window.

declare @smoRoot varchar(1024)
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE',
N'SOFTWARE\Microsoft\MSSQLServer\Setup', N'SQLPath', @SmoRoot OUTPUT
select @smoRoot

Now, the included project has a sample “sqlservr.exe.config” file that will work with the sample project.

Once this file is placed in the SQL \Binn directory, you must restart the SQL Server instance (using Windows Service Manager is one way) in order for the file to be utilized. In fact, any changes you make to this file, you must restart the SQL Server instance to read the new values – another reason that this may not be the best option for application settings.

Assembly Deployment

Visual Studio 2005’s SQL Project makes building and deploying the compiled assembly very easy. In fact, it hides quite a bit of what is happening each time you choose “Deploy” from the build menu. To see some details of how to deploy manually, the solution files with this article includes a file called “AddAssembly.sql” that provides the steps necessary to both install the assembly and declare the user defined function. This script assumes 2 things – 1) the name of the database and 2) the path to the Assembly. On your environment these most likely will be different.

So, from within Visual Studio, ensure that you have a database reference to the database you want to deploy to. You can check or change by select project properties and navigating to the Database tab. Here you can change the connection string that will be used for deployment and other SQL Project needs (such as reading what other Assemblies are available for references).

Once you have a valid database reference for your project, you can deploy the assembly choosing "Deploy" from the build menu or right-click on the project in Solution Explorer, and select "Deploy" as follows:

 

Executing Your SQL CLR User Defined Function

Once it’s deployed, it’s just a matter of making a call to the function. For that launch SQL Server Management studio, start a new query window and choose the database that the Assembly was deployed to.

From the query window just enter the command to execute the function (note that the DB name in this line is 'AJunkDb'):

SELECT [AJunkDb].[dbo].[GetAppSetting] ('MyKey')

This should provide a result in the query results window that corresponds to the value stored in the “sqlservr.exe.config” file – which is just “MyValue”.  What the runtime and your CLR based function has done is read the "sqlservr.exe.config" file, looked up the key value provided - 'MyKey' - and returned the associated value - 'MyValue' - that was stored in the file.

Issues

One of the issues I encountered (a bug) is if the first call through ConfigurationManager is to the static AppSettings method an error is returned indicating it couldn’t read the key value. That error is:

"The value of the property 'key' cannot be parsed.
* The error is: Request failed. (sqlservr.exe.Config line X)".

Now, the line that causes this exception is:

string s = ConfigurationManager.AppSettings[key.ToString()];

There’s absolutely nothing wrong with that line of code. And, there’s nothing wrong with the configuration file.

So, after some debugging, I found that if I make some “dummy” call through ConfigurationManager to another method, then I can make the call to AppSettings with absolutely no issue. So, the following line is added just to provide a kludge of a workaround on line 36:

int i = ConfigurationManager.ConnectionStrings.Count;

Now, this line does nothing other than initialize ConfigurationManager and force a de-serialization of the configuration file.

To verify that this is the issue, comment out line 36 above in the source code, and be sure to “Deploy” the project again (this forces SQL to unload and reload the Assembly from the CLR). This is important as the problem only occurs on the 1st time an Assembly is loaded and the 1st call is to AppSettings. If any other call (such as line 36) is made to ConfigurationManager then the problem doesn’t reveal itself.

Summary

To summarize the steps that provides a way to read Application Configuration settings from within SQL CLR:

  1. Enable SQL CLR capability for the SQL Server instance by using the 'clr enabled' option via 'sp_configure'
  2. Create a Visual Studio 2005 SQL Server Project
  3. Manually edit the Visual Studio Project file adding a reference to the SQL CLR Approved assemby "System.Configuration"
  4. Develop my CLR Function
  5. Create a "sqlservr.exe.config" file and deploy to the correct Binn directory for my SQL Server instance
  6. Restart my SQL Server instance to ensure the Application Configuration file is read

So, a couple of things were uncovered in this sample.

  • Adding System.Configuration to the project file manually is no problem as it’s an approved assembly for SQL 2005, but the Visual Studio 2005 RTM isn’t aware of it.
  • An anomaly in System.Configuration.ConfigurationManager with the AppSettings method being called first may cause a conclusion that it’s not possible to read App.config settings
  • The Assembly itself that is deployed to the SQL Instance only needs a Safe access level even though it’s accessing the file system. This to me is probably an oversight by the SQL team given the policy for any external resource (file system) would normally require either External or Unsafe level
  • Consideration should be made if this is the right way to store settings for the Db tier for a couple of good reasons: 1) it violates the reason why your using a Db – the capability to store objects in tables, and 2) requires a restart of the SQL Instance if any changes are made to the configuration file; so, if it's about re-use it's another capability that's at your disposal

About

Shawn Cicoria is a Consultant with Avanade (www.Avanade.com) the leading Systems Integration Consultancy focused on the Microsoft Platform. Shawn is also a MCT training instructor with SetFocus (www.Setfocus.com) located in Parsippany NJ. Focused on distributed technologies such as COM[+], J2EE, and for the past 5 years .NET, SOAP, BizTalk, and Database technologies -- and now WinFX..

[1] Using System.Configuration.dll in .NET sprocs and UDFs
[2] Supported .NET Framework Libraries
[3] Application Configuration Files - MSDN Online
[4] Application Domains - MSDN Online
 

posted @ Monday, May 01, 2006 6:13 AM | Feedback (0)
News





Tag Cloud