0

Skipping the Header in ItemDataBound

Posted in Asp.Net, Uncategorized at July 31st, 2007 by Gerrod / No Comments »

I often subscribe to the ItemDataBound event in a repeater to perform custom logic for each item within the repeater (for example, performing some custom calculations). When the repeater includes a header though, more often than not, you want to skip over the header row, since you don’t want to perform your custom calculations on that row. Until now, the way I did this was like this:


private void OnItemDataBound(object sender, RepeaterItemEventArgs e) {
    // skip header row
    if (e.Item.ItemIndex < 0) {
        return;
    }

    // custom logic
}

Today however, I found out there's a nicer way:


private void OnItemDataBound(object sender, RepeaterItemEventArgs e) {
    // skip header row
    if (e.Item.ItemType == ListItemType.Header) {
        return;
    }

    // custom logic
}

Sure, given that both ways work equally well, it seems as though the difference is for aesthetics only (i.e it's nicer to read); but there are actually two other big advantages:

  1. It is not tied into the implementation of the repeater - that is, it does not rely on the header row index being less than zero; and
  2. You can use the ListItemType enumeration to detect many different types of items - for example, the Footer row for performing summary calculations.

1

Not Quite Quicksilver for Windows

Posted in Uncategorized at July 28th, 2007 by Pat / 1 Comment »

A work colleague introduced me to Launchy and it has started to change the way that I at least stop organising the items that appear in the Start menu.

CTRL-Space is a nice little shortcut for launching new applications or documents and it’s pretty configurable so you can open up as much or as little as you want.

Give it a go!

0

Code comments

Posted in Development at July 20th, 2007 by Gerrod / No Comments »

The only good thing about inheriting code is when the previous author/s have a sense of humour…


/* Apparently we are not using the t_Challenge table anymore
 * Too bad you can't do the messenger *rolling eyes*
 * smilie in code file comments...

Doomed I tells ya…

4

GetValueOrDefault

Posted in .Net, C# at July 16th, 2007 by Gerrod / 4 Comments »

Here’s another method that comes under the category, “Methods that I wish I’d have found at least six months ago”.

Nullable objects all implement an overloaded method called GetValueOrDefault, which – as the name suggests – returns the value of the nullable object if it has been assigned one (i.e. HasValue returns true), or a default value (being either the default value for the type, or a default value that you provide). So, instead of writing code like this (note: I’d never really write this method, but it serves as an example):


public int GetValueOfNullableInt(int? nullableInt) {
    return nullableInt.HasValue ? nullableInt.Value : default(int);
}

You can instead use this (and again, pointless code used as an example only):


public int GetValueOfNullableInt(int? nullableInt) {
    return nullableInt.GetValueOrDefault();
}

The overloaded method lets you pass in a default value you wish to have returned should the nullable not have a value. Is nice!

Recently at work we discovered that our SSL encrypted pages weren’t coming back fully encrypted. We narrowed down the partial SSL encryption problem to some default AJAX requests we were doing.

After searching the net I found that Microsofts XML Parser software must be version 3.0 with SP1 or later to support SSL.

I looked on my machine and noticed that I had MSXML 6.0 Parser.

Program Files - MSXML Parser 6.0

So it was time to look at my javascript file that instantiated the ActiveXObject.


function getXmlHttp() {
  try {
        return new ActiveXObject("Msxml2.XMLHTTP");
  } catch(e) {
    try {
      return new ActiveXObject("Microsoft.XMLHTTP");
    } catch(E) {}
  }

  if (XMLHttpRequest != "undefined") {
    return new XMLHttpRequest();
  } else {
    return null;
  }
}



Now admitedly this bit of code was copied and pasted from somewhere so it was time to finally understand exactly what was going on.

Firstly, the code tries to instantiate a version specific instance of the XmlHttp object. I’m not entirely sure which version this is bringing back but it is definitely pre-3.0 SP1.


  return new ActiveXObject("Msxml2.XMLHTTP");



If that failed to bring back an instance it tries again with the following line: -


  return new ActiveXObject("Microsoft.XMLHTTP");



This is like an factory object that will bring back the most recent version installed on the clients computer.

So to fix this problem the code was changed to: –

Firstly, the code tries to instantiate a version specific instance of the XmlHttp object. I’m not entirely sure which version this is bring back but it is definitely pre-3.0 SP1.


  try {
        return new ActiveXObject("Msxml2.XMLHTTP.6.0");
  } catch(e) {
    try {
      return new ActiveXObject("Microsoft.XMLHTTP");
    } catch(E) {}
  }

  if (XMLHttpRequest != "undefined") {
    return new XMLHttpRequest();
  } else {
    return null;
  }
}

You might think it odd that I have hard-coded an version instance as our first try, but because we’re in an intranet environment we can ensure that all clients have version 6.0 of the XML parser installed. If they don’t we’ll try our best to get a version that is hopefully later than 3.0SP1 so that we can get SSL support.

1

Creating an MD5 hashed password

Posted in .Net, C#, Uncategorized at July 12th, 2007 by Gerrod / 1 Comment »

Ever wondered how the FormsAuthentication.HashPasswordForStoringInConfigFile method works? Me neither, but I had to basically replicate its functionality the other day. I tried decompiling it using Reflector, but it really wasn’t any help.

The part I was struggling with was working out how to get a Hex string from a Base64 string (which is what the ComputeHash method will return to you). Turns out you need to call the ToString() method on each byte, specifying “X2″ as the format. Of course! Well, nothing illustrates a point like some code, so here it is:


/// <summary>
/// Return a Hex-string encoded validation for the nominated password
/// </summary>
public string GetHashedPassword(string password) {
    Encoding encoding = new ASCIIEncoding();
    byte[] hash = new MD5CryptoServiceProvider().ComputeHash(encoding.GetBytes(password));

    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < hash.Length; i++) {
        builder.Append(hash[i].ToString("X2"));
    }

    return builder.ToString();
}
2

Overriding the equality operators

Posted in .Net, C#, Uncategorized at July 6th, 2007 by Gerrod / 2 Comments »

I’ve always found it rather painful to correctly override the equality operators in a class file. I always end up with cyclic references, stack overflows, null pointers, or other problems that are equally terrible. So finally today I sat down and figured out how to do it “correctly” – whereby “correctly” I mean, “in a way that gives me the right result without throwing an exception.

My model here is a very simple class called SimpleResponse. The class is generic (must be a primitive type, i.e. struct) and only has two fields: Value (of type T), and Description (of type String). Here’s how I did the equality overloads:


// Instance method
override public bool Equals(object obj) {
    return Equals(this, obj as SimpleResponse<T>);
}

static public bool operator ==(SimpleResponse<T> first, SimpleResponse<T> second)
{
    return Equals(first, second);
}

static public bool operator !=(SimpleResponse<T> first, SimpleResponse<T> second)
{
    return !Equals(first, second);
}

static public bool Equals(SimpleResponse<T> first, SimpleResponse<T> second)
{
    if (ReferenceEquals(first, null) && ReferenceEquals(second, null)) return true;
    if (ReferenceEquals(first, null) || ReferenceEquals(second, null)) return false;

    return Object.Equals(first.Value, second.Value) &&
        String.Equals(first.Description, second.Description);
}

The important things to note here are:

  1. All the equality methods effectively just delegate to the Equals method right down the bottom.
  2. Since you’re overriding the == and != operators, you cannot use these in your Equals method to calculate equality – this will cause a StackOverflowException. This includes checking for null – note that you have to use ReferenceEquals instead (which is a static method on the Object class).
  3. Similarly, you can’t use the Equals method without causing a StackOverflowException. If you need to use an Equals method, you need to explicitly state which Object implements the method you want to use -note here I’m using String.Equals for comparing the descriptions, and Object.Equals when I can’t tell the type of the variable.

If anyone has suggestions as to a way I could have done this better, I’d love to hear them!

0

Using WebRequest to hit a RESTful web service

Posted in .Net, C# at July 6th, 2007 by Gerrod / No Comments »

RESTful web services seem to be all the buzz at the moment. In my current project, I have to hit just such a service – which in fact, is simply simulating a POST request to a form.

To do this, all you need to do is create a new WebRequest (using a factory method), passing in the URL of the service that you want to hit. Once you’ve done that, it’s simply a matter of writing your request body to the request stream, and then reading a response from the response stream. You can even do it asynchronously if you want to!


/// <summary>
/// Executes a CheckMend request
/// </summary>
/// <param name="request">The CheckMend request to execute.</param>
/// <returns>A <see cref="CheckMendResponse" /> containing the results of the request</returns>
public CheckMendResponse CheckMend(CheckMendRequest request)
{
    byte[] requestBytes = request.ToASCIIByteArray();

    // Setup the web request to hit the CheckMend service
    WebRequest webRequest = WebRequest.Create(Settings.Default.CheckMendUrl);
    webRequest.Method = "POST";
    webRequest.ContentType = "application/x-www-form-urlencoded";
    webRequest.ContentLength = requestBytes.Length;

    // Write the request to the request stream
    DateTime requestTime = DateTime.Now;
    using (Stream webRequestStream = webRequest.GetRequestStream()) {
        webRequestStream.Write(requestBytes, 0, requestBytes.Length);
    }

    // Now read the response from the response stream
    using (WebResponse webResponse = webRequest.GetResponse()) {
        using (StreamReader reader = new StreamReader(webResponse.GetResponseStream())) {
            return CheckMendResponse.Parse(requestTime, reader.ReadToEnd(), request.Options);
        }
    }
}

Pretty easy, right? The only real trap is making sure that you have set the ContentType correctly:


    webRequest.ContentType = "application/x-www-form-urlencoded";

At first, I was trying with a content type of “text/html”, and that just doesn’t work.