Long Time No Post

04.02.07

Its been a wile sense my last post but I have a good excuse. My blog was contending with finals from last quarter and a new job. I am now working for The PBA as a C# application developer and I love it.  It is a great opportunity and I get to work with great people. But now that I have finally settled in too my new job and new quarter of school I can continue my quest for mastering patterns I have already started working on a good example of the strategy pattern and will have it completed and posted by the end of the week. Cheers all I have to catch my bus.

 

Web 2.0 Presentation

02.09.07

This video is the coolest most impressive explanation of the buzz word web 2.0 I have ever seen. Definitely worth 5 min of your time.

The Observer Pattern

02.06.07

The observer pattern is very useful and very easy to implement. It only requires two interfaces. One interface is the subject interface the other is the Observer.

    The subject contains three methods: AddObserver, RemoveObserver, and Notify. This interface is implemented by any class that needs to notify other objects that its state has changed.
Public Interface ISubject
    Sub AddObserver(ByRef ob As IObserver)
    Sub RemoveObserver(ByRef ob As IObserver)
    Sub Notify()
End Interface

The other interface is the observer it only contains one method Update, this interface is implemented by any class that needs to be notified by the subject object.

Public Interface IObserver
    Sub Update(ByVal subj As Object)
End Interface
In some examples of this pattern I have seen the subject is setup as an abstract class that you must inherit from, but I believe it limits the usefulness of the pattern. From what I read in the Head First Design Patterns book it says it is best to program to an interface instead of using inheritance. To illustrate this pattern I have created a simple program that monitors My Documents  folder on your computer and notifies a form when ever this folder's contents have changed. This is only an example, the way I implemented the subject object is a little weak but it will serve well enough.

I used the FileSystemWatcher as my base class and implemented the ISubject interface to serve as the subject. The class that implements the subject interface must contain a collection of observers the observers are added and removed using the AddObserver and RemoveObserver methods. The observers are notified by the Notify method witch iterates through the observer collection calling the Update method in the IObserver interface.

Imports System.IO
Public Class MyFileWatcher
    Inherits FileSystemWatcher
    Implements ISubject
Dim _observers As New ArrayList
Public Sub AddObserver(ByRef ob As IObserver) _
  Implements ISubject.AddObserver
    _observers.Add(ob)
End Sub
Public Sub Notify() _
  Implements ISubject.Notify
    Dim ob As IObserver
    For Each ob In _observers
        ob.Update(Me)
    Next
End Sub
Public Sub RemoveObserver(ByRef ob As IObserver) _
  Implements ISubject.RemoveObserver
    _observers.Remove(ob)
End Sub
Private Sub File_Changed _
 (ByVal sender As Object, ByVal e As System.IO.FileSystemEventArgs) Handles Me.Changed
    Me.Notify()
End Sub
Private Sub File_Created _
 (ByVal sender As Object, ByVal e As System.IO.FileSystemEventArgs) Handles Me.Created
    Me.Notify()
End Sub
Private Sub File_Deleted _
 (ByVal sender As Object, ByVal e As System.IO.FileSystemEventArgs) Handles Me.Deleted
    Me.Notify()
End Sub
Private Sub file_Renamed _
    (ByVal sender As Object, ByVal e As System.IO.RenamedEventArgs)Handles Me.Renamed
    Me.Notify()
End Sub
End Class

The observer is implemented as a form that contains List box this list box is Notified by the Subject and the Update method is ran witch updates the list with a valid list of files.

Imports fileWatcher
Imports System.IO
Public Class Form1
    Implements IObserver
    Private _path As String
    Private _allfiles As Collections.ObjectModel.ReadOnlyCollection(Of String)
    Public Property Path() As String
        Get
            Return _path
        End Get
        Set(ByVal value As String)
            _path = value
        End Set
    End Property
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        _allfiles = My.Computer.FileSystem.GetFiles(_path)
        For Each singleFile As String In _allfiles
            Me.ListBox1.Items.Add(singleFile)
        Next
    End Sub
    Public Sub Update1(ByVal subj As Object) Implements fileWatcher.IObserver.Update
        Me.ListBox1.Items.Clear()
        _allfiles = My.Computer.FileSystem.GetFiles(_path)
        For Each singleFile As String In _allfiles
            Me.ListBox1.Items.Add(singleFile)
        Next
    End Sub
End Class

Lastly I created an MDI form that contains an instance of the FileWatcher class and creates a new Instance of the subject form every time a tool strip button is clicked. When ever a file in my documents is update all the child forms of the mdi are updated.

Imports System.Windows.Forms
Imports fileWatcher
Public Class MDIParent1
    Private Sub ShowNewForm(ByVal sender As Object, ByVal e As EventArgs) Handles NewToolStripButton.Click
        Dim FormObserver As New Form1
        FormObserver.MdiParent = Me
        FormObserver.Path = My.Computer.FileSystem.SpecialDirectories.MyDocuments
        _fileWatcherSubject.AddObserver(FormObserver)
        FormObserver.Show()
    End Sub
    Private Sub MDIParent1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        _fileWatcherSubject.Path = My.Computer.FileSystem.SpecialDirectories.MyDocuments
    End Sub
End Class
For complete Observer pattern code download at the following link.

fileWatcher.zip (116.6 KB)

I' m Learning Design Patterns

01.26.07

I received a great book from my girl friend this Christmas called Head First Design Patterns. I have been reading this book and it is really getting me excited (about coding patterns in case you needed clarification). To better understand these patterns I am going to try and code examples of each one and post my experience as well as the code on my blog. I will list the patterns so I can keep track of them as well as giving my one or two readers a heads up on what to expect.

All of these patterns and definitions are described in Head First Design Patterns by Eric Freeman & Elisabeth Freeman with Kathy Sierra & Bert Bates from O'Reilly

Design patterns

  • The Strategy Pattern (p24) - Defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
  • The Observer Pattern (p51) - Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
  • The Decorator Pattern (p91) - Attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
  • The factory Method Pattern (p134) - Defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
  • The Abstract Factory Pattern(p156) - Provides an interface for creating families of related of dependent objects without specifying their concrete classes.
  • The Singleton Pattern (p177) - Ensures a class has only one instance, and provides a global point of access to it.
  • The Command Pattern (p206) - Encapsulates a request as an object, thereby letting you parameterize other objects with different requests, queue or log requests, and support undoable operations.
  • The Adapter Pattern (p243) - Converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
  • The Template Method Pattern(p289) - Defines the skeleton of an algorithm in a method, deferring some steps to subclasses. Template Methods lets subclasses redefined certain steps of an algorithm without changing the algorithm's structure.
  • The Interator Pattern (p336) - Provides a way to access the elements of an aggregate object sequentially without exposing the underlying representation.
  • The Composite Pattern(p356) - Allows you to compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
  • The State Pattern(p410) - Allows an object to alter its behavior when its internal state changes. The object will appear to change its class.
  • The proxy pattern(p460) -  Provides a surrogate or placeholder for another object to control access to it.

Universal/Global Spell checks vs Free Dyslexic Helper, System Wide Spell Check

01.26.07

I have been looking for a good universal or system wide spell check for a long time I finally gave up and coded one for my self. I really like my spell check its simple and its fast. Basically it takes two key strokes to use, one to copy the text, two to launch the spell checker with a global assigned hot key. After you have corrected the spelling you paste it back. That is it, simple and fast. Do me a favor anyone that reads this blog compare what I threw together to some of the others. If enough people use/like my spell check I could add some new features like an auto-update and optimizing its memory usage.

My Spell check
Dyslexic Helper - System Wide Spell check.

Others

Enso Words 39.95 - This one takes way to many key strokes and seems too intrusive on what you are doing. I didn't want something to take up my whole screen and all of my attention. It is however very clever program and well done.

GlobalSpellChecker (freeware) - I like it, its free, and it contains a dictionary(very cool). But it uses the Microsoft Word spell checker and you have to leave the keyboard and actually access the program with your mouse, I guess you could combine it with slickrun to make this faster. It also looks like it only does one word per call to GLobalSpellCheck.

Spell Check Anywhere $29.97 - It seems to be the same as what I have done but you have to pay for it.

Throw vs Throw ex - The Why

01.17.07

I was talking to a friend of mine and he found my example of throw vs. throw ex interesting but he asked me a question that I didn’t expect, he asked me, "why?" I simply replied, "I don’t know, just don’t do it." But his insightful question made me curious. The answer to the question is in the real .Net language, the IL. When you compile your C# or VB.Net code just plain Throw becomes ReThrow but if you write Throw ex it becomes throw. In the IL snipit below Look at line 13 for JustThrowIT and line 14 in ThrowEX.

.method private instance void JustThrowIT() cil managed
{
      .maxstack 2
      .locals init (
            [mscorlib]System.Exception exception1)
       L_0000: nop
       L_0001: nop
       L_0002: ldarg.0
       L_0003: callvirt instance void throwDemo.Form1::ThrowsExceptions()
       L_0008: nop
       L_0009: leave.s L_001c
       L_000b: dup
       L_000c: call void [Microsoft.VisualBasic]
Microsoft.VisualBasic.CompilerServices.ProjectData::SetProjectError([mscorlib]System.Exception)
       L_0011: stloc.0
       L_0012: nop
       L_0013: rethrow
       L_0015: call void [Microsoft.VisualBasic]
Microsoft.VisualBasic.CompilerServices.ProjectData::ClearProjectError()
       L_001a: leave.s L_001c
       L_001c: nop
       L_001d: nop
       L_001e: ret
       .try L_0002 to L_000b catch [mscorlib]System.Exception handler L_000b to L_001c
}
.method private instance void ThrowEX() cil managed
{
      .maxstack 2
      .locals init (
            [mscorlib]System.Exception exception1)
       L_0000: nop
       L_0001: nop
       L_0002: ldarg.0
       L_0003: callvirt instance void throwDemo.Form1::ThrowsExceptions()
       L_0008: nop
       L_0009: leave.s L_001c
       L_000b: dup
       L_000c: call void [Microsoft.VisualBasic]
Microsoft.VisualBasic.CompilerServices.ProjectData::SetProjectError([mscorlib]System.Exception)
       L_0011: stloc.0
       L_0012: nop
       L_0013: ldloc.0
       L_0014: throw
       L_0015: call void [Microsoft.VisualBasic]
Microsoft.VisualBasic.CompilerServices.ProjectData::ClearProjectError()
       L_001a: leave.s L_001c
       L_001c: nop
       L_001d: nop
       L_001e: ret
       .try L_0002 to L_000b catch [mscorlib]System.Exception handler L_000b to L_001c
}
The ReThrow will pass on exception details were the throw is starting from scratch.

Microsoft Home Server

01.12.07

I just found out about Microsoft Home Server it was unveil at the Consumer Electronics Show in Las Vegas. I am very excited about the possibilities of this product it sounds like its main purpose is backing up your Data, File Share, and Remote data access. This is awsome for people like me who have a media center computer, laptop, and a desktop. The best description I can find so far is an interview Tod did from Geek News Central Pod Cast.

Style Helper/Color Converter

01.02.07

I found out that editing Cascading Style Sheets (CSS) for my blog as well as other projects can be really annoying, mostly when you are playing colors and font. I find my self constantly editing one number in a color hex set, saving the CSS file, hitting CTRL + F5, and then waiting for browser to refresh. My solution for this was a quick windows app I put together to help me coordinate my colors and font.


This app is very simple, to use it all you have to do is either enter the hex values or click on the buttons next to them choose the proper color or text from the dialog. You can also use dialogs to convert RGB to hex or hex to RGB.

Feel free to downlaod and use this application as much as you like.
DOWNLOAD
StyleHelper.exe (64 KB)
If you would like to see how it works or add more to it you can download the source.
StyleHelper.zip (110.3 KB)

Throw vs Throw ex

12.27.06

A common mistake a lot of new .Net developers do is using Throw ex instead of just Throw. The difference between Throw ex and Throw is very simple but can cause major headaches when it comes to maintenance. If you use Throw ex it overwrites the stack trace this makes it very hard to find the original line of the thrown exception as you can see in the example I have provided.
Public Class Form1
    Private Sub ThrowsExceptions()
        Throw New System.Exception("Exception Thrown") 'Line 3
    End Sub
    Private Sub JustThrowIT()
        Try
            ThrowsExceptions()
        Catch ex As Exception
            Throw 'Line 9
        End Try
    End Sub
    Private Sub ThrowEX()
        Try
            ThrowsExceptions()
        Catch ex As Exception
            Throw ex 'Line 16
        End Try
    End Sub
    Private Sub ThrowEX_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button1.Click
        Try
            ThrowEX() 'Line 21
        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try
    End Sub
    Private Sub JustThrowIt_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button2.Click
        Try
            JustThrowIT() 'Line 29
        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try
    End Sub
End Class

When you click the Throw ex button you get only get references to two lines 16 and 21 the original line the exception is thrown is missing(line 3).



When you click the Throw button you get the full stack trace including the line of the original exception that was thrown.



Download Source.
throwDemo.zip (47.73 KB)

My Wish List

12.22.06

I think one of the hardest parts of becoming a successful and educated programmer (besides just sitting down and coding) is finding good tools and resources to learn from and use. I put a lot of effort into finding these. In order to find these tools and recourses I look toward programmers I consider successful, most of which are listed under the Developer and Technologist Journals on my site. So far I have found frequent references to the following books and tools, these are on my to read/buy list.

Book Wish List
Tools Wish List
Tools and Resources I Own & Recommend
  • Reflector for .NET - Reflector is the class browser, explorer, analyzer and documentation viewer for .NET. Reflector allows you to easily view, navigate, search, decompile and analyze .NET assemblies in C#, Visual Basic and IL.
  • Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers.
  • Head First Design Patterns:  I got this book for Christmas, thank you Minette and Jesse, it is an entertaining read and easy to understand.