Sunday, December 13, 2009

E-mail reporting from Maintenance tasks in SQL Server 2008

Submit this story to DotNetKicks

Just migrated two databases to a new 2008 server, when I discovered something weird: You cannot choose in any way to alert operators on error in the maintenance plan. Under reports settings, there is a checkbox, but it's disabled, and I found that other users are not able to check it either. Plus it only allows you to send a report every time. Which is not what I want...

The only workaround I found applies to scheduled tasks, which I guess is reasonable - if you run the job manually, you shouldn't need an e-mail to see if it failed. SQL Server creates a job for you, that runs the task, and for jobs, you can set the Notification properties to send an e-mail.

Wednesday, December 9, 2009

Sending XML input to a web method expecting a string

Submit this story to DotNetKicks

I'm working on a project where I receive data in XML format. So far I have been using the auto-generated .asmx front-end form to send inn small XML one-liners just for testing my parsing logic.

But when I wanted to use soap UI to send in larger portions, not to mention being able to save the whole scenario for later use, I ran into a problem. Whatever I sent in I only got "#status# HTTP/1.1 400 Bad Request".

Even just sending just the XML declaration gave me this problem!

But when I sent the exact same string from the auto-generated form, it was working perfectly. Which led me to believe there was (as usual) someone working behind the scenes, doing things without asking me.

Finally I found a post with the answer I was looking for.

In short, wrap your XML inside a CDATA section, and you're good to go.

Thursday, June 11, 2009

How to get the values of an enum?

Submit this story to DotNetKicks

Sometimes you need to list the values of your enums. Typically, I have to represent them in dropdown-boxes for a web page. Here's my solution:

public static ListItem[] GetEnumValues(Type t)

{

List<ListItem> lc = new List<ListItem>();

lc.Add(new ListItem() { Text = "Choose an item", Value = "-1" });

if (t.UnderlyingSystemType.BaseType == typeof(System.Enum))

{

foreach (int value in Enum.GetValues(t))

{

lc.Add(new ListItem() { Text = Enum.GetName(t, value), Value = value.ToString() });

}

}

return lc.ToArray();

}


Then, to use it in a control, use the Items.AddRange() function:

_dropdown.Items.AddRange(SomeClass.GetEnumValues(typeof(myEnumType)));

Plain and easy, but as far as I know, not available directly from .NET.

Monday, June 8, 2009

Finding stuff in Visual Studio 2008

Submit this story to DotNetKicks

Usually when I try to find something in my code, instead of relying on my memory to help me locate it, I just press Ctrl+F on my keyboard, and let Visual Studio do the finding. If you didn't already know, you can also press Ctrl+H and go directly to the replace dialog (where you can search with wildcards, but you can't replace with them - that would have been a nice feature!).

However, the find and replace dialog is a pretty powerful tool to locate stuff in your code, if you know how to use the options: Match case, match whole word, Search up, Search Hidden text, and Use. The first four are pretty straight-forward but if you don't know them or understand them from their names, here's a very quick update:
Match case - if you write CONST, VS will not find const, Const or COnSt.
Match whole word - if you write sum, VS will only find that, and not summary.
Search up - default is down, but you can search up. "Search up" feels buggy for me if you search in anything else than current document.
Search hidden text - collapsed or otherwise hidden sections


Wildcards
If you check the "Use" checkbox, you can select an option from the dropdown, either Wildcards or Regular Expressions. Let's try the first one first, it is by far the easiest and for my part, most used. Wildcards are ?, * and #, ? representing a single character, # a single digit, and * being pretty much anything, like you would expect.

If you want to find a single digit, you can search for #, double digit is ##, and you get the picture. The same goes for ?, search for ?nt and get and, int, ent... I really don't use it that much. If you'd like to find all numbers in their forties, type 4# and there they are. Or use Int## if you would like to avoid other types of Int in your code. Might come in handy if you are looking for that special number...

The * is my favorite. If I'm looking through a project to find a string that says "Sql-something", I'll just write Sql* and go. That's not very much different from searching for Sql without checking "Match whole word" though, so try finding "*yste*" and see if you find System. Or combine with # and ? for interesting effects.

You can even look for things like using( ... ), search for "using(*)" will help you. Tip: What if you want to find places you aren't using using? Search for example for *Connection(); or *Context(); - the semicolon will not be there if there is a using( ) wrapped around it. Or even search for new *(); to find any instance of an object that's not inside a using block.

And if you do want to search for # or * or ? in your code, and still use the wildcards, you can escape the characters using the backslash (\).

Regular expressions
For the regular expressions, or regex as most developers call them, there is a very good cheat sheet available at addedbytes.com (previously ilovejackdaniels.com). It's a very powerful feature, but thankfully I don't come across many situations where I need it.

Microsoft has a reference to some short-hand expressions that VS understands,

You could imagine having to find e-mail addresses referenced in an old app that you have inherited from another developer, who was fond of using @ in his code, perhaps in sql script written inline? You could go with regex and find only valid e-mail addresses. Or hex numbers, or all caps or all lowercase or enclosed in quotes, any kind of text that matches a given pattern.

Friday, May 29, 2009

Performance testing of Dictionary, List and HashSet

Submit this story to DotNetKicks

Update June 4, 2009
The original post favored Dictionary as the fastest data structure both for add and contains. After some debate and some re-runs of my test code, I found the result to be wrong. HashSet is faster. Probably the results were affected by the workload on my computer. I ran one List test, then a Dictionary test and finally a HashSet test - I should have run them multiple times and at the same workload (i.e. no programs or processes running). Anyway, on to the article.

Still working with high-volume realtime datafeeds, I'm struggling to understand where the bottleneck in my code is. It's not with the database, it's not with the network - it's somewhere in the code. Now that doesn't help a lot.

So I decided to have a look at the different data structures that could be usable for my needs. Right now I'm using a List to keep track of my orders, and each time I get a new order, I check that list for the given ID.

So I'm starting to wonder, maybe there is a performance issue with the List data structure. So I made a small test with the following code:

static void TestList()
{

var watch = new Stopwatch();

var theList = new List<int>();

watch.Start();

//Fill it
for (int i = 0; i <>

{

theList.Add(i);

}

watch.Stop();

Console.WriteLine("Avg add time for List: {0}", (watch.Elapsed.TotalMilliseconds / noOfIterations));

watch.Reset();

watch.Start();

//Test containsKey

for (int j = 0; j <>

theList.Contains(j);

}

watch.Stop();

Console.WriteLine("Avg Contains lookup time for List: {0}", (watch.Elapsed.TotalMilliseconds / noOfIterations));

}

I created similar test code for Dictionary and HashSet. In all of the tests I used a loop where the given key always existed in the data structure. I used Add instead of Insert, because of tests I've seen online show that this is much faster. For example, this one.

First run, I used 1,000 for the noOfIterations variable and ran it three times.

The horizontal scale here is in milliseconds, so things are reasonably fast. A value of 0.2 gives you a possible 200 adds per second. As you probably can see without checking the numbers, dictionary is faster. List is slower for lookup, but HashSet suprises a little with the slow add function. So what happens when we go to 100,000 items?

OK, List is a lot slower for lookup still. Add seems to compare ok though. Let's see how it compares if we remove the lookup-time from the chart: This is wrong, see "The aftermath"

Now that's a result! Turns out List is your winner if fast adding is all you care about. If you want to look up your values later though, dictionary is your winner. Hope this will save some time for other developers in the same situation. Also feel free to comment if you find different results, or a problem with my test!

By popular request: The rest of the code!

static void TestDictionary()

{

var watch = new Stopwatch();

//Create Dictionary

var theDict = new Dictionary<int, int>();

watch.Start();

//Fill it

for (int i = 0; i <noofiterations;i++)

{

theDict.Add(i, i);

}

watch.Stop();

Console.WriteLine("Avg add time for Dictionary: {0}", (watch.Elapsed.TotalMilliseconds/noOfIterations));

watch.Reset();

//Test containsKey

watch.Start();

for (int j = 0; j <noofiterations;j++)

{

theDict.ContainsKey(j);

}

watch.Stop();

Console.WriteLine("Avg Contains lookup time for Dictionary: {0}",

(watch.Elapsed.TotalMilliseconds/noOfIterations));

}

static void TestHashSet()

{

var watch = new Stopwatch();

//Create List

var hashSet = new HashSet<int>();

//Fill it

watch.Start();

for (int i = 0; i <>

{

hashSet.Add(i);

}

watch.Stop();

Console.WriteLine("Avg add time for HashSet: {0}", (watch.Elapsed.TotalMilliseconds / noOfIterations));

watch.Reset();

//Test contains

watch.Start();

for (int j = 0; j <>

{

hashSet.Contains(j);

}

watch.Stop();

Console.WriteLine("Avg Contains lookup time for HashSet: {0}", (watch.Elapsed.TotalMilliseconds / noOfIterations));

}

The aftermath
Because of the controversy involved in HashSet being slower than Dictionary, despite having only one value and the Dictionary two, I re-ran the test on my computer, and on a colleagues. Instead of running the tests one by one, I ran three times HashTest and three times Dictionary, and picked the averages. The result you can see below, HashSet is faster than Dictionary both for Add and Contains methods.


Monday, May 25, 2009

Exchange ActiveSync on my SE W715

Submit this story to DotNetKicks

I got a new phone! After three years of windoze mobile, I decided to go back to a regular phone. But I wanted e-mail, or rather, exchange activesync. So I landed on a Sony Ericsson W715. But after completing my setup, the only message I got was "Session Failed". Huh?

I found a promising blog from a Swede, but even that (allowing non-provisional devices to use ActiveSync on the Exchange Server) was not enough.

Finally we found that the connection attempts were being blocked by the ISA server (Microsoft firewall). By allowing All users, not just Authenticated ones, to connect to OWA, I was able to synch my emails.