Archive for October, 2007

Introduction to the Comparer Delegate

The Comparer Delegate Does the Hard Work for You

Once you have data in a generic List or Dictionary you may find that you need to sort it into the order you need. This is fairly easy if you’re using simple data types since .NET provides default comparers but it can get a little trickier if you need to sort objects. In this article we’ll look at how to use Comparer Delegates to do this.

What is a Comparer Delegate?

A comparer delegate is a routine that is used to compare two objects. It returns a 1 if the value of the first object is greater, -1 if the value of the first object is lesser, and 0 if the objects are equal. Since we’re working with objects we can compare multiple values in the two objects to determine which is greater than the other.

Code Example #1

In this example we’ll look at sorting PointF coordinates by their distance from 0,0. First, let’s load up our list and call the Sort method with our comparer that we’ll write in a moment.

Dim CoordinateList As New List(Of PointF)(New PointF() {New PointF(14, 22), New PointF(17, 21), _
                                          New PointF(15, 8), New PointF(15, 20), _
                                          New PointF(16, 7), New PointF(15, 21), _
                                          New PointF(17, 7), New PointF(16, 21), _
                                          New PointF(14, 23)})
CoordinateList.Sort(AddressOf ComparePointF)

Now, let’s code our comparer routine, ComparePointF:

Public Function ComparePointF(ByVal positionOne As PointF, ByVal positionTwo As PointF) As Integer
    Dim DistanceOne As Double = Math.Sqrt((positionOne.X ^ 2) + (positionOne.Y ^ 2))
    Dim DistanceTwo As Double = Math.Sqrt((positionTwo.X ^ 2) + (positionTwo.Y ^ 2))
    If DistanceOne > DistanceTwo Then
        Return 1
    ElseIf DistanceOne < DistanceTwo Then
        Return -1
    Else
        Return 0
    End If
End Function

Here we’re using the Pythagorean distance formula to determine the distance from 0,0 for each point and then comparing the results. The List object handles all of the sorting internally so the performance is quite good.

Code Example #2

In this example, we have an invoice object where we’re wanting to sort the objects first by customer type and then by the total amount of the invoice. Here’s what our comparer delegate would look like:

Public Function CompareInvoices(ByVal invoiceOne As Invoice, ByVal invoiceTwo As Invoice) As Integer
    If invoiceOne.CustomerType > invoiceTwo.CustomerType Then
        Return 1
    ElseIf invoiceOne.CustomerType < invoiceTwo.CustomerType Then
        Return -1
    Else
        If invoiceOne.Total > invoiceTwo.Total Then
            Return 1
        ElseIf invoiceOne.Total < invoiceTwo.Total Then
            Return -1
        Else
            Return 0
        End If
    End If
End Function

As you can see in this function, we first compare the customer type, then the total amount. Of course, you could make this even more complex for your sorting situations. All you have to keep in mind is your integer return value.

I hope these examples have been helpful to you in learning how to use the comparer delegate. If you have any further questions or observations about this subject, please feel free to leave a comment.

Share This Article: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Technorati
  • DotNetKicks
  • DZone

Add comment October 19th, 2007

Link Round-Up for 10/18/07

I’ve been a bit busy this week so I haven’t got as many links this time around.

Careers

I did run across a few good career related links though, such as this one on Tech Republic: Write a resume that will land you a programming job. It has some very detailed tips on how to write a resume that will get you an interview.

Also, on the career front, there was this good article by Rob Walling called Q & A on Leaving Management for Development. It’s a follow-up on an earlier article he had written on this topic but it has good info all on its own. Also check out the rest of his site for more good stuff.

Architecture and Methods

I found this article, How To Tell If You’re Doing Agile Right, by Ryan Cooper. I think he does a good job of making the business case for Agile development although I’m not sure if that’s what he intended to do.

Niclas Nilsson wrote this piece on Top Ten Software Architecture Mistakes that’s pretty good. Actually he’s just condensing what Eoin Woods had said in this longer, 2 part, article, Avoiding the Icebergs.

Programming

Saptarshi Purkayastha applies a little Eastern philosophy in this article, Programming Lesson: You Are The Bug…. He’s working on some follow-up articles with the same kind of theme so check back with him later as well.

That’s all the links for this week. As always, let me know of any interesting .NET or general software development links by leaving me a comment or dropping me an email.

Share This Article: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Technorati
  • DotNetKicks
  • DZone

Add comment October 18th, 2007

Practice, Practice, Practice

Let Your Programming Make Beautiful MusicThe old joke has a guy asking pianist Arthur Rubinstein "Pardon me sir, but how do I get to Carnegie Hall?" and Rubinstein replying, "Practice, practice, practice." The question that novice programmers often ask is like it, "How do I become a professional programmer?" And, like the guy who only wanted directions they want to know which classes to take or certifications to earn to become a programmer. However, the real answer is that one must practice programming just like one practices the piano in order to master it.

How Do You Practice Programming?

The obvious way to practice is to write programs just like if you expect to learn piano you play the piano. But, it goes deeper than that. To learn, to effectively practice, you need to work on things that aren’t easy for you. For example, if you struggle with understanding how to write a good SQL Join, practice writing them until you get good at it. If the ins and outs of ADO.NET baffle you, work on them. Find areas that you’re weak in and practice them by writing actual working code.

Another way to practice programming, particularly when you’re learning a new language, is to take an algorithm that you wrote in one language and figure out how to write it in the new one. For example, if you’re transitioning to VB.NET from VB6, take some of your old code and figure out the .NET way of writing it. If you know VB.NET and want to learn C# or Java, do the same thing. You will find that this exercise not only helps you learn something new but also increases your knowledge of your original language.

Make Your Practice Structured

To make your programming practice more effective create a schedule or structure that you follow. For example, you might set a goal of practicing for 1 hour a week to improve your database coding and dedicate another hour in the week to learning something new. If you don’t set goals you’ll find that your practice becomes less and less until it doesn’t exist at all. It’s also a good idea to chart your progress so that you have hard evidence to yourself that you’ve achieved your learning goals. The sense of accomplishment when you do this is quite rewarding.

Practice While Working

You can practice while you work as well. The way I do this is to have a ’scratchpad’ program where I create little snippets of code. These often match my main work but this gives me a place outside of it to work through ideas without the overhead and distraction of the core program. Often you’ll find these little practice pieces will fit well into your existing program or even earn a place in the snippets plug-in.

Do you practice programming? If you do, what are some of your practice techniques? If you don’t, why don’t you? Do you have anything you would like to add or ask about concerning programming practice? If so, please leave a comment.

Share This Article: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Technorati
  • DotNetKicks
  • DZone

3 comments October 18th, 2007

How To Create a Blog Badge in VB.NET

Visual Basic Notebook For .NET Blog Badge

I’m sure you’ve seen blog badges around like this around the Internet. Perhaps you’ve also wondered how to create one in VB.NET. Here’s a simple class that you can use to create 80×15 pixel badges. You could even add this class to your own ASP.NET web site and, with a little fleshing out, make your own badge generator.

The Basics

What we will be doing is creating a new 80×15 System.Drawing.Bitmap object. We will then create a Graphics object for the bitmap and drawing our rectangles and text on it. Then we’ll save the bitmap image out in PNG (Portable Network Graphics) format.

The Code

Here’s our code.

Public Class BlogButton

    Public Shared Sub GenerateBlogButton(ByVal buttonSaveLocation As String, ByVal leftText As String, ByVal leftTextColor As Color, _
                                         ByVal leftBackgroundColor As Color, ByVal rightText As String, ByVal rightTextColor As Color, _
                                         ByVal rightBackgroundColor As Color, ByVal borderColor As Color, ByVal backgroundColor As Color)
        Dim ButtonPicture As New Bitmap(80, 15)
        Using ButtonGraphics As Graphics = Graphics.FromImage(ButtonPicture)
            Dim ButtonFont As New Font("Verdana", 6, FontStyle.Regular)
            Dim TextBrush As New SolidBrush(leftTextColor)
            ButtonGraphics.Clear(backgroundColor)
            ButtonGraphics.DrawRectangle(New Pen(borderColor, 1), New Rectangle(0, 0, 79, 14))
            ButtonGraphics.FillRectangle(New SolidBrush(leftBackgroundColor), New RectangleF(2, 2, 31, 11))
            ButtonGraphics.FillRectangle(New SolidBrush(rightBackgroundColor), New RectangleF(34, 2, 44, 11))
            ButtonGraphics.DrawString(Mid(leftText.ToUpper, 1, 4), ButtonFont, TextBrush, 3, 3)
            ButtonGraphics.DrawString(Mid(rightText.ToUpper, 1, 8), ButtonFont, TextBrush, 34, 3)
            ButtonGraphics.Flush()
        End Using
        ButtonPicture.Save(buttonSaveLocation, System.Drawing.Imaging.ImageFormat.Png)
    End Sub

End Class

A few of things to note about the code.

First of all, why am I using the Mid function? Isn’t it suppose to be ‘evil’? I’m using it here because it can be used to limit the length of text in a very simple and readable manner. SubString(0,4) would throw an exception if the length was shorter than that. To avoid the exception and be “.NET Pure” I would have to have more length checking code in the routine. I decided not to do that and instead make use of a handy VB function that does this for me.

Another thing to note is that I’m using hardcoded values in several places. Since I’m working with a fixed size I didn’t go to the trouble of using constants or variables for these values. However, if I were to expand this implementation I would want to replace any hardcodes.

I’m not using any overloads on this function although it probably could benefit from some if it was production code. For example, you might want to have overloads for the size of the graphic and the font object or you might want to have an overload with fewer parameters for a default version.

Lastly, I made it shared so that it could be called without having to worry about the state of an object. You could create a version that did not use shared if you wanted.

More You Can Do

In addition to making the size flexible you could also add dynamic sizing between the right and left columns by using MeasureString. Using it to calculate the size of the passed in strings you could determine where to draw the rectangles. Another thing you could do is make the font changeable. 

You could also take this code and develop your own CAPTCHA or hit counter components. The basics would be the same. You could also take this same code and put it into a desktop app for graphic generation there although you might want to create a version that passes back a bitmap rather than writing it to disk.

Let me know if you have any questions or observations about this code sample by leaving me a comment.

Share This Article: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Technorati
  • DotNetKicks
  • DZone

1 comment October 16th, 2007

Guest Blogging on AjaxNinja

Aaron at AjaxNinja asked me to write an article for his website with my suggestions for someone who’s just starting a career in programming. He’s posted it this evening: How to Jump Start Your Programming Career. Check it out and let me know what you think.

Share This Article: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Technorati
  • DotNetKicks
  • DZone

Add comment October 15th, 2007

Next Posts Previous Posts


Visit Me At My New Site, Programming In C#

Most Popular Articles

Highest Rated Articles

Categories

Most Recent Articles

Feeds

 Subscribe in a reader

To subscribe by e-mail
Enter your address here

Delivered by FeedBurner

VB Opportunities

Archives