Tag Archives: C#

WPF simulate mouse click in code behind

Let’s say there is an event captured on a control and you want to simulate a click of a button to fire whatever that button is bound to do, there are a few ways of doing this, one that I’ve used before is using an AutomationPeer:

AutomationPeer button1AP = UIElementAutomationPeer.CreatePeerForElement(button1);
(button1AP.GetPattern(PatternInterface.Invoke) as IInvokeProvider).Invoke();

Another option is to use:
button1.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));

SQL Server: Bulk updates, bulk inserts and table valued parameters for arrays

When writing bulk updates or inserts into Oracle with ODP.NET you can use PLSQLAssociativeArray (example here) and you may search around for an equivalent array type in SQL Server but there isn’t one. Firstly this is disappointing, then you kind of get used to the idea, hopefully this post will help you on onto this path.
First off I thought it was wrong not to have an array type, “Oracle does, this is stupid” I thought. After a cup of tea, I put a couple of seconds thought into this and the best I could come up with is all the data we use in SQL is tabular data anyway and you could represent a PLSQLAssociativeArray as a table with one column right? So is it any loss? No, of course not, but the programmer in me is used to dealing with arrays.
However there is a drawback that I haven’t completely got over yet, and that is that you must define the type name of the SqlParameter, this must be a valid type, so randomly creating some SQL and firing it at the database isn’t an option. But I have other options in my mind, here’s some examples of bulk operations utilizing table valued parameters:

Create a table to manipulate:

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Greetings](
	[PrimaryId] [int] NOT NULL,
	[FirstValue] [nchar](10) NULL,
	[SecondValue] [nchar](10) NULL
) ON [PRIMARY]

GO

Create a loosely typed DataTable and populate it with some data to insert into the table:

DataTable dt = new DataTable("Tim");
dt.Columns.Add(new DataColumn("FirstCol", typeof(int)));
dt.Columns.Add(new DataColumn("SecondCol", typeof(String)));
dt.Columns.Add(new DataColumn("ThirdCol", typeof(String)));

DataRow r1 = dt.NewRow();
r1["FirstCol"] = 1;
r1["SecondCol"] = "Hello";
r1["ThirdCol"] = "Hi";
dt.Rows.Add(r1);

DataRow r2 = dt.NewRow();
r2["FirstCol"] = 2;
r2["SecondCol"] = "Goodbye";
r2["ThirdCol"] = "Bye";
dt.Rows.Add(r2);

(brings back memories of .NET 1.1 doesn’t it)

Next up create a table valued type in SQL Server, of course you could keep well defined types in your database, but for this example I just want something “temporary”. Also this could be a generated string from the DataTable, look around someone might already be doing this, else it’s easy enough to roll your own

using (SqlCommand cmd = conn.CreateCommand())
{
    cmd.CommandType = CommandType.Text;
    cmd.CommandText =
        "BEGIN TRY"
        + " CREATE TYPE dbo.T1"
        + " AS TABLE ( [FirstCol] [int] NOT NULL, [SecondCol] [nchar](10) NULL, [ThirdCol] [nchar](10) NULL )"
        + " END TRY"
        + " BEGIN CATCH"
        + " END CATCH";
    cmd.ExecuteNonQuery();
}

So by this point in execution your app would have a type defined called dbo.T1, you could of course use a temporary generated name for this too. Note the TRY CATCH in there; ignoring errors.

Next do a bulk insert: (Note: SqlBulkCopy may be quicker, I’ve not checked)

using (SqlCommand cmd = conn.CreateCommand())
{
    SqlParameter p = new SqlParameter("@MyInputDT", SqlDbType.Structured);
    p.Value = dt;
    p.TypeName = "dbo.T1";
    cmd.Parameters.Add(p);
    cmd.CommandType = CommandType.Text;
    cmd.CommandText =
        "INSERT INTO dbo.Greetings (PrimaryId, SecondValue)"
        + " SELECT FirstCol, ThirdCol"
        + " FROM @MyInputDT";
    cmd.ExecuteNonQuery();
}

This to me is better than passing two arrays, a size parameter and looping though and inserting each. But we’ve got SqlBulkCopy, so you may not want to use this approach.

By this point in execution there would be two new entries in the dbo.Greetings table but I’ve deliberately missed out the FirstValue, so that will be NULL.

Let’s do a bulk update to fix it, also remove the “temporary” table valued type:

using (SqlCommand cmd = conn.CreateCommand())
{
    SqlParameter p = new SqlParameter("@MyUpdDT", SqlDbType.Structured);
    p.Value = dt;
    p.TypeName = "dbo.T1";
    cmd.Parameters.Add(p);
    cmd.CommandType = CommandType.Text;
    cmd.CommandText =
        "UPDATE Greetings"
        + " SET FirstValue = SecondCol"
        + " FROM @MyUpdDT"
        + " WHERE PrimaryId = FirstCol"
        + " BEGIN TRY"
        + " DROP TYPE dbo.T1"
        + " END TRY"
        + " BEGIN CATCH"
        + " END CATCH";
    cmd.ExecuteNonQuery();
}

So there’s a bulk insert and bulk update, I think this is pretty neat, but the requirement on having a well defined type is a gripe, now I’m over the lack of array type I want a var type now, shame.

See also Table-Valued Parameters in SQL Server 2008 (ADO.NET)

Shell32 Interop DLL Generation

As far as I’m aware you’ve got two choices when you want to call non .NET assemblies, DllImport or Interop.

For DllImport you’ll want to consult pinvoke.net.

But that DllImport syntax isn’t for everyone, some like to pretend we are working with .NET assemblies and want to use an Interop DLL, but how?

First you need to generate one using Tlbimp.exe (Type Library Importer)
For example
c:\Windows\System32>tlbimp shell32.dll /out:me.dll
Microsoft (R) .NET Framework Type Library to Assembly Converter 3.5.30729.1
Copyright (C) Microsoft Corporation. All rights reserved.
Type library imported to c:\Windows\System32\me.dll

Now just include the me.dll in your project (as a normal .NET assembly reference), stick a “using Shell32 = me;” / “Import Shell32 = me” in your source code and voila, Shell32.Folder etc is at your disposal.

Note: retrospectively thinking, don’t generate the dll into System32, you’re just asking for trouble.

Unit Test Projects and NUnit compatibility

I often need to write Unit Tests and have them accessible from NUnit as well as the Visual Studio Test View (etc), so I thought I’d write myself a walkthrough of the common things I have to do.

Firstly, whichever language I’m using, Visual Studio is normally configured to create the wrong one, so let’s say I’ve got my C# hat on and I create a test project:

Darn it, it’s created a VB.NET one, so I delete it and search for the setting or way I create a C# one. This can be located under Tools -> Options -> Test Tools -> Test Project, then choose your preference from the “Default test project language” dropdown, like so:

You will also notice you can choose what (if any) template test classes are created for you. 99% of the time I use Unit Test and that is it.
So you go back in and create the project again and it’s created a C# one, it automatically adds a reference to the Visual Studio Test classes, great:

Add a reference to NUnit, so you have:

Now let’s look at the Unit Test class, I’ve stripped it down to the bare bones:

using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace TestProject1
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
        }
    }
}

Since we don’t want the Visual Studio and the NUnit classes to conflict my approach is to take out the Visual Studio using statement like so:
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;

namespace TestProject1
{
    [Microsoft.VisualStudio.TestTools.UnitTesting.TestClass]
    public class UnitTest1
    {
        [Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod]
        public void TestMethod1()
        {
        }
    }
}

Now this will still work as before, but we can add NUnit in now too, like so:

using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;

namespace TestProject1
{
    [Microsoft.VisualStudio.TestTools.UnitTesting.TestClass]
    [TestFixture]
    public class UnitTest1
    {
        [Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod]
        [Test]
        public void TestMethod1()
        {
        }
    }
}

And proof of the pudding, Visual Studio:

NUnit:

This also reminds me, while I’m on the subject, to be able to open a Visual Studio project from within NUnit there is a setting you need to change, go to Tools -> Settings -> IDE Support -> Visual Studio and then tick the “Enable Visual Studio Support” checkbox, like so:

Null coalesce operator

Null coalesce operators:

C# – ??

int? myVar = null;
System.Console.Write(myVar ?? 0);

VB.NET – If ()

Dim myVar As Nullable(Of int) = Nothing
System.Console.Write(If(myVar, 0))

Ternary Operators

Ternary Operators:

VB.NET – IIf ()

IIf (predicate, valueiftrue, valueiffalse)

C# – ?:

predicate ? valueiftrue : valueiffalse

Asynchronous code execution in .NET 2.0 – BackgroundWorker

When TPL (.NET 4.0) is not available and you want to asynchronously do some work you can resort to .NET 2.0:

BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += delegate(object s, DoWorkEventArgs args)
{
  // Do something here, any local variables you use will be cloned
};
worker.RunWorkerAsync();

See MSDN BackgroundWorker Class

Call private or internal constructors using reflection

Sometimes you want to get past the object oriented barriers that C# throws up.
A while ago now I wanted to instantiate a class that only had internal constructors, here is a useful snippet of how I achieved this:
// Use reflection to call private or internal constructors
Type ty = Type.GetType("assembly.name.space.name.myclass, assembly.name.space.name, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
ConstructorInfo ctor = ty.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic)[0];
var inst = ctor.Invoke(new object[] { param1, param2 });

XPath to return non-empty values

This is an example of an XPath I’ve used before to get the nodes with a non-empty attribute:
// Where rows have a non-empty subtag called field with a name attribute equal to attrib1, select the rows
XmlNodeList nodeList = xmlDocument.SelectNodes("./idc:row[./idc:field[@name='attrib1'][text()]]", xmlnsmgr);

Note: the key part in this XPath is the text() part.

I’m not totally convinced this is the correct XPath to be using.
Of course there is also the node() function.
Combining these with not (e.g. not(node())) may yield the correct way to do it.

For further information try:
W3C XML Path Language (XPath) Spec
MSDN XmlNode.SelectNodes Method

.Net Parse DateTime from String

I’m always forgetting the exact way to parse a DateTime from a String, so I’ll put it down in writing here so I can easily find it next time:
// E.g. 13 Jan 2010 15:30:01:123
DateTime.ParseExact(dateString, "dd MMM yyyy HH:mm:ss:fff", CultureInfo.CreateSpecificCulture("en-GB"))

For the format string see MSDN Custom Date and Time Format Strings