SQL – find by text

Many moons ago (at least 18 months ago), I had a stored procedure that let me search for text in DML in the databases. Yeah, so I could search for “Order” and it would find all mentions in SPs, functiosn etc.

Here is my new version:

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED 

SELECT
        SUBSTRING (qt.text,(qs.statement_start_offset/2) + 1,
        ((CASE WHEN qs.statement_end_offset = -1
        THEN LEN(CONVERT(NVARCHAR(MAX), qt.text)) * 2
        ELSE qs.statement_end_offset
        END - qs.statement_start_offset)/2) + 1) AS [Individual Query]
, qt.text AS [Parent Query]
, DB_NAME(qt.dbid) AS DatabaseName
, qp.query_plan
FROM sys.dm_exec_query_stats qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) as qt
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qp
WHERE SUBSTRING (qt.text,(qs.statement_start_offset/2) + 1,
        ((CASE WHEN qs.statement_end_offset = -1
        THEN LEN(CONVERT(NVARCHAR(MAX), qt.text)) * 2
        ELSE qs.statement_end_offset
        END - qs.statement_start_offset)/2) + 1)
LIKE '@searchtext'
and DB_NAME(qt.dbid) = @database
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Posted in Uncategorized | Comments Off

Dependency Injection with Unity: passing runtime parameters

Today, I had a problem of how to construct an object passing a specific date into the constructor. Normally, this is not an issue encountered frequently as only “services” are passed via constructor injection. This time however, I needed to make sure a date was passed when the object was created, and this date needs to be evaluated each time.

I’m not a fan of the “initialise” pattern, so that was out. Here is how I solved the problem using Unity DI Container.

First, I defined a dependency and an implementation:

    public interface IService
    {
        void DoSomething();
    }

    public class Service : IService
    {
        private readonly DateTime date;

        public Service(DateTime date)
        {
            this.date = date;
        }        

        public void DoSomething()
        {
            Console.WriteLine(date);
        }
    }

Then, configure the container, and attempt to make some calls:

IUnityContainer container = new UnityContainer();
container.RegisterType<IService, Service>(
  new InjectionConstructor(
    new InjectionParameter<DateTime>(DateTime.Now)
  ));

var dateService = container.Resolve<IService>();
// prints datetime container was configured
dateService.DoSomething(); 

Console.Read();
// still datetime container was configured
dateService.DoSomething();

Ok, so this is not doing what I wanted. The DateTime is being captured. This is not surprising, as the value is copied into the constructor.

If we resolve the item from the container again, we still get the same value:

dateService = container.Resolve<IService>();
// still datetime container was configured with
dateService.DoSomething();

This was annoying, it seems we need some sort of factory or delegate that is resolved each time the object is constructed:

    public interface IDateFetchingFactory
    {
        DateTime GetDate();
    }

    public class DateFetchingFactory : IDateFetchingFactory
    {
        public DateTime GetDate()
        {
            return DateTime.Now;
        }
    }

    public class Service2 : IService
    {
        private readonly IDateFetchingFactory dateFetchingFactory;        

        public Service2(IDateFetchingFactory dateFetchingFactory)
        {
            this.dateFetchingFactory = dateFetchingFactory;
        }

        public void DoSomething()
        {
            Console.WriteLine(dateFetchingFactory.GetDate());
        }
    }

Now we can register our new type:

container.RegisterType<IService, Service2>("Service2");
container.RegisterType<IDateFetchingFactory, DateFetchingFactory>();

and each time we make a call, we get the behaviour we wanted:

dateService.DoSomething(); // datetime when method call was made via factory
Console.Read();

dateService.DoSomething(); // a different datetime from factory

There must be other ways of achieving this, is there a better way?

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Posted in Uncategorized | Comments Off

Flexible layout with WPF GridSplitter

Here is a quick sample showing how it is possible to create a flexible resizeable layout in WPF with a GridSplitter. Here we see how you can change the size of panes in a vertical and horizontal direction.

And the Xaml:

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
   <Grid>
      <Grid.RowDefinitions>
         <RowDefinition Height="*"/>
         <RowDefinition Height="Auto"/>
         <RowDefinition Height="*"/>
      </Grid.RowDefinitions>
      <Grid Grid.Row="0">
         <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition/>
         </Grid.ColumnDefinitions>
         <Label Grid.Column="0">Row 0, Column 0</Label>
         <GridSplitter
            Width="5"
            Grid.Column="0"
            Background="Blue"
            ShowsPreview="True"/>
         <Label Grid.Column="2">Row 0 Column 2</Label>
      </Grid>
      <GridSplitter
         Height="5"
         Grid.ColumnSpan="3"
         Grid.Row="1"
         HorizontalAlignment="Stretch"
         VerticalAlignment="Stretch"
         Background="Black"
         ResizeDirection="Rows"
         ShowsPreview="true"/>
      <Grid Grid.Row="2">
         <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition/>
         </Grid.ColumnDefinitions>
         <Label Grid.Column="0">Row 2, Column 0</Label>
         <GridSplitter
            Width="5"
            Grid.Column="0"
            Background="Blue"
            ShowsPreview="True"/>
         <Label Grid.Column="2">Row 2 Column 2</Label>
      </Grid>
   </Grid>
</Page>
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Posted in Uncategorized | Comments Off

NUnit Constraints

For some reason, I have ignored the NUnit syntax around Assert.That up to now. I thought it was one of these experiments around a fluent interface which didn’t offer any advantages over the existing API.

I wanted to write a test that tested whether a value was as expected, but within a certain range. I had previously used Assert.Equals with the overload that takes a delta.

Here is an alternative implementation:

[Test]
public void MinValue_IsCloseToMinimum_OfAllBids()
{
var lowPrice = new Price(10, 20);
var otherPrice = new Price(11, 20);

var priceViewModel =
new PriceViewModel(new List {lowPriceTolerance, otherPriceTolerance});

//old api
Assert.AreEqual(10, Convert.ToDouble(priceViewModel.MinValue), 0.2);

// new api
Assert.That(priceViewModel.MinValue, Is.EqualTo(10).Within(0.2));
}

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Posted in Uncategorized | Comments Off

Javascript Learning Resources

I am making a concerted effort to really *learn* javascript at the moment.
There are a load of great resources out there.

Here is the beginnings of a list:

Douglas Crockford’s Home Page
JavaScript Garden – advanced topics
Learn JavaScript by making tests pass
Mozilla JavaScript reference
JQuery Guide
Run JavaScript in your browser with jsfiddle
Another online IDE

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Posted in Uncategorized | Comments Off

Contrawhatywho – nicer generics in C# 4.0

Everyone probably knows this already, but it’s probably easy to miss as *stuff now just works*. Contravariance, or covariance is now improved to make working with generics that little bit simpler.

The following code now compiles fine in .net 4, but won’t compile against .net 3.5:

class Program
{
static void Main(string[] args)
{
Animal a = new Animal();
Bear b = new Bear();
IList<Bear> bears = new List<Bear>();
bears.Add(b);
IEnumerable<IAnimal> animals = bears;
}

class Animal : IAnimal
{
public override string ToString()
{
return “I am an animal”;
}
}

   class Bear : IAnimal
   {
       public override string ToString()
       {
           return "I am a bear";
       }
    } 

    internal interface IAnimal
    {
    }
}
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Posted in Uncategorized | Comments Off

Console2 and Cygwin – how to setup

So, I’ve set up my console how Scott Hanselman recommended.

This is how I managed to get Cygwin to work correctly as a shell.

You just need to set your shell to:

%cygwin-path%\bin\bash.exe --login -i
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Posted in Uncategorized | Comments Off

XCopy your dependencies in a pre-build step

Ok, again – this isn’t really ground breaking or anything, but if you have a load of dependencies that you need to copy at build time to your bin folder, this is a nice script that goes into the pre-build events section of visual studio.

xcopy ..\..\..\lib\whateverframework\*.* . /E /D

The really neat part, is the /D switch  - this only copies files that have changed since they were last modified.

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Posted in Uncategorized | Comments Off

Distinct in Linq

Sometimes, in .net it can get a bit confusing about which interface you need to implement for to get object equality to work correctly. When using the Distinct extension method in Linq, IEqualityComparer<T> is very useful

var items = new List<Cheese>();
items.Add(new Cheese { Name = "Cheddar" });
items.Add(new Cheese { Name = "Cheddar" });
items.Add(new Cheese { Name = "Red Leicester" });
items.Add(new Cheese { Name = "Stilton" });
var distinct = items.Distinct();	

foreach (var item in distinct) {
    Console.WriteLine (item.Name);
}

//outputs
// Cheddar
// Cheddar
// Red Leicester
// Stilton

The key part is implementing GetHashCode so that the two objects will return the same hash code.

An example implementation:

class CheeseNameComparer : IEqualityComparer<Cheese> {	

 public bool Equals (Cheese x, Cheese y)	{
  return x.Name == y.Name;
 }

 public int GetHashCode (Cheese obj) {
  return obj.Name.GetHashCode();
 }
}

distinct = items.Distinct(new CheeseNameComparer());
foreach (var item in distinct) {
  Console.WriteLine (item.Name);
} 
//outputs
// Cheddar
// Red Leicester
// Stilton
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Posted in Uncategorized | Comments Off

Finding Stuff

A little bit of unix command knowledge can often save a stack of time even on a windows box. This little snippet was really useful when I was trying to find out which file a function was declared in:

find . -name "*.h" | xargs grep textToSearchFor
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Posted in Uncategorized | Comments Off