Tuesday, September 28, 2010

Control catalog name when using AttachDBFilename

I was using the AttachDBFilename and discovered that the database name ended up being the full path of the file being attached.

Setting InitialCatalog as well enable me to control the catalog name of the attached file.

var cb = new SqlConnectionStringBuilder {
IntegratedSecurity = true,
DataSource = ".\MyInstance",
AttachDBFilename = @"c:\mypath\mydb.mdf",
InitialCatalog = "mydb catalog name"
};

Thursday, September 23, 2010

Visual studio designer hangs and fails to load ToolStripControlHost derived class

I found a problem using a ToolStripControlHost derived class when the class is being built in the same solution as the form that uses the component.

When performing a rebuild the designer would freeze and wouldn't redraw the toolbar. The fix I discovered solves the problem where the designer disposes the object and then attempts to access it after the rebuild.

public class CustomButtonToolStripHost : ToolStripControlHost
{
public CustomButtonToolStripHost ()
: base(CustomToolStripButton())
{
}
/// Used to overcome a designer error when rebuilding the project.
private class CustomToolStripButton : Button // Replace with your control
{
/// Override CreateHandle to avoid exception if called when object is disposed.
/// This occurs when the designer updates after a rebuild.

protected override void CreateHandle()
{
if (!IsDisposed)
{
base.CreateHandle();
}
}
}
}

.Net button that doesn't take/steal focus

This is a simple solution that I've came up with after some thinking:

public class MyButton : Button
{
public MyButton()
{
if (!DesignMode)
{
SetStyle(ControlStyles.Selectable, false);
}
}
}

Much easier than trying to handle mouse activation messages etc...

Tuesday, March 23, 2010

Isolation from database

So I'm working on a legacy project and quite intent to re-factor the heck out of it. One of my goals was to make the code testable and to do that I had to rip out the dependency on the database/DataSet implementation.

To do this I created a data provider class and then implemented an iterator block and used the yield statement.

public override IEnumerable MyDataObjects
{
get
{
using (var connection = new SqlConnection(ConnectionString))
{
connection.Open();
using (var command = new SqlCommand{CommandText = "...", Connection = connection })
{
using (var reader = command.ExecuteReader())
{
while (reader != null && reader.Read())
{
yield return new MyDataObject
{
//extract the column values
};
}
}
}
}
}
}


Now the consumer of the data doesn't know where the data is coming from and that's just fine!

foreach(var myData in provider.MyDataObjects)
{
//do stuff with the object
}