LP on .NET

April 15, 2010

SQL Server 2008 Management Studio Express Installation Problems

Filed under: .NET,Microsoft,Software Development,SQL Server — Larry Parker @ 8:50 pm

Boy was this a day to remember.  Granted it was April 15th, but it had nothing to do with taxes.

I needed to apply a short SQL script to a database, so I fired up SQL Server 2005 Management Studio and tried to connect to my local SQL Server 2005 Express instance.  But surprisingly, I got this error:

image

[This version of Microsoft SQL Server Management Studio can only be used to connect to SQL Server 2000 and SQL Server 2005 servers]

It turns out that my local SQL Server instance was no longer SQL Server 2005 Express but was instead SQL Server 2008 Express.  I recently installed Visual Studio 2010 on my development machine and it must have upgraded this.  Fair enough.

So I proceeded to run SQL Server 2008 Management Studio Express instead so it could talk to my SQL Server 2008 Express instance.  The only problem was that it wasn’t under the Microsoft SQL Server 2008 program group.  I guess VS 2010 did not install this but instead just installed the SQL engine itself.  I cannot understand why Microsoft would not include the GUI tool for SQL 2008, but surely they have a good reason.

So I found the SQL Server 2008 Management Studio Express link and proceeded to install that.

When I got to the Installation Type screen, I selected “Add features to an existing instance of SQL Server 2008”.

image

This seemed like the logical choice since SQL 2008 was already installed by the Visual Studio 2010 install.

But logic did not prevail in this case.  When I got to the Feature Selection screen, there were no features to select:

image

After searching around on some blogs and forums, it turns out that I should have selected “Perform a new installation of SQL Server 2008”:

image

Not very intuitive, but at least now I could select the Management Tools feature:

image

After successfully clicking through the next couple of wizard screens , I ran into another snag – this time on the Installation Rules screen:

image

When I clicked on the Failed hyperlink next to the “Previous releases of Microsoft Visual Studio 2008” entry, I got the following error:

image

[A previous release of Microsoft Visual Studio 2008 is installed on this computer.  Upgrade Microsoft Visual Studio 2008 to the SP1 before installing SQL Server 2008]

So I brought up Visual Studio 2008 to check if I had SP1 installed, and it turned out that I did.  Huh??  At this point, I felt like I was on Candid Camera (ok, I’m showing my age – I should have said Punk’d) and probably uttered a few expletives.

After looking around for Allen Funt, I mean Ashton Kutcher, I tried repairing Visual Studio 2008 by going to Control Panel and bringing up this screen:

image

Then I uninstalled SQL 2008 Express and reinstalled it again, but got the same problem on the Installation Rules screen where it was saying I needed VS 2008 SP1.

Note: make sure you install SQL Server 2008 Express with Tools!  At first I just installed SQL Server 2008 Express and had to waste more time figuring out why Management Tools was not available on the Feature Selection screen.

Back to the VS 2008 SP1 problem…  After checking around on a few blogs and forums, the general consensus was to uninstall Visual Studio 2008 SP1 and reinstall it.

Instead of suffering through completely uninstalling and reinstalling Visual Studio,  I tried out a shortcut and just reinstalled the service pack from this link.  I didn’t encounter any problems with this, but I highly recommend that you back up your Visual Studio 2008 settings first (under Tools | Import and Export Settings…).

So then I went back to the SQL Server 2008 Express with Tools installation and this time the Installation Rules passed the check.  Progress at last!  🙂

image

From there it was just a matter of clicking through the remaining wizard screens (and setting up some security) and it finally went through!

image

Wow.  That was a full day of work.  I finally got to run my SQL script at the end of the day, which took all of 30 seconds to complete.  Gotta roll with the punches, I guess.

Anyway, I sincerely hope this helps others out who have run into this same nonsense.  If you would like some more information on this problem, you can read more here and here.

November 28, 2009

Unit Testing Exceptions

Filed under: .NET,C#,Microsoft,Software Development,Visual Studio — Larry Parker @ 10:23 pm

Up until recently,  I had been following a pattern in my unit tests of catching expected exceptions that is similar to the following:

[TestMethod()]
public void AddTaskTest()
{
    Schedule target = new Schedule("* * * * *", "Every minute");
    ScheduledTask scheduledTask = null;

    Boolean isCaught = false;
    try
    {
        target.AddTask(scheduledTask);
    }
    catch (ArgumentNullException) { isCaught = true; }
    Assert.IsTrue(isCaught);
}

This works, but is a bit of a pain to write every time you want to check that an exception gets thrown by the method being tested.

I found a better approach at this blog post by Pedro Silva of Microsoft.

I modified it slightly to take a generic type parameter instead of passing in the type as a formal parameter (a little easier in my opinion).

Now the unit test looks like this:

[TestMethod()]
public void AddTaskTest()
{
    Schedule target = new Schedule("* * * * *", "Every minute");
    ScheduledTask scheduledTask = null;

    UnitTestHelper.TestException<ArgumentNullException>(() =>
        target.AddTask(scheduledTask));
}

Much simpler – especially when you’re testing for lots of exceptions!

I’m using a lambda expression in this example, but you can also use an anonymous delegate as in the blog.  I just think lambdas are more succint, but either will do.

Here’s the code with my tweaks (comments removed for brevity – please check the original blog post for more info).

public static class UnitTestHelper
{
    static public void TestException<T>(Action action)
    {
        try
        {
            action();
            Assert.Fail("Test should have thrown exception " +
                typeof(T).Name + ".");
        }
        catch (AssertFailedException) { throw; }
        catch (Exception e)
        {
            Assert.IsInstanceOfType(e, typeof(T),
                "Exception is not of the expected type.", typeof(T).Name);
        }
    }
}

August 25, 2009

Documenting Thread Safety

Filed under: .NET,C#,Microsoft,Software Development — Larry Parker @ 7:10 am

I have found that developers (including myself) typically write code to be thread-safe only when needed, as opposed to proactively making code thread-safe.  This is understood because writing thread-safe code is not always easy, especially when dealing with instance members.  Just look at the MSDN documention, and you’ll find the following disclaimer under most classes in the Thread Safety section:

Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

But once code has been written to be thread-safe, it’s often not very well documented as such.  When the code is revisited months (or even years) later, it’s not immediately evident if the code is thread-safe, or what measures were taken to make it thread-safe.

Taking a cue from a book I recently read on concurrency (Java Concurrency in Practice — see my blog post as well), I have created a few attributes that can be used to decorate your code to help document thread safety.

Attributes can be very helpful with documentation because they help enforce consistency, and can also be read programatically.  For example, we could write a utility that uses reflection to display all classes in an assembly that have been marked as thread-safe.

Before I insert the code that defines the attributes, I’ll give a quick example showing how they might be used.

I recently wrote a file synchronization utility that syncs up files across the public Internet.  Client machines periodically take snapshots of the folders under sync management and send them to the server, at which time the server compares these with its own recent snapshot.  In order to reduce I/O requirements on the server, snapshots of the server’s source folder are taken periodically via a timer and cached.  The timer fires on a thread from the thread pool, and the service calls are processed (via WCF) on threads from the thread pool as well.  Therefore, there’s definitely some concurrency going on, and the code needs to be thread safe.

The following is an excerpt from the File Sync Snapshot Manager class:

[ThreadSafe]
public class FileSyncSnapshotMgr
{
    // ...

    [Guards("_lastSnapshot, _lastDiff")]
    private Object _syncObj = new Object();

    [GuardedBy("_syncObj")]
    private FileSyncSnapshot _lastSnapshot;

    /// <summary>
    /// Gets the last snapshot stored in cache.
    /// </summary>
    public FileSyncSnapshot LastSnapshot
    {
        get { lock (_syncObj) return _lastSnapshot; }
    }

    [GuardedBy("_syncObj")]
    private FileSyncDiff _lastDiff;

    /// <summary>
    /// Gets the last snapshot diff stored in cache.
    /// </summary>
    public FileSyncDiff LastDiff
    {
        get { lock (_syncObj) return _lastDiff; }
    }

    // ...
}

Looking at the code, we see a few things.  The class is marked as thread-safe with the ThreadSafe attribute.  This is just an attribute for documentation purposes and doesn’t have any effect on the code.  But it tells us that someone marked the class as thread-safe, so we assume (or at least hope!) that the class is indeed thread-safe for its intended use.

We can also tell, by looking at the Guards attribute, that our _syncObject field guards the _lastSnapshot and _lastDiff fields.  Conversely, by looking at the GuardedBy attribute, we can quickly identify the sync object that guards a field.

In the case where a field is both the synchronization object and the object it guards, I use the text “self” to designate this.  For example:

[GuardedBy("self")]
private Queue<PackageCreationRequest> _packageCreationRequests =
    new Queue<PackageCreationRequest>();

None of this is very complicated, but I have found that some simple documentation can go a long way.  The hope is that when you (or another developer) revisits the code, that it will be easier to understand the intention behind what was done to make the code thread-safe.

The following is the code that defines the attributes.  Hope this helps.

/// <summary>
/// Represents an attribute that marks a class as thread-safe.
/// This is only for documentation purposes and does not
/// have any affect on the code's actual thread-safety.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
public class ThreadSafeAttribute : Attribute
{
}

/// <summary>
/// Represents an attribute that marks a class as not being thread-safe.
/// This is only for documentation purposes and does not
/// have any affect on the code's actual thread-safety.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
public class ThreadUnsafeAttribute : Attribute
{
}

/// <summary>
/// Indicates the synchronization object that guards this item.
/// </summary>
[AttributeUsage(AttributeTargets.Field)]
public class GuardedByAttribute : Attribute
{
    /// <summary>
    /// Initializes a new <see cref="GuardedByAttribute"/> object
    /// and sets the <see cref="SyncObjectName"/> property.
    /// </summary>
    /// <param name="syncObjectName">The name of the sync object.</param>
    public GuardedByAttribute(String syncObjectName)
    {
        SyncObjectName = syncObjectName;
    }

    /// <summary>
    /// Gets or sets the name of the synchronization object that guards this item.
    /// </summary>
    public String SyncObjectName { get; set; }
}

/// <summary>
/// Indicates the items that this synchronization object guards.
/// </summary>
[AttributeUsage(AttributeTargets.Field)]
public class GuardsAttribute : Attribute
{
    /// <summary>
    /// Initializes a new <see cref="GuardsAttribute"/> object
    /// and sets the <see cref="Items"/> property.
    /// </summary>
    /// <param name="syncObjectName">The name of the sync object.</param>
    public GuardsAttribute(String items)
    {
        Items = items;
    }

    /// <summary>
    /// Gets or sets a comma-separated list of items guarded by this synchronization object.
    /// </summary>
    public String Items { get; set; }
}

June 21, 2009

Extension Methods

Filed under: .NET,C#,Microsoft,Software Development — Larry Parker @ 9:30 pm

One really nice feature introduced in C# 3.0 (.NET 3.5 / Visual Studio 2008) is something called extension methods.  This was a language feature made to support LINQ, but you can also use it to write your own custom extension methods.

For example, with extension methods you can do something like this:

if (!"joe@smith.com".IsValidEmail())
    return false;

Without extension methods, this would not be possible because even if you could subclass from the String type (which you can’t because it’s sealed) and added the IsValidEmail method, the “joe@smith.com” literal would still be a string.

So extension methods can be very helpful in adding new functionality to existing types, but I also find them useful for changing the syntax of existing methods that just don’t seem to “make sense”.   One such method is the String.IsNullOrEmpty static method.

To use this, you need to do something like this:

if (String.IsNullOrEmpty(firstName))

That’s not very “programmer friendly” because you have to indicate the String class, call a method, and then finally pass in the string as the parameter.

Wouldn’t it make more sense to be able to do something like this?

if (firstName.IsNullOrEmpty())

Not only is it less to type, but it’s more intuitive because you’re calling a method on an instance variable, instead of passing the instance variable into a static method.

The good news is that with extension methods, this is very easy to do:

public static Boolean IsNullOrEmpty(this String value)
{
    return String.IsNullOrEmpty(value);
}

This is as simple as it gets because the implementation of this just calls the original static method.  But you can put anything you wish in your own extension methods – it’s your code.

Hope this helps.

June 11, 2009

Cannot Paste into Microsoft Virtual PC

Filed under: Microsoft,technology — Larry Parker @ 4:18 pm

I’ve been using Microsoft Virtual PC 2007 for various things, and it’s been working well.  But one thing that really annoys me is that I can’t copy from my host desktop machine and paste into the virtual PC (nor can I copy from the virtual PC and paste into the host machine).  This has become frustrating enough that I finally googled it and came up with this article.

The simple workaround is to just Remote Desktop into the virtual PC.  Works for me!  🙂

Windows XP SP2 Support Tools and httpcfg.exe

Filed under: Microsoft,technology — Larry Parker @ 11:51 am

I’m doing some work with WCF and SSL and need to configure a port with an SSL certificate on the server.  To do this, you need the httpcfg.exe utility, available with Windows XP SP2 Support Tools.

So I downloaded it, installed it, looked in C:\Program Files\Support Tools, and no httpcfg.exe.  What’s the deal?

It turns out that when you install Support Tools, you need to select Optional Tools from the setup wizard (it’s disabled by default).

untitled

So just make sure you select the feature to get httpcfg.exe (and the other optional tools).  Hope this helps.

June 10, 2009

Generating Method Stubs in Visual Studio

Filed under: .NET,Microsoft,technology,Visual Studio — Larry Parker @ 3:17 pm

I’ve been using Visual Studio for years and just stumbled upon a very useful feature – generating method stubs.  You can read more about it here, but say you’re in the middle of coding and want to call a method that you haven’t written yet.  That’s what I was just doing a few minutes ago, but instead of doing the usual and moving out of the current block of code in the editor to create a new method, I decided to just code the method call the way it seemed it should be.

Then I right-clicked on the method call for the unwritten method, and to my delight I saw this:

untitled

A Generate Method Stub menu item gets added to the context menu!  I clicked on it and the following code was automatically generated for me:

private static XElement TransformQueryElement(ushort queryNum, XElement origQueryElem)
{
    throw new NotImplementedException();
}

Exactly what I needed!  Thanks Microsoft.  🙂

May 28, 2009

Domain Account Login Problem on Virtual PC

Filed under: Microsoft,technology — Larry Parker @ 3:45 pm

I just tried logging into a virtual PC of mine (Microsoft Virtual PC 2007) using my domain account at my company and got the following error:

untitled

My domain account worked before, so something must have changed but I couldn’t figure out what.

A quick Google search turned up this article which describes the same problem I was having, including the solution.

Turns out that you just need to take the virtual pc off the domain and then rejoin.  Now I’m in business!

But you still need a way to log into the virtual pc with administrator rights, so it’s important to have a local account for that.

Hope this helps.

Create a free website or blog at WordPress.com.