I ran into a problem today where I was trying to set up a SqlDependency against a table, with what I thought was a plain vanilla select statement:
private const string SqlCommandText =
"Select ImportDate From dbo.Imports Where ImportDate = '{0:yyyyMMdd}'";
I was formatting this string with a date/time value at runtime, then passing that into my SqlCommand object, then attempting to register the dependency. Well guess what - it didn’t work! The SqlNotificationEventArgs class kept telling me that my statement was invalid. Checking the special considerations using query notifications, I couldn’t see anything wrong with my query, so I was a bit lost.
Anyway, I decided to axe the “Where” condition from my query, and sure enough, it worked! So, by process of elimination, I figured it was something to do with converting a date from a character string that was throwing it. Not sure why; this works fine when run as T-Sql, or within a normal query…
To get around this problem, I used the “best practice” approach of using a parameter in the SqlCommand object:
private const string SqlCommandText =
"Select ImportDate From dbo.Imports Where ImportDate = @ImportDate";
protected SqlCommand CreateSqlCommand() {
var command = new SqlCommand(SqlCommandText);
command.Parameters.Add(new SqlParameter("ImportDate", SqlDbType.DateTime) {
Value = PositionDate
});
return command;
}
To my surprise, this worked a treat! I guess in the end, it wasn’t all that surprising, however I for some reason thought that using a parameter would surely not work; hence the reason I was pre-formatting the date/time in the first place!
One of my all time favourite features about FireFox is the Web Developer Toolbar, which makes life much simpler when you’re trying to figure out problems with your web pages. Up until now, internet explorer hasn’t offered anything that’s quite so concise and easy to use, which makes FireFox the easy choice for web developers everywhere.
Well, now that Internet Explorer 8 Beta 2 has been released, the choice is no longer so clear. IE8 now includes “Developer Tools” which, so far, look like an absolute gem.
So far, I’ve only played with the script debugger, which works pretty much as you would expect, and handily uses the same keyboard shortcuts as Visual Studio. The CSS debugger looks great too - you can selectively turn on/off different parts of your stylesheet using the checkbox next to each style declaration.
Though I’m still a long way off giving up FireFox, I’m happy to see that Internet Explorer is finally offering something that will at least tempt me to use it sometimes.
Many of the controls in ASP.Net (e.g. a Repeater) support the concept of an AlternatingItemTemplate, which, as the name suggests, allows you to define an additional item template to change the look and feel for each alternating item in the data source. This is all well and good, but I’ve never seen a good use for it; more often than not, all you really want to do in your alternating item is, for example, slightly change the background colour for ease of visual differentiation.
Though you can use the alternating item template for this, it typically involves you duplicating a lot of code, since the AlternatingItemTemplate is mostly the same as your ItemTemplate (save perhaps for a CSS class declaration somewhere).
<asp:Repeater ID="rpt" runat="server">
<HeaderTemplate>
<table cellpadding="0" cellspacing="0">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("FirstName") %></td>
<td><%# Eval("LastName") %></td>
<td><%# Eval("Age") %></td>
</tr>
</ItemTemplate>
<AlternatingItemTemplate>
<tr class="Alternating">
<td><%# Eval("FirstName") %></td>
<td><%# Eval("LastName") %></td>
<td><%# Eval("Age") %></td>
</tr>
</AlternatingItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
If this sounds like you, then never fear - there IS a better way!
When you’re binding, you have access to the RepeaterItem via the Container property, which contains an ItemIndex property. As such, the simplest way of alternating your items is simply to check if the number divides evenly by two:
<asp:Repeater ID="rpt" runat="server">
<HeaderTemplate>
<table cellpadding="0" cellspacing="0">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr class="<%# Container.ItemIndex % 2 == 0 ? "Alternating" : String.Empty %>">
<td><%# Eval("FirstName") %></td>
<td><%# Eval("LastName") %></td>
<td><%# Eval("Age") %></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
There is a minor downside using this approach - the non-alternating rows will all declare an empty CSS class within them. But, this is a sacrifice I think is acceptable to decrease repetition of code.
This is actually quite straightforward, but something that perhaps you may not have thought about.
On my current project, I have the concept of a “PerishableObject” - an object whose value is only valid between two particular dates. The interface for an IPerishable looks something like this:
public interface IPerishable {
/// <summary>
/// Get/Set the date that this component is valid from
/// </summary>
DateTime? ValidFrom { get; set; }
/// <summary>
/// Get/Set the date that this component is valid until
/// </summary>
DateTime? ValidTo { get; set; }
}
Now, logically, I wanted to create a helper method called “IsValidOn”, which could be passed a date, and would return true/false indicating if the component is valid on the supplied date. Obviously, I could define this in the interface, but that would leave me to either implement the method on every object which implements the interface, or to create a common base class which implemented that method, and then force all perishable objects to inherit from this base class. Both of these are not desirable!
Thankfully, extension methods in C# 3.0 provide a perfect solution for this:
/// <summary>
/// Determines if the perishable component is valid on the given reference date
/// </summary>
/// <param name="component">The component to be tested</param>
/// <param name="referenceDate">Reference date to test</param>
/// <returns><c>true</c> if the perishable component is valid on the given reference date</returns>
static internal bool IsValidOn(this IPerishable component, DateTime? referenceDate) {
if (!referenceDate.HasValue) {
return true;
}
return (!component.ValidFrom.HasValue || component.ValidFrom.Value <= referenceDate)
&& (!component.ValidTo.HasValue || component.ValidTo.Value >= referenceDate);
}
Defining extension methods against an interface is a great way of extending the interface without bulking it up.
It’s been a while since anyone has posted a daily question, but here’s one to get y’all in the mood…
Given the following code:
public class BaseClass {
public BaseClass() : this("Base value") {
Console.WriteLine("Base: Empty");
}
public BaseClass(object value) {
Console.WriteLine("Base with value: {0}", value);
}
}
public class DerivedClass : BaseClass {
public DerivedClass() : this("Derived value") {
Console.WriteLine("Derived: Empty");
}
public DerivedClass(object value) : base(value) {
Console.WriteLine("Derived with value: {0}", value);
}
}
What will be printed to the console when a new DerivedClass object is created using the default DerivedClass constructor:
new DerivedClass();
First person to post the correct answer wins a prize consiting solely of that warm fuzzy feeling you get by being the first person to answer a question correctly.
I’ve been focusing a lot (read: “learning”) on WPF lately, and one thing that crops up all the time is StaticResource and DynamicResource. I had tried to infer their usage/differences from the context of where I’d seen them used, but I could never quite get it right. Anyway, I just read a nice definition which makes it all rather clear:
Static resources are resolved at compile time, whereas dynamic resources are resolved at runtime.
Use DynamicResources when the value of the resource could change during the lifetime of the Application.
Use StaticResources when it’s clear that you don’t need your resource re-evaluated when fetching it – static resources perform better than dynamic resources.
My latest contract has seen my development time focus strongly on Sql Server, Xml and C# server side code.
However, lately I’ve been playing around with all the new Asp.Net 3.5 extensions (MVC) and Linq with VS 2008 and found that I could use a refresher course in all things Javascript - particularly Ajax and JSON.
I found this awesome guide which gives you a quick reminder of the useful techniques required to author some top notch client side code when building web apps.
If you want to run sql server scripts through code, you can’t just run a standard ExecuteNonQuery() with a SqlCommand. There’s problems with ExecuteNonQuery() recognizing multiple sql statements.
Don’t fear though, if you reference the Microsoft.SqlServer.Smo and Microsoft.SqlServer.ConnectionInfo assemblies you get access to some goodies that’ll help you on your way!
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBName"].ConnectionString);
Server server = new Server(new ServerConnection(connection));
server.ConnectionContext.ExecuteNonQuery(File.ReadAllText("SqlScript.sql"));
A classic problem to unit testing code that modifies the underlying data in the database tables is that you need to find a way to revert back to the original database state so that the tests can be run over and over again.
Using the transaction capabilities provided with the .Net 2.0 framework and a unit testing framework you can achieve this easily.
The process:
- Create a new transaction before each test.
- Dispose (Rollback) the transaction after each test.
using System.Data;
[TestClass]
public class DataProviderTest {
private readonly DataProvider _dp = new DataProvider();
private TransactionScope _transactionScope;
[TestInitialize]
public void TestInitialize() {
_transactionScope = new TransactionScope();
}
[TestCleanup]
public void TestCleanup() {
_transactionScope.Dispose();
}
[TestMethod]
public void InsertTest()
{
// modify the database
...
}
}
It’s been a while since I’ve had the opportunity to catch up on what’s been happening in the Ent.Lib space.
I was pleasantly surprised to find two awesome new application blocks included in Ent.Lib 3.x versions:
- The Policy Injection App Block
- The Validation Application Block
The policy injection app block addresses Aspect Oriented programming concepts - the ability to affect code across systems using policies.
Check out a great introduction powerpoint show here.
The validation app block allows you to configure validation logic around members and methods.
You can find some details about the Validation App Block and all the latest Ent.Lib features here.