Sunday, March 16, 2008
Time to use an Ioc (Inversion of Control) container like structuremap. Most if not all examples you find on the net are in C# but us VB.Net developers aren't imune for it either. So today I made my first project with structuremap. Lets' see how it goes. Thanks to Jeremy D. Miller for making this great product.

I used the atributes for this and not the external config file (aka: StructureMap.config).

I will demonstrate this by crating a Dal, A model and A view/presenter. Let's start with the Model

the interface

Namespace Model.Interfaces
    Public Interface IPerson
        Property Id() As Guid
        Property LastName() As String
        Property FirstName() As String
    End Interface
End Namespace

the implementation

Namespace Model
    Public Class Person
        Implements Model.Interfaces.IPerson

        Private _lastName As String
        Private _id As Guid
        Private _firstName As String

        Public Sub New()
            _id = New Guid
            _firstName = ""
            _lastName = ""
        End Sub

        Public Property FirstName() As String Implements Interfaces.IPerson.FirstName
            Get
                Return _firstName
            End Get
            Set(ByVal value As String)
                _firstName = value
            End Set
        End Property

        Public Property Id() As System.Guid Implements Interfaces.IPerson.Id
            Get
                Return _id
            End Get
            Set(ByVal value As System.Guid)
                _id = value
            End Set
        End Property

        Public Property LastName() As String Implements Interfaces.IPerson.LastName
            Get
                Return _lastName
            End Get
            Set(ByVal value As String)
                _lastName = value
            End Set
        End Property

        Public Overrides Function ToString() As String
            Return _lastName & " " & _firstName
        End Function
    End Class
End Namespace


Nothing fancy, not even pretty. But it works.

Then the dal

I start with an interface for the factory.

Imports StructureMap

Namespace Dal.Factory
    <PluginFamily("SQLServerDaoFactory", Issingleton:=True)> _
    Public Interface IDAOFactory
        ReadOnly Property Person() As Dal.Interfaces.IPerson
    End Interface
End Namespace

And here we have the first attribute for structuremap. this says that if you want an instance of this interface that you will have to look for a class with an attribute plugable and a concretekey of "SQLServerDaoFactory" in other words this is the default implementation of our interface.

Now lets look at SQLServerDAOFactory.

Imports StructureMap

Namespace Dal.SQLServer
    <Pluggable("SQLServerDaoFactory")> _
    Public Class DaoFactory
        Implements Dal.Factory.IDAOFactory

        Public ReadOnly Property Person() As Interfaces.IPerson Implements Factory.IDAOFactory.Person
            Get
                Return ObjectFactory.GetInstance(Of Interfaces.IPerson)()
            End Get
        End Property
    End Class
End Namespace
so this has a plugabble attribute with SQLServerDaoFactory as key. So this is the default implementation for IDaoFactory.

Now we will create a form with 2 labels on them and One button. Just leave the standard, this is just to show how it works. I won't even bother creating a presenter, let's talk dirty.

In the form_load event you have to add this to intialize structuremap.

StructureMapConfiguration.UseDefaultStructureMapConfigFile = False
StructureMapConfiguration.ScanAssemblies.IncludeTheCallingAssembly()

And in the button_click event you have to add this

Dim a As Model.Person
Dim d As Dal.Factory.IDAOFactory = ObjectFactory.GetInstance(Of Dal.Factory.IDAOFactory)()
a = d.Person.FindPersonbyName("")
Label1.Text = a.FirstName
Label2.Text = a.LastName

Don't forget to add structuremap.dll as a reference and to do an imports of structuremap in the form.
As you can we are doing a getinstance on ObjectFactory this will get us the default implementation of DAOFactory. Namely SQLServerDAOFactory

So why are we doing all this? Since we could have just instantiated it the normal way without a problem.

What if we now needed to have a MySQL Database instead of SQLServer? in our normal program we had to change all the references from SQLServerDAOFactory to MySQLFactory with structuremap we just change the pluginfamily default value and create a new daofactory.

this is the new daofactory.

Imports StructureMap

Namespace Dal.MySQL
    <Pluggable("MySQLDaoFactory")> _
    Public Class DaoFactory
        Implements Dal.Factory.IDAOFactory

        Public ReadOnly Property Person() As Interfaces.IPerson Implements Factory.IDAOFactory.Person
            Get
                ObjectFactory.InjectStub(GetType(Interfaces.IPerson), New MySQLPerson)
                Return ObjectFactory.GetInstance(Of Interfaces.IPerson)()
            End Get
        End Property
    End Class
End Namespace


and this is the adapted idaofactory.

Imports StructureMap

Namespace Dal.SQLServer
    <Pluggable("MySQLDaoFactory")> _
    Public Class DaoFactory
        Implements Dal.Factory.IDAOFactory

        Public ReadOnly Property Person() As Interfaces.IPerson Implements Factory.IDAOFactory.Person
            Get
                Return ObjectFactory.GetInstance(Of Interfaces.IPerson)()
            End Get
        End Property
    End Class
End Namespace


and now run the code again and see the difference in the labels. So we have low coupling and high cohesion.

Hope to see you soon for part 2




3/16/2008 3:39 PM Romance Standard Time  #    Disclaimer  |  Comments [0]  |  Trackback
 Thursday, January 17, 2008
I think this is kinda neat ;-)

No more writting of compareto's or equals just use linq.


Dim _Directories() As String Dim _Directory As String Dim _DirectoryInfos As New List(Of DirectoryInfo)

_Directories = Directory.GetDirectories("c:/")
For Each _Directory In _Directories
Dim directoryinfo As System.IO.DirectoryInfo = New System.IO.DirectoryInfo(_Directory)
_DirectoryInfos.Add(directoryinfo)
Next ' Run LINQ Query Dim _DirectoryInfosOrderedByCreationTime = From DirectoryInfos In _DirectoryInfos _
Order By DirectoryInfos.CreationTime Descending _
Select DirectoryInfos

' Display results of query If _DirectoryInfosOrderedByCreationTime.Count > 0 Then For Each DirectoryInfo In _DirectoryInfosOrderedByCreationTime
TextBox1.AppendText("Directory: " & DirectoryInfo.FullName & " Date: " & DirectoryInfo.CreationTime & ControlChars.CrLf)
Next End If



1/17/2008 11:16 PM Romance Standard Time  #    Disclaimer  |  Comments [3]  |  Trackback
 Tuesday, January 15, 2008
The first one is about MVP and dependecy injection and threading.

And Allthough it's not perfect it does explain a lot. However, agian the example is to simple and therefor more work needs to be done to really understsand the concepts.

The next one is about SQL-Server interview questions.

A bit different from the one on Denis' page but still contains a few usefull tips.

The third and last one is an introduction to Object oriented programming concepts.

What can I say. Sometimes a bit simple. But simple can be good.

1/15/2008 9:13 AM Romance Standard Time  #    Disclaimer  |  Comments [0]  |  Trackback
 Friday, December 21, 2007
What is wrong with adobe, are they trying to ruin a very good product? Today I downloaded a pdf-fiel and guess what, I didn't seem to have any pdf-reader on my laptop. Not so strange Since I just reinstalled it. So I let windows Cp do it's work and search for a program online thinking it would find acrobat reader but no it found nothing that could open a pdf file. And that was the first strange thing. So I looked for it via google and found the dutch downloadpage.
I use Firefox but I didn't really read the fineprint or not so fineprint. So it instaled a plugin really fast after asking if it could but what choice do I have, nothing bad happend it happens to be a pretty good downloadmanager. So then it starts downloading and installing. Nothing bad but still, why are people thinking that they can any people by instaling more things then I need or want.
And then the good part. Right after instalation it tells me I need to update, for Gods sake, I just installed a brand new version. Please Adobe be good and clean up your act, remember less is more.


12/21/2007 8:18 PM Romance Standard Time  #    Disclaimer  |  Comments [0]  |  Trackback

My explanation


Well there seems to be some confusing opinions on the net over what OOP seems to be. I've been reading up on the concepts of OOP after a little discussion with our teacher yesterday where he did most of the talking.

He followed the APIE principal

  • A = Abstraction
  • P = Polymorphism
  • I = Inheritance
  • E = Encapsulation

1. Abstraction


Not many sites talk about this concept as part of OOP but apparantly this means that abstract real world things to your code, for example Car, Vehicule, Sportscar, ... become objects. So you try to mimic Real world objects into an OO model.


2. Polymorphism


According to the teacher (who I hope will read this and orrect me), polymorphism is the fact that a certain object can be different at designtime then at runtime.

For example: A car is a vehicle and a sporstcar is a car. A vehicle has a max-speed of 80 and a car a max-speed of a 100 and sportscar a max-speed of 120. They all share the same method getspeed. At designtime you do this.

More or less pseudocode.

Vehicle vehicle = new Vehicle();
print vehicle.getspeed(); // This will give you 80

Vehicule vehicle = new Car();
print vehicle.getspeed(); // This will give you 100

Vehicle vehicle = new SportsCar();
print vehicle.getspeed(); // This will give you 120

So the vehicle is always of type Vehicule but depending on the implementation it will return a different speed.

3. Inheritance


A. The subclass inherits the methods of its superclass.
B. The subclass can add methods other then the once of the superclass.
C. The subclass can implement a method of the superclass differently via overriding.

4. Encapsulation


The hiding of your private attributes via public getters and setters.


Other explanations


I can live with the above, but I also like the opinion of others and they seem to differ somewhat.

This site seems to be in agreement somewhat.


This site seems to have a different concept of polymorphism.

According to them polymorphism is nothing more then overloading and overriding

This professor of an Austin, TE college seems to forget about abstraction.
Here he talks about Encapsulation.
Here about Polymorphism.
Here about Inheritance.

And this one tries to be too simple. Starting here.

So if anyone can come up with a better site please do.



12/21/2007 10:31 AM Romance Standard Time  #    Disclaimer  |  Comments [0]  |  Trackback
 Tuesday, October 09, 2007
Today I had a little problem with component mapping and the attributes. And It has something to do with the fact that all my objects use interfaces.

I had this in my MspResult class.

<NHibernate.Mapping.Attributes.ComponentProperty(componenttype:=GetType(Littlexyz))> _
        Public Overridable Property Littlexyz() As Interfaces.ILittleXyz Implements IMspResult.Littlexyz
            Get
                _Log.LogDebug("Property Littlexyz - returning _Littlexyz")
                Return _littlexyz
            End Get
            Set(ByVal Value As Interfaces.ILittleXyz)
                _Log.LogDebug("Property Littlexyz - setting _Littlexyz")
                _littlexyz = Value
            End Set
        End Property
And this in the Littlexyz class.

<NHibernate.Mapping.Attributes.Component())> _
    Public Class Littlexyz
        Implements ILittleXyz

#Region " Private members "
        ''' <summary>
        ''' A local variable called _x of type Decimal
        ''' </summary>
        ''' <remarks>Has Property X</remarks>
        Private _x As Decimal

Which gave me this error in nhibernate

NHibernate.MappingException: Problem trying to set property type by reflection ---> NHibernate.PropertyNotFoundException: Could not find field '_x' in class 'Model.Msp.Interfaces.ILittleXyz'

Which is completely correct since the interface doesn't have any private fields.
But the solutiion was simple ;-) as always it just took a little searching.
So i just changed the Littlexyz class to this.

<NHibernate.Mapping.Attributes.Component(classtype:=GetType(Model.Msp.Littlexyz))> _
    Public Class Littlexyz
        Implements ILittleXyz

#Region " Private members "
        ''' <summary>
        ''' A local variable called _x of type Decimal
        ''' </summary>
        ''' <remarks>Has Property X</remarks>
        Private _x As Decimal

Which does exactly what I want and what it should.



10/9/2007 4:08 PM Romance Daylight Time  #    Disclaimer  |  Comments [0]  |  Trackback
Just so I don't forget this is the syntax.
Imports Lan = Langauge

Where Language is the namespace and Lan is the alias.

And not the other way round which I apparently find more logical.

Especially usefull if you got a namespace and a variable that share the same name (which shouldn't happen ;-)).


10/9/2007 1:49 PM Romance Daylight Time  #    Disclaimer  |  Comments [0]  |  Trackback
Balls

Try it, on a dual monitor setup it is even more fun since the balls can't pass the border.

10/9/2007 1:30 PM Romance Daylight Time  #    Disclaimer  |  Comments [0]  |  Trackback
So someone tell me why you get to this blog by searching viagra? I never used the word :-).



10/9/2007 11:25 AM Romance Daylight Time  #    Disclaimer  |  Comments [0]  |  Trackback
Allthough I don't get them very often Nullref exceptions do happen and guess what they even happen with VS




This ussually means I have to restart VS ;-).
10/9/2007 11:21 AM Romance Daylight Time  #    Disclaimer  |  Comments [0]  |  Trackback