Monthly Archives: August 2010

Extension methods: what, how, when

I’ve already written a little bit about extension methods in the past. However, since I’ve decided to create a new basics series, I think that I probably should go back and write about it again. I guess that the first thing I need to do is define the what. In other words, *what* is an extension method?

An extension method is a static method that you can invoke using instance method syntax. Here’s a quick example:

namespace StringHelpers {
    public static class StringExtension {
        //don''t need this in real world!!
        public static Boolean ContainsOnlyDigits(this String str){
            if(str == null ) throw new NullReferenceException();
            return str.All(c => char.IsDigit(c));
//use the extension method
namespace ConsoleApplication1 { //import extension methods using StringHelpers; class Program { static void Main(string[] args){ var notOnlyDigits = "123Nop"; //const is better Console.WriteLine(((String)null).ContainsOnlyDigits()); } } }

As you can see, an extension method is always static and must be defined in a non generic, non nested, static class. The first parameter of an extension method is annotated with the this qualifier and defines the type over which the method can be called using an instance method syntax. In order to use the extension method (the *how*), we must first introduce it in the current scope. To achieve that, we need to resort to the using directive (as shown in the previous example).

Whenever the compiler finds an extension method, it will convert it into a static method call. Currently, you can use extension methods to extend classes, interfaces,delegates (probably more about this in a future post) and enumerate types. Internally,and since external methods aren’t C# specific, there is a “standard” way to mark a method as an extension method. In C#, when you mark a static method’s first parameter with the this qualifier, the compiler will automatically apply the ExtensionAttribute to that method and to the class where that method is defined. By annotating the type with the attribute, the compiler is able to query an assembly and get all the types that have extension methods defined.

Extension methods are really great and do improve the quality and readability of the code. However, I’ve noticed that they’re starting to be abused…for instance, it was only recently that I’ve downloaded the source code for the Fluent NH project and I couldn’t stop noticing that the CheckXXX methods (used against PersistenceSpecification instances) are all implemented as static methods. I’m having a hard time understanding this and here’s why. In my limited experience, PersistenceSpecification exists so that you can write tests for your NH mappings. Now, that means that you’ll *be* using this methods to test the mappings whenever you instantiate a new instance of that type. Since the guys that wrote the code for those methods *do* have access to the PersistenceSpecification class, I really can’t understand their decision of defining these methods as extension methods (and yes, I know that MS used the same approach for extending the IEnumberable<T> interface, but I believe that we’re not talking about the same type of scenario: after all, it’s perfectly fine to use the IEnumerable<T> without using LINQ).

So, when should we use extension methods? Here’s my thoughts about it (the *when*):

  • use it *sparingly*. I really can’t stress this enough! We’re still doing OO and there are several options for extending types. Do remember that there are some versioning problems associated with extension methods. For instance, if the type you’re “extending” adds a new method with the same name as the extension method, the code will always use the instance method (after recompilation, of course) because extension methods will only be considered as candidates when all the instance method available have been considered as non-viable.
  • they should look and feel like extension methods. The typical example of not following this recommendation is adding an IsNullOrEmpty extension method to some class and returning true when the “this” parameter is null (btw, here’s an example of what I mean). If the “this” parameter of the extension method is null, it should really throw a null reference exception since this is the best option for mimicking what happens with instance methods.

Overall, I’d say that extension methods are an excellent tool, but don’t get carried on and start using it everywhere. After all, we’re still writing object oriented code, right?

Wrap-upper and wrap up for August 2010

Simon May from MS UK created cool app: Live Writer Wrapup Tool. The tool allows you to create the following from your RSS feed:

Bingo: one click and all my messages for the month are published.

To install the tool visit

Then start it, enter your feed address, blog post title, and select the range for you wrap-up (click (don’t release the button) on a first date and slide cursor  to the last date) and click “Blog This!”



PowerShell in Practice offer

Today Manning are offering 50% their best selling books including PowerShell in Practice.


See to order

Code and data

In a recent Stack Overflow question, I answered a question which started off with a broken XPath expression by suggesting that that poster might be better off using LINQ to XML instead. The discussion which followed in the comments (around whether or not this was an appropriate answer) led me to think about the nature of code and data, and how important context is.

I don’t think there’s any particularly deep insight in this post – so I’ll attempt to keep it relatively short. However, you might like to think about how code and data interact in your own experience, and what the effects of this can be.

Code is data

Okay, so let’s start off with the obvious: all code is data, at some level. If it’s compiled code, it’s just binary data which a machine can execute. Put it on another machine with no VM, and there’s nothing remarkable about it. It’s just a load of 1s and 0s. As source code, most languages are just plain text. Open up some source code written in C#, Ruby, Python, Java, C++ etc in Notepad and it’ll be readable. You may miss the syntax highlighting and so forth, but it’s still just text.

Code in the right context is more than just data

So what makes this data different to (say) a CSV file or a plain text story? It’s all in the context. When you load it into the right editor, or pass it to the right compiler, you get more information: in an editor you may see the aforementioned syntax highlighting, autocompletion, documentation for members you’re using; a compiler will either produce errors or a binary file. For something like Python or Ruby, you may want to feed the source into an interpreter instead of a compiler, but the principle is the same: the data takes on more meaning.

Code in the wrong code-related context is just data again

Now let’s think about typical places where you might put code (or something with similar characteristics) into the "wrong" context:

  • SQL statements
  • XSLT transformations
  • XPath expressions
  • XML or HTML text
  • Regular expressions

All of these languages have editors which understand them, and will help you avoid problems. All of these are also possible to embed in other code – C#, for example. Indeed, almost all the regular expressions I’ve personally written have ended up in Java or C# code. At that point, there are two problems:

  • You may want to include text which doesn’t embed easily within the "host" language’s string literals (particularly double quotes, backslashes and newlines)
  • The code editor doesn’t understand the additional meaning to the text

The first problem is at least somewhat mitigated by C#’s support for verbatim string literals – only double quotes remain as a problem. But the second problem is the really big one. Visual Studio isn’t going to check that your regular expression or XPath expression looks valid. It’s not going to give you syntax highlighting for your SQL statement, much less IntelliSense on the columns present in your database. Admittedly such a thing might be possible, if the IDE looked ahead to find out where the text was going to be used – but I haven’t seen any IDE that advanced yet. (The closest I’ve seen is ReSharper noticing when you’re using a format string with the wrong number of parameters – that’s primitive but still really useful.)

Of course, you could write your SQL (or XPath etc) in a dedicated editor, and then either copy and paste it into your code or embed it into your eventual binary and load it at execution time. Neither of these is particularly appealing. Copy and paste works well once, but then when you’re reading or modifying the code you lose the advantages you had unless you copy and paste it again. Embedding the file can work well in some cases – I use it liberally for test data in unit tests, for example – but I wouldn’t want it all over production code. It means that when reading the code, you have to refer to the external resource to work out what’s going to happen. In some cases that’s not too bad – it’s only like opening another class or method, I guess – but in other cases the shift of gears is too distracting.

When code is data, it’s easy to mix it with other data – badly

Within C# code, it’s easy to see the bits of data which sometimes occur in your code: string or numeric literals, typically. Maybe you subscribe to the "no magic values" philosophy, and only ever have literals (other than 0 or 1, typically) as values for constants. Well, that’s just a level of indirection – which in some ways hides the fact that you’ve still got magic values. If you’re only going to use a piece of data once, including it directly in-place actually adds to readability in my view. Anyway, without wishing to dive into that particular debate too deeply, the point is that the compiler (or whatever) will typically stop you from using that data as code – at least without being explicit about it. It will make sure that if you’re using a value, it really is a value. If you’re trying to use a variable, it had better be a variable. Putting a variable name in quotes means it’s just text, and using a word without the quotes will make the compiler complain unless you happen to have a variable with the right name.

Now compare that with embedding XPath within C#, where you might have:

var node = doc.SelectSingleNode("//foo/bar[@baz=xyz]");

Now it may be obvious to you that "xyz" is meant to be a value here, not the name of an attribute, an element, a function or anything like that… but it’s not obvious to Visual Studio, which won’t give you any warnings. This is only a special case of the previous issue of invalid code, of course, but it does lead onto a related issue… SQL injection attacks.

When you’ve already got your "code" as a simple text value – a string literal containing your SQL statement, as an obvious example – it’s all too easy to start mixing that code/data with genuine data data: a value entered by a user, for example. Hey, let’s just concatenate the two together. Or maybe use a format string, effectively mixing three languages (C#, SQL, the primitive string formatting "language" of string.Format) into a single statement. We all know the results, of course: nothing differentiates between the code/data and the genuine data, so if the user-entered value happens to look like SQL to drop a database table, we end up with Little Bobby Tables.

I’m sure 99% of my blog readers know the way to avoid SQL injection attacks: use parameterized SQL statements. Keep the data and the code separate, basically.

Expressing the same ideas, but back in the "native" language

Going back to the start of all this, the above is why I like LINQ to XML. When I express a query using LINQ to XML, it’s often a lot longer than it would have been in the equivalent XPath – but I can tell where the data goes. I know where I’m using an element name, where I’m using an attribute name, and where I’m comparing or extracting values. If I miss out some quotes, chances are pretty high that the resulting code will be invalid, and it’ll be obvious where the problem is. I’m prepared to sacrifice brevity for the fact that I only work in a single language + library, instead of trying to embed one language within another.

Likewise building XML using LINQ to XML is much better than concatenating strings – I don’t need to worry about any nasty escaping issues, for example. LINQ to XML has been so nicely design, it makes all kinds of things incredibly easy.

Regular expressions can sometimes be replaced by simple string operations. Where they can, I will often do so. I’d rather use a few IndexOf and Substring calls over a regular expression in general – but where the patterns I need get too tricky, I will currently fall back to regular expressions. I’m aware of ReadableRex but I haven’t looked at it in enough detail to say whether it can take the place of "normal" regular expressions in the way that LINQ to XML can so often take the place of XPath.

Of course, LINQ to SQL (and the Entity Framework) do something similar for SQL… although that’s slightly different, and has its own issues around predictability.

In all of these cases, however, the point is that by falling back to more verbose but more native-feeling code, some of the issues of embedding one language within another are removed. Code is still code, data is data again, and the two don’t get mixed up with each other.


If I ever manage to organize these thoughts in a more lucid way, I will probably just rewrite them as another (shorter) post. In the meantime, I’d urge you to think about where your code and data get uncomfortably close.

Writing the perfect question

Update: now that I’ve actually posted this, I’ve added a tinyurl to it for easy reference: Nice and easy to remember for comments :)

A while ago, I wrote a blog entry on how to answer questions helpfully on sites like Stack Overflow. Recently I saw a meta question about bad questions and thought it would be worth following up with another blog post on asking questions. For the sake of convenience – and as Stack Overflow is so popular – I will assume the question is going to be asked on Stack Overflow or a similar Stack Exchange site. Most of the post doesn’t actually depend on that, but if you’re asking elsewhere you may need to tweak the advice a little.

There are plenty of similar resources around, of course – in particular, Eric Raymond’s How to Ask Questions the Smart Way is a perennial favourite. Still, I think I can bring something to the table.

The Golden Rule: Imagine You’re Trying To Answer The Question

If you don’t remember anything else from this post, remember this bit. Everything else follows from here. (And yes, this does smack somewhat of Matthew 7:12.)

Once you’ve finished writing your question, read it through. Imagine you were coming to it fresh, with no context other than what’s on the screen. Does it make sense? Is it clear what’s being asked? Is it easy to read and understand? Are there any obvious areas you’d need to ask about before providing an answer? You can usually do this pretty well however stuck you are on the actual question. Just apply common sense. If there’s anything wrong with the question when you’re reading it, obviously that will be a problem for whoever’s actually trying to answer it. So fix the problems. Improve the question until you can read it and think, "If I only knew the answer to the question, it would be a pleasure to provide that answer." At that point, post and wait for the answers to come rolling in.

Obviously this is somewhat easier to do if you have a certain amount of experience answering questions, particularly on the forum where you’re about to post. So, what should you be looking out for?

Question title

When a reader first sees your question, they’re likely to be scrolling down a list of snippets. The most eye-catching part of the snippet will be the title – so use that text wisely. While you can include language or platform information, you should only do so naturally – not as a sort of "header". For example, this is bad:

Java: Why are bytes signed?

But this is okay:

Why are bytes signed in Java?

Of course, you should also include this information in tags, as it will help people who pay particular attention to specific tags.

Ideally, a question title should be a question – but frankly that’s not always feasible. I would recommend favouring a short, descriptive title which captures the theme of the question without actually being a question instead of really trying to crowbar it into the form of a question when it really doesn’t want to be. That’s not an excuse for laziness though – it’s usually possible to come up with a good title which is genuinely a question.

It’s important that the question title is specific though, and has at least some meaning with no other information. A question such as "Why doesn’t this work?" makes absolutely no sense without the rest of the question. Likewise a "question" title of "Please help" is unlikely to do well.


In most cases, anyone answering the question will need to know what language and platform you’re using. The basics should usually be communicated through tags, but it may very well be worth providing more information:

  • Language version (e.g. C# 4)
  • Platform version (e.g. .NET 3.5; note that this isn’t always implicit from the language version, or vice versa)
  • Operating system, if it could be relevant (e.g. particular permissions issues)
  • Any other relevant software (e.g. database type and version, the IDE you’re using, web server you’re connecting to)
  • Any other constraints. This is particularly important. It’s really annoying to give a perfectly good answer to a question, only to be told that you’re not allowed to use feature X or Y which provide the obvious solution.
    • If you have unusual constraints, it’s worth explaining why. Not only does this answer the obvious follow-up comment, but it also gives more information about what other solutions may not be applicable.

Describe what you’ve already tried and the results of any research. (You have searched for a solution to your problem before asking it, haven’t you? Stack Overflow isn’t meant to replace basic search skills.) Often there will be other people in a similar situation, but the answers didn’t quite match your situation. Just like the above point about unusual constraints, it saves time if you can point out differences between your situation and other common ones. It’s even worth referring to other related questions explicitly – particularly if they’re on the same forum. Aside from anything else, this shows a certain amount of "due diligence" – people are generally more willing to help you if can show you’ve already put some effort in.

You should absolutely make sure that you tag the question appropriately. If you’re not sure which exact tags are appropriate, see what gets auto-suggested and look at samples for each one. If that sounds like a lot of work, just remember how much time you may be able to save yourself in the long run. It gets easier over time, of course.

Problem statement

Make sure it’s obvious what you’re trying to get out of the question. Too many "questions" are actually just statements: when I do X, something goes wrong.

Well, what did you expect it to do? What are you trying to accomplish? What have you already tried? What happened in those attempts? Be detailed: in particular, if something didn’t work, don’t just state that: tell us how it failed. If it threw an exception, what was the exception? (Don’t just give the type – give the error message and say which line threw it. If there’s a nested exception, post that too.)

If at all possible, write a sort of "executive summary" at the start of your question, followed by a more detailed description. Remember that on the list of questions, the first few sentences will appear as a snippet. If you can get a sense of the question across in that snippet, you’re more likely to attract views from people who can answer the question.

One trap that many posters fall into is to ask how to achieve some "small" aim, but never say what the larger aim is. Often the smaller aim is either impossible or rarely a good idea – instead, a different approach is needed. Again, if you provide more context when writing your problem statement, we can suggest better designs. It’s fine to specify how you’re currently trying to solve your bigger problem, of course – that’s likely to be necessary detail – but include the bigger goal too.

Sample code and data

I may be biased on this one. I’m a huge believer in sample code, both for questions and answers… and I probably use it in an unconventional way. I usually paste it into a text editor, and try to compile it from the command line. If that’s not likely to work (and the problem isn’t obvious by inspection), I’m unlikely to bother too much with it. Firing up Eclipse or Visual Studio and finding an existing project I don’t care about or starting a new one is going to take much more time.

That means if you want me to look at code, it should:

  • Be standalone. Don’t try to talk to a database unless you really have to. (Obviously for database questions, that’s kinda hard :) If you use sample XML, provide a short but complete XML file for us to reproduce the issue with. (And the same for other file types, obviously.)
  • Be complete. If there are missing imports or using directives, that’s really annoying
  • Actually compile (unless the compilation error is the reason for the question). Don’t give me code which is "something like" the real code but which clearly isn’t the real code, and may well not exhibit the same symptoms by the time I’ve fixed it so that it compiles.
  • Ideally not bring up a UI. Unless your code is about a UI issue, don’t bring one up. Console apps are simpler, and simplicity is a huge benefit when trying to hunt down a problem.
  • Demonstrate the problem. You should be able to say, "I expected the result to be X, it’s actually Y." (You should actually say that too, so that we can check that we get the same results.)
  • Be as short as possible. If I have to wade through hundreds of lines of code to find the problem, I’m doing work that you should be doing. Often if you work hard to reduce the problem to a short but complete program, you’ll find the issue yourself. You can absolutely do this without knowing what the problem is; you should be looking to the community for their expertise, not their willingness to spend time on your problem doing the work that you can do yourself.

Yes, this is a relatively onerous list. It doesn’t all apply to every problem, but it does apply in a great many situations. While I get put off by reams of irrelevant, badly formatted code, some of which clearly won’t compile, the inverse is true as well: if I can tell by looking at the question that the code can go through a copy/paste/compile/run cycle really quickly, I’m much more likely to pay the question significant attention.

In data-oriented questions, it’s very often helpful to give some sample data. Cut out anything irrelevant (if your real table has 50 columns, you only need to include relevant ones) but make sure that you give enough sample input for it to be meaningful. For example, if you’re trying to group some data by a PersonID column, it’s pretty useless if there’s only one PersonID given, or if each PersonID only appears once. If you are giving examples of expected input and output, make sure it’s clear why that’s the expected output. Often I see questions which give a small number of samples, and there are various ways they could be interpreted. This is one area where it’s particularly important to reread the question from a stranger’s point of view: while a brief summary of the desired results may well make sense to someone who already knows what your app is trying to achieve, it may be gobbledygook to those trying to answer your question.

Spelling, grammar and formatting

I know not everyone speaks English natively. My own command of non-English languages is lamentably poor – I’m incredibly lucky that my native tongue happens to be the lingua franca of the technical world. However, if you’re trying to communicate on an English-language forum, you owe it to yourself to make an effort to write at least reasonably correct English.

  • Please use capital letters where appropriate. It really can make a big difference in the readability of text.
  • Please split your text into paragraphs. Imagine this blog post as one big paragraph – it would be almost impossible to read.
  • Please write actual words. There are undoubtedly some abbreviations which are acceptable to most readers – IMO, IIRC etc -  there’s no reason to switch into text-speak with "gr8", "bcoz", "u" and so forth. It’s unlikely that you’re actually writing your question on a phone with only a primitive keyboard; show your readers respect by writing properly. It may take you a few more seconds, but if it means you get an answer quicker, it’s surely worth the extra effort.
  • Most browsers have built-in spelling checkers these days, or at least have plug-ins or extensions available to check your text. Technical text often creates a lot of false positives for checkers, but if your spelling isn’t generally great, it’s worth looking at the suggestions.

Having said all of this, you’re not trying to create a literary masterpiece. You’re trying to communicate your question as effectively as possible. If you’re faced with the choice between an unambiguous but ugly sentence, or a phrase which stirs the soul but leaves the reader confused about exactly what you mean, go for the unambiguous option every time.

One way a huge number of questions can be improved with very little effort is simply formatting them properly. Stack Overflow’s markdown editor is very good – the preview below your input box is almost always accurate in terms of the eventual result, and you can always edit the question later if anything doesn’t quite work. The exact details of the markdown is beyond the scope of this article – Stack Overflow has a detailed guide though – if you’re new to the site, I’d recommend you at least skim through it.

By far the most important kind of formatting is making code look like code. Within a text paragraph, simply surround the code with backticks `like this`. For blocks of code, just indent everything by four spaces. If you’re cutting and pasting code, it may already be indented (for example if you’re copying code within a class) but if not, the easiest way to indent everything is to paste it, select the whole code block, and then press Ctrl-K or the “{ }” button just above the editor.

One of the important things about code formatting is that it means angle brackets (and some other symbols) are preserved instead of being swallowed by the markdown formatter. In some cases this can mean all the difference between a question which is easy to answer and one which doesn’t make any sense, particularly in terms of generics in Java and C# or templates in C++. For example, like this

Why can’t I convert an expression of type List<string> to List<object>?

makes no sense at all if the type arguments are removed:

Why can’t I convert an expression of type List to List?

Often experienced members of the site will recognise what’s going on and edit your question for you, but obviously it’s better if they don’t have to.

Making a good impression

Leaving aside the main body of the question, there are a few simple ways to get the community "on your side" and therefore more likely to give you a useful answer quickly.

  • Register as a user and give yourself a meaningful name. It doesn’t have to be your real name, but frankly names like "Top Coder" or "Coding Guru" look pretty silly when you’re asking a question which others find simple. That’s still better than leaving yourself as "user154232" or whatever identifier is assigned to you by default though. Aside from anything else, it shows a certain amount of commitment to the question and/or site: if you’ve bothered to give yourself a name, you’re less likely to be an "ask-and-run" questioner.
  • Keep an eye on your question. There may well be requests for clarification – and of course, answers! If you receive an answer which wasn’t quite what you were looking for, explain carefully (and politely) why it’s not suitable for your purposes. Consider going back and editing your question to make it clearer for subsequent users.
  • Don’t add your own answer unless it really is an answer. Often users add extra details in an "answer" when they should really have just edited their question. Likewise editing your question is generally a better idea than adding a long comment to an existing answer – particularly if that comment contains a block of code (which won’t work well in a comment). If you do change the question in response to an answer though, it’s worth adding a comment to the answer just to let the user know that you’ve updated it though… you may well find they quickly edit their answer to match the revised question.
  • There’s no need to include greetings and sign-offs such as "Hi everyone!" and "Thanks – hope to get an answer soon" in the question. These will often be edited out by other users, as they’re basically a distraction. Greetings at the start of a question are particularly useless as they can take up valuable space in the snippet displayed in the question list.
  • Above all, be polite. Remember that no-one is getting paid to answer your question. Users are giving up their time to help you – so please be appreciative of that. If you’re asking a homework question, explain why you’re asking for help with something that traditionally you’d have to answer all by yourself. If a user suggests that your general approach is wrong and that there’s a better way of doing things, don’t take it personally: they’re trying to help you improve your code. By all means disagree robustly, but don’t start into ad hominem arguments. (This advice applies to answerers as well, of course.)
  • (Somewhat specific to Stack Overflow.) If an answer is particularly helpful or solves your problem, accept it by clicking on the tick mark by it. After you’ve asked a certain number of questions, an accept rate will be shown by your username in the question. Some users get annoyed with those with low accept rates (i.e. people who ask a lot of questions but rarely accept answers). Personally I’m not overly bothered by accept rates, but accepting an answer is still a generally good thing to do if it solved your problem. I certainly wouldn’t suggest accepting answers just to get your accept rate, if they didn’t help you.

Conclusion and feedback

Stack Overflow is an amazing resource (along with other Q&A sites, of course). The idea that you can get a good answer to a wide range of questions within minutes is pretty staggering… but there’s an obvious correlation between the quality of a question and the likelihood that you’ll get quick, helpful answers. Put that extra bit of effort in yourself, and it will probably pay for itself very quickly.

I’m hoping to keep this blog post up to date with suggestions received – if I’ve missed out anything, over- or under-emphasized a specific point, or generally gone off track, let me know either in the comments here or mail me ( If this document ends up elsewhere, then that copy may end up being the "canonical" one which is edited over time – in which case I’ll indicate that here.

Iterate Through the Properties of a Class

Reflection provides features to obtain information about loaded assemblies and the classes (and other types) within them. One of the many things you can do with reflection is to iterate through each of the properties of a class and access its values.

This example uses a customer class.

In C#:

public class Customer
    public int CustomerId { get; set; }
    public string LastName { get; set; }
    public string FirstName { get; set; }
    public string EmailAddress { get; set; }
    private string myPrivateProperty { get; set; }

In VB:

Public Class Customer
    Public Property CustomerId As Integer
    Public Property FirstName() As String
    Public Property LastName() As String
    Public Property EmailAddress() As String
    Private Property myPrivateProperty() As String
End Class

First, get the type of the instance. Then use reflection to access all of the properties of the class.

Be sure to import the System.Reflection namespace.

In C#:

// Create a customer instance
Customer cust = new Customer()
    CustomerId = 5,
    FirstName = "Bilbo",
    LastName = "Baggins",
    EmailAddress = ""

// Get the type of this instance
Type t = cust.GetType();
string fieldName;
object propertyValue;

// Use each property of the business object passed in
foreach (PropertyInfo pi in t.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
    // Get the name and value of the property
    fieldName = pi.Name;

    // Get the value of the property
    propertyValue = pi.GetValue(cust, null);
    Console.WriteLine(fieldName + ": " +
       (propertyValue==null ? "null" : propertyValue.ToString()));

In VB:

‘ Create a customer instance
Dim cust As New Customer With {.CustomerId = 5,
                               .FirstName = "Bilbo",
                               .LastName = "Baggins",
                               .EmailAddress = ""}

‘ Get the type of this instance
Dim t As Type = cust.GetType
Dim fieldName As String
Dim propertyValue As Object

‘ Use each property of the business object passed in
For Each pi As PropertyInfo In t.GetProperties(BindingFlags.Instance Or BindingFlags.Public Or BindingFlags.NonPublic)
    ‘ Get the name and value of the property
    fieldName = pi.Name

    ‘ Get the value of the property
    propertyValue = pi.GetValue(cust, Nothing)
    Console.WriteLine(fieldName & ": " &
      If(propertyValue Is Nothing, "Nothing", propertyValue.ToString))

This code first creates an instance of the customer class for testing purposes. Then it gets the type of that instance using GetType. This code work on any class.

The GetProperties method retrieves the set of properties for that type based on the binding flags. Use an Or to combine binding flags.

The most commonly used binding flags are:

  • Instance: Includes instance members.
  • Static: Includes static (shared) members.
  • Public:Includes public instance members.
  • NonPublic: Includes non-public (private, protected, etc) members.

NOTE: You must include either Instance or Static (or both) to get a return value from GetProperties.

The GetProperties method returns an array of PropertyInfo objects that each provide information on one of the properties. The Name property of the PropertyInfo object provides the property name. The GetValue method returns the value of the property. Since the property could be any type, the GetValue returns an object.

Though not shown in this example, the SetValue method of the PropertyInfo object sets the value of a property.

Use this technique any time you need to loop through all of the properties of an object.

For example, you could use this technique to read through the set of properties of an object and build the parameters for an Insert or Update stored procedure or build a SQL statement. Or you could read a DataTable and use the SetValue method to set the value of each property to a matching field in the DataTable.


Divide a List into Equal Parts

A recent post in the forums asked how to divide a generic list of items into separate lists of equal length.

For example, take a list of integers as shown below. Divide the list into separate lists of equal size (plus one list for the remaining elements).

In C#:

List<int> dd = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 
                                11, 12, 13, 14, 15, 16, 17, 18, 19};

In VB:

Dim dd As New List(Of Integer) From {1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
                                11, 12, 13, 14, 15, 16, 17, 18, 19}

You can use the Skip and Take Enumerable extension methods for the task.

Here is the code:

In C#:

public List<List<int>> splitData(int width, List<int> dd)
    List<List<int>> dds = new List<List<int>>();

    // Determine how many lists are required
    int numberOfLists = (dd.Count / width);

    for (int i = 0; i <= numberOfLists; i++)
        List<int> newdd();
        newdd = dd.Skip(i * width).Take(width).ToList();

    return dds;

In VB:

Public Function splitData(ByVal width As Integer,
                          ByVal dd As List(Of Integer)) _
                      As List(Of List(Of Integer))

    Dim dds As New List(Of List(Of Integer))

    ‘ Determine how many lists are required
    Dim numberOfLists As Integer = (dd.Count width)

    For i As Integer = 0 To numberOfLists
        Dim newdd As List(Of Integer)
        newdd = dd.Skip(i * width).Take(width).ToList()
    Next i

    Return dds
End Function

This code first creates a List for the set of Lists. The number of equal sized lists is then calculated by dividing the number of items in the original list by the desired number of items in each list. In this case, there are 19 elements in the list. If the "width" is 4, then there will be 5 lists.

The loop creates each of the equal sized lists. It uses the Skip method to skip the appropriate number of elements. It then uses the Take method to take the appropriate number of elements for each list.

You call this method as follows:

In C#:

List<int> dd = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 
                                11, 12, 13, 14, 15, 16, 17, 18, 19};

List<List<int>> splitdd = splitData(4, dd);

In VB:

Dim dd As New List(Of Integer) From {1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
                                11, 12, 13, 14, 15, 16, 17, 18, 19}

Dim splitdd As List(Of List(Of Integer)) = splitData(4, dd)

Use this technique any time you want to use parts of a list to build another list.


EDIT 9/1/2010: Inadvertently included a new when creating the List<int>. Removed it in both code examples. Thanks to Richard for pointing this out.

MS Security advisory: Insecure Library Loading Could Allow Remote Code Execution

lockRecently issued advisory has kind of shaken the around-security-society: “we all gonna die will be hacked”. Really, this is that nasty sort of a bug which is not a bug, actually. It is more like FireWire: just vulnerable by design, so it is to be fixed more on software vendors side, rather than on Windows one. Correspondingly it is a long, long process and until it is finished it will be considered as a 0day vulnerability. But will it really have such an impact on your security?

I doubt it. Really. On the one hand, an attacker, who successfully utilized the vector has all the power of the current user, which is not good anyway. On the other hand, nevertheless,  the attacker must be either in your local network, or you should use WebDAV. LAN is usually considered as more or less secure. Now the question: how often do you open applications from a not trusted WebDAV folders? I don’t do it and I don’t recommend it whether there is some 0day vulnerability around or no. The only thing that you can do to harm yourself is to open a document from a “prepared” WebDAV folder. This is the hard part to protect from. But you just can avoid doing that unless you are totally sure that the software piece you use to open the document is patched by its vendor or download the document to a local drive before opening it.

So,in normal environment the attacker will get only user’s rights and only in case a document or a program was opened from a not trusted location. It is bad situation,but not as bad as some journalists picture it.

P.S. I still recommend to read the advisory and take precautions.

Meet Aurora (1 of ??)

Now that the public beta of Aurora is out and in the wild, we can finally talk turkey about the product and what it does and doesn”t do. To that end, I”m starting a series of posts to introduce people to Aurora who might not otherwise be able to look at the product. My reasons for doing this (given that there are a lot of other folks who are also blogging/writing about the product) are multifold. First, back in the SBS 2008 pre-release days, I got up on my soapbox and told everyone who would listen that they needed to take a long hard look at SBS 2008 because it was significantly different from SBS 2003. Based on the types of issues I”m still helping IT Pros get through with SBS 2008, there are a LOT of people who didn”t do this. Well, Aurora is completely different from anything you”ve seen in the SBS product space before, and as such, there are some misconceptions and false assumptions I hope I can stamp out early on through these posts. Second, there are some things about the defaults in Aurora that I think need to be tweaked that I doubt very seriously will make it into the final product release build, so I”ll be documenting some of those tweaks here as we go through the series. Third, there are some,well,*different* things I”ll be doing with Aurora, and I want to have a place to highlight some of those unusual configurations someplace, especially if a few of these zany ideas make sense to other IT Pros who want to use them in their own deployments. Finally, I think that Aurora is going to be a huge player in the under-25 employee business, and the sooner consultants and businesses learn about what it can (and cannot!) do, the better!

So, with that introduction, let”s get started. If you haven”t already, I HIGHLY RECOMMEND that you start learning about the product on your own. You can get some overview information from the SBS Blog post from Michael Leworthy. That post includes links to several resources, including an overview video, that make for a good introduction. I”d also recommend, if you haven”t already, that you read the Aurora Beta Announcement on the SBS Blog and go sign up for the beta of the product so you can get your hands on the bits now. 

While you”re waiting for the bits to download, let”s take a quick tour of an out-of-the-box basic install of Aurora in a test environment. From the basic desktop screen, you can see that this is NOT your typical SBS.


In fact, if you”ve seen Windows Home Server, it should look really familiar to you (especially if you”ve been in on the Vail beta). That”s because Aurora is built on the same codebase as the next version of Windows Home Server, codenamed Vail. We”ll get more into the similarities in later posts, but for now, let”s mention the one key difference between Vail and Aurora, and that”s Active Directory.

As you”ll see in the above image, when looking at the list of services running on our unmodified Aurora install, there are Active Directory services running on this server. These are set up as part of the Aurora install and are present by default (i.e., you cannot choose whether to install Active Directory or not). Part of the licensing restriction for Aurora is that it must run Active Directory, and it must be the root domain holder for the network (very similar to the licensing restrictions for SBS, and the reason why you cannot have Aurora and SBS in the same domain).

One other key service of Active Directory is DNS, and as you can see in the above shot of the second page of services on Aurora, the DNS server service is installed and running. Again this is done as part of setup and is not configurable. Active Directory relies heavily on DNS, so it”s good to have the service there and pre-configured as part of the setup.

If you look carefully at the list of services in that second screenshot, however, you may notice something missing (if you”re used to the typical SBS installation). That”s right, there”s no DHCP Server service listed. Aurora does not preinstall or preconfigure DHCP services for the network. The default assumption with Aurora is that some other device on your network, perhaps the Internet Router, is providing DHCP for the network. This is one area where I disagree with the default configuration of Aurora out of the box. I firmly believe that DHCP should be installed and running on Aurora so that proper AD information can be handed out to workstations participating in the Aurora network, such as the default internal domain name and the IP address of the Aurora box as the primary DNS server for the workstations. Anyone who has run across domain-joined workstations that do not point to a domain-enbled DNS server knows that the Active DIrectory performance of the workstation leaves a great deal to be desired. Fortunately, the DHCP service can be installed on Aurora, and I have it on good authority that steps for doing so will be included on independent Aurora build docs that are being developed right now.

Next, let”s take a look at the Active Directory environment that is configured with Aurora. Below is a capture of the Active DIrectory Users and Computers console showing the AD defaults for Aurora.

Again, anyone familiar with SBS will notice significant differences in the SBS AD configuration and the Aurora AD configuration. The Aurora AD configuration is the same as what you would get installing Active Directory on a standard Windows Server 2008 box. No custom OUs, user accounts placed in the Users containers, and so on. This isn”t necessarily a bad thing – Foundation Server does the same when AD is installed (not installed by default). But it *is* different from SBS, and that”s something that IT Pros need to be aware of. This configuration has significant impacts on how Group Policy will be applied, but we”ll dive into Group Policy on Aurora in more detail in a later post.

Since we did mention Group Policy, however, let”s take a quick peek at the Group Policy configuration in our out-of-the-box Aurora install:

When you look in the Group Policy Management Console, you”ll see that the only GPOs listed for the domain are the Default Domain Policy and the Default Domain Controllers Policy. That”s it. Again, this is exactly what you”d expect from a traditional Active Directory installation, but NOT from an SBS installation. SBS has used Group Policy heavily in its configuration since SBS 2003, but that is not the case in the default Aurora install.

So in this quick look at Aurora, I hope you”ve seen that Aurora is NOT the “next version of SBS” as some media outlets have claimed that it is. It”s going to be an interesting hybrid of Home Server and Foundation Server, but it is NOT a derivative of the traditional SBS product line. While not all of the details regarding Aurora have been finalized or made public yet (i.e., pricing, licensing, additional restrictions, etc.), I still think that this is going to be a great platform to build on for the 1-20 employee business. I”m already making plans to “upgrade” several of our customers from SBS 2003 to Aurora (and I”ll cover more about how I plan to approach that move from a technology standpoint in later posts in this series) once the product is released, and see the potential of this product with other clients that we haven”t had a good solution for up until now. But as different as this product is, the typical SBS consultant will need to rethink the way they approach ongoing maintenance for this solution, and the best way to devise those plans is to start working with the product NOW to see what you”re really up against. Some of the tools or processes you”ve been using for years simply may not work the same way on Aurora as they do your other supported devices, and you really don”t want to figure that out AFTER you”ve deployed this to a customer.

Bottom line, we”re sold on Aurora, and think you will be, too. cool apps–useful and not

cloudSome time ago I posted about group policy search service, published in Azure at the Then I thought: “it cannot be the only application on the whole domain!”. And I was right, of course. There is, actually at least several dozens of apps there. There is mostly test stuff at the moment on the site:

WordPress on Azure (how-to)

Several apps related to environment which don’t seem to be a completed apps, but are interesting, nevertheless

A 70 gigapixel (!!!!!) shot of Budapest with zoom and browsing ability. Man, it’s useless, but what a beautiful city. Thanks, guys!

Real-word polygonal battle game (the whole world is a chess-board)

And even the site about medical marijuana strains…

But look, here we have:


Equallogic site

VMWareConsulting (their Azure version works better than the usual one 8) ,,)

They are real, actually.

And just two apps which seem to be interesting:

Webcast collection for IT Pros and developers. Renewable.

And even a document search engine (should compare to Google =) )

Try to find your favourite on, and even to create your own one.

Recent Comments