Posts

Showing posts from 2008

.NET 2.0 Extension Methods

I regularly write programs in C# on Visual Studio 2008. The default Framework for the environment is 3.5. But sometimes I must re-target 2008 to Framework 2.0. Is it possible to take advantage of the new "Extension Method" language feature of 2008 when required to target 2.0? This is a good question and applies to more than the extension methods. But for now, let's answer the question for extensions.

Yes.

But, you need to do some of the work yourself. The compiler's support for extension methods is really unconnected with Framework 3.5. But maybe you've seen the error...


Cannot define a new extension method because the compiler required type 'System.Runtime.CompilerServices.ExtensionAttribute' cannot be found. Are you missing a reference to System.Core.dll?

To write an extension, you need the ExtensionAttribute somewhere, anywhere. The compiler is looking for it in the System.Runtime.CompilerServices namespace which is in System.Core.dll. The 2.0 …

An Interesting Delegate Usage

An interesting thing happened while I was surfing the MSDN C# forums. I was completely thrown for a loop when I came across some code posted by a regular contributor. It went something like this...

private void ACallBackFunction()
{
if(this.InvokeRequired)
this.Invoke(new ThreadStart(ACallBackFunction));
else
this.label1.Text = "Something or other";
}

The programming pattern should be very familiar to those using threads, because this is how a child thread updates the GUI (only the thread on which the GUI is created can update the UI). But, what seemed very strange was the use of "new ThreadStart(...)". I thought, what does a ThreadStart() delegate have to do with this operation?

The answer is ... nothing. But the application is none the less interesting. Here, the programmer decided to draw from a handy delegate in the C# tool chest just to get that required delegate to call "Invoke()" with. "ThreadS…

Regular Expressions in C# - Password Validator Revisited

Sometimes we make life more difficult than it needs to be.

Lately, I've learned a little more about Regular Expressions and "Negative Look-Around". I've used it a lot, but it only recently dawned upon me that I was not making full use of it.

Case in point, take a look at my earlier regular expression article where I explain how to validate a password with multiple requirements (Regular Expression Alternations). This article discusses the absense of the boolean AND in regular expressions and provides a complex IF-THEN-ELSE approach to test a string for conforming to multiple "password" constraints. And my subsequent article (Regular Expression Double Negatives) gets more complex with an "inside-out" approach to compensate for the lack of an AND operator.

But, let's go back even further to the article where I "explain" Negative Look-ahead. In this article, I provide the simple Negative Look-ahead pattern...


“(?!pattern)”

... and pro…

Callbacks And Delegates

It's been a couple of weeks since last writing. Besides being very busy, I've had a touch of "writer's block". Nothing too serious, I should get over it soon.

Lately, I've been intrigued by the abundant use of callback functions and delegates in the .NET Framework. If you want to do anything interesting, you gotta know callbacks. I'll try to describe callbacks and delegates in simplistic terms. Maybe it will help you over the hump.

Consider the following code...


List list = new List();
//Populate list with some MyClass objects
for(int i=0; i<10; ++i)
list.Add(new MyClass(){ ID=i, strValue=i.ToString() });
//Sort the list
list.Sort();
foreach(MyClass c in list)
Console.WriteLine("{0}",c.strValue);

...

public class MyClass
{
public int ID;
public string strValue;
public override string ToString() { return strValue; }
}


This code throws an exception at the line that says Sort(). …

A Simple Task Queue

I’ve spent the last 4 posts talking about Regular Expressions and some difficult patterns. But, this is a C# blog, so I really want to be talking about C#. Today, I hope to provide you with a nice little start on a multi-threading "Task Queue" application. A Task Queue will place task requests in a queue that will be serviced Asynchronously and in the order received.

Rather than keep you in suspense, here’s the code up front. If you'd like an explanation, I've attempted that below. (Update 10/6/2008: Sorry folks about the bug below. The Enqueue method must set the the Busy field to true when queing the first task in order to avoid the thread race. It's now been fixed.)


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace TaskQueuePOC
{
public partial class Form1 : Form
{
public Form1()

Regular Expression Double Negatives

In my last article titled "Regular Expression Alternation" we discussed Alternation as one means of performing the AND operation in a regular expression pattern.

(?(expression)yes|no)

But, what if you don't have this pattern in your version of RegEx? Some of you may be reading to gain knowledge that you can apply in other programming languages besides C# or the .NET environment. The pattern I described in the last article does not work in all versions of .NET Regular Expressions. In particular, it does not work in JScript Regular Expression Syntax. And, when you use tools like ASP.NET’s RegularExpressionValidator, you are implicitly using JScript. So then, what do you do?

To restate the original requirement, we want to validate a string that has at least one digit, at least one uppercase letter, and at least 6 characters. The problem statement is clearly an AND problem, so it begs to be written with the Alternation pattern. But in situations where we can’t us…

Regular Expression Alternations

I promised in my last article that I'd have more to say about regular expression. So here you have it. Today, we look at another tough problem for Regular Expressions. Let’s consider writing a pattern to validate that a string contains at least one digit, at least one uppercase letter, and at least 6 characters. One would think that this would be easy. But here we’re faced with an AND situation and the regular expression syntax doesn't provide an AND operator. Take, for example, any validation problem that has the form…

A and B and C

Without an AND operation in Regex, you are almost forced to go outside of the pattern and implement the test in multiple patterns and multiple passes of your validator. That may be the best approach, or it may be impossible if you are working with a blackbox validator and must provide a single Regex pattern.

I've found two approaches that can be applied to solve such problems. We'll discuss one of those approaches today. The approach…

Regular Expressions in C# - Negative Look-ahead

In my last article on Regular Expressions, we looked at a couple of simple expressions and 3 algorithms to use the expressions for “validating” strings. The main point of the article is that Regular Expression behavior will be confusing if not considered in the context of the algorithm being used. Please take a look at Regular Expressions. What’s that got to do with C#? to get the background for this article.

In this article, we will discuss one of the more difficult Regular Expression problems. How do you use “Negative Look-ahead”? To use Regular Expression “Negative Look-Ahead” or “Negative Look-Behind”, you have to change the way you think about pattern matching. First, the negative look-ahead takes the syntax…

“(?!pattern)”

In the words of the MSDN documentation…

(Zero-width negative lookahead assertion.) Continues match only if the subexpression does not match at this position on the right. For example, \b(?!un)\w+\b matches words that do not begin with un.


This expression wil…

Regular Expressions? What's That Got To Do With C#?

...Only that I often need to know Regular Expressions for my C# work. However, the online help and resources seem to come up a little short. So, today I diverge a little and discuss this cryptic yet valuable ancillary topic to try to help you through your next Regex dilema.

I'm not going to waste time and internet bandwidth explaining what a Regular Expression is, there are plenty of sites for those. But, I will give special thanks here to OmegaMan who compiled and posted the following on the MSDN Regex Forum...

OmegaMan's .Net Regex Resources Reference

I refer to it often.

So let's dive right in. Whenever you are considering using regular expressions, you need to determine what kind of pattern matching problem are you trying to solve.

1) Do I want a regular expression to check a string for validity?
2) Do I want a regular expression to find certain things in my string?
3) Do I want a regular expression so that I can replace patterns in my string?

There can be some overlap …

Enumerations and Strings

It has been a while since my last post. Things get crazy at times. But, here is another bit of sample code for you to muse over. We will look at enumerations and strings.

In C#, an enumeration is NOT a string, nor can you define it to be one. An enumeration can be defined as any of a number of integer types. You can leave it as its default type...


public enum unspecifiedTypeEnum
{
one = 1, two, three,
}


In which case you get named 32 bit values. Or you can specify the type of the underlying value as byte, sbyte, ushort, short, uint, int, ulong or long...


public enum byteTypeEnum : byte
{
one = 1, two, three,
}
// or...
public enum ushortTypeEnum : ushort
{
one = 1, two, three,
}
// etc...


... But, you can't declare it as a string.

That doesn't mean you can't use strings at all. When I want to save data to a file for future reference, I like to make my enumerations human readable and store them in the file as human-rea…

Threading with .NET ThreadPool Part 4

Suppose you've been given the task to write a function that copies the contents of one folder to another. So you set off on your merry way and come up with something like the following.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace ThreadPoolPart4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
// Get the Folder names, copy contents from one to the other
FolderBrowserDialog fb = new FolderBrowserDialog();
fb.ShowDialog();
string src = fb.SelectedPath;
fb.ShowDialog();
string dst = fb.SelectedPath;
// no error checking on the names, this is an example only

if (dst != src)
{
if (…

Generics Fast

You are trying to come up to speed in C# fast. Then all of a sudden, you come across the C# Generic Type and wonder how do I master that.

Well, I've got some good news for you. You are in good company. You thought I was going to say I'll help you master generics. No, that's beyond a simple blog like mine. But, maybe I can help you become proficient. We just have to get the main learning hurdles out of the way.

Hurdle #1 - Rationale
Generic Types were added to C# in version 2.0. Now, I am not going to go into any detail on the history of C# or generics. I just mention this because the C# team decided they had a serious enough short coming in 1.1 to add this major feature. That is, many, many programmers were opting to ditch type-safety and decent performance in order to write more versatile data structures. How's that? Well, folks (MS included) were writing things like List and Queue and Stack to take "objects". Then their particular data structure co…

Sleep

When I first started programming, I thought "Sleep" to be one of the most useless calls I could make. No, I'm not talking about personal habits, I'm talking about the Sleep() function.


using System.Threading;
Thread.Sleep(int milliSeconds)

We find this little "do nothing" function in C, C++, C#, VB, VB.Net, WScipt, and similar functions in other languages. And, I have since come to understand how useful and confusing "doing nothing" can be. So, let's take a look at it; I'll be focusing on the C# Sleep() function.

Sleep() simply suspends the execution of your thread for a specific period of time. It relinquishes the remainder of its time-slice and becomes "unrunnable" for a period of time. If the time period is zero, it relinquish its time-slice only if another thread is ready and waiting to run. If there are no waiting threads, and the time span is zero, the calling thread remains ready to run and therefore returns from Sleep(…