Long time no see!

So it’s been an awfully long time since my last post, and I’m aiming to bring my blog post entries up to speed with my everyday workings and discoveries – So with that I’ll introduce my most recent GitHub project.

This project is aimed at people who’ve been looking at utilising MEF (Managed Extensibility Framework) but are overwhelmed with the amount of refactoring that would be involved to implement it. 

As with any framework, you need to weigh up the pro’s and con’s of each solution, and compare many solutions to find the closest fit to your needs. I think it’s naive for anyone to think that a single framework would cover their project’s every need, but by matching a framework as close to your requirements as possible means that bridging the gaps is a relatively small cost. Especially when you compare to to refactor hell to make your application fit the framework.

One other thing – If you’re starting a new project, this whole post may be irrelevant as you have the freedom to make the design choices when orchestrating your application. Whereas a LOB (Line of business) application that is mature, or a project that has limited staff resources may struggle and so I’m going to introduce a more simplistic choice for anyone that may need it.

Plugins

I’m sure that you’ve heard many people before use new and trendy development buzz words like SoC (Separation of Concern), or Loosely/Tightly coupled. Though these words have been trending recently, their core concepts have actually been in the minds of developers for decades. 

Q. What is a ‘loosely coupled’ system? Loosely couple first off is not an innuendo though I would welcome a few laughs/suggestions in the comments. I will instead steal the wikipedia definition of the term because I think it’s the clearest explanation without getting into technicalities of development:

In computing and systems design a loosely coupled system is one in which each of its components has, or makes use of, little or no knowledge of the definitions of other separate components.

Q. How does loose coupling relate to SoC? Hopefully if you’re a programmer you’ll notice that by the definition of loose coupling it almost enforces a Separation of concern. By loosely coupling components when you develop them, you will ensure that components are only dealing with the process they are contained to, and there is no dependency leaking.

Plugins are the best form of SoC

That’s a pretty bold statement I agree, but by physically separating the functionality to a plugin architecture you’re fully separating your business logic with a clear and concise boundary. By having such a clear boundary you’re enabling your application to not worry about the specifics of something like, for example, calculating a shipping cost.

There are of course some draw backs to this, by having such a large boundary you can create some tight dependencies due to the way the .NET framework is composed.

There used to be a namespace of System.AddIn but this is no longer the Microsoft recommended route of implementing plugins – they instead recommend the MEF which can be difficult to bolt on to an existing mature product. 

By utilising a dynamically invoked external assembly (DIEA – Yeah I actually just made that up!) you can implement specific endpoints of OO code with a single line of plugin implementation rather than refactoring your whole class to fit an MEF system.

The drawbacks

Unfortunately this is a difficult thing to get a good example of, but I’ve put up my solution on GitHub that will allow you to get a basic working example. It’s already defeated the main issue with dynamic assemblies, by using CrossDomainMarshalling.

Benefits

  1. It allows us to instaniate our assembly in a different AppDomain, which means that if they’re any fatal errors in the plugin, it doesn’t bring your whole application down. Just the AppDomain it was loaded into.
  2. It allows us to only hold a lock on the assembly for the lifetime of the secondary AppDomain, rather than the entire lifecycle of the application.
  3. Lastly, it allows plugins to be invoked which reference different versions of 3rd party components (such as NLog)

When you’re done with your plugin, you simply unload the AppDomain you created and all the tear-down is done by .NET to release assembly locks meaning you’re able to update these plugins from within your own application without having to shut down.

Please take a look at the code on GitHub and if you have any feedback or suggestions I’m always eager to learn from others experiences.

Advertisements

Isotope & Knockout.js Mashup

I’ve been prettty busy learning some new tech recently so I’ve been too busy to write for a while. Today, I’ve been working on something internally for my employer, and found the need to combine Knockout.js with Isotope.js – However this was not as straight forward as I had originally thought as Isotope doesn’t re-evaluate it’s items, and doesn’t re-evaluate it’s size either.

So I came up with the following Custom Knockout Binding, which makes applying Isotope with Bindings on many elements a breeze. I hope this helps someone else who needs it!

jsFiddle: http://jsfiddle.net/uk6yt/6/

Transparent Proxy Service Locator

Quick Note: Just published a quick release of a service locator pattern that uses a transparent proxy to invoke the methods on all implementations of a service without the visibility there may be more than one instance of the service.

It’s probably not the best fit for a full service locator pattern, but using the transparent proxy to intercept the method calls will definitely find a use somewhere! 

See: https://github.com/abbottdev/ProxyServiceLocator

Plugin based development

Plugin based development


I’m currently working on a software project for a well known Church based over in Los Angeles where we are installing an online ordering portal, the site in question uses ASP NET Webforms, but is an LOB (Line of Business) application used by many over vendors in our market. We need to integrate with the customer at the payment stage in order to:

  1. Update their internal system with the information from our system.
  2. Collect payment for the order.

Code

As we need this system to be totally independent of our core system, we need to be able to reference these “Plugins” from an outside source, but we need to know what these interfaces actually do!

The answer is simple. Interfaces.

An interface is a method of declaring what properties, methods a particular CLR type is compatible with. Most of us use this without knowing about it every day, when you use:

For Each item in collection
    item.PerformAction()
Next item

You are actually referencing the IEnumerable(Of T) interface, which tells the compiler I am able to Enumerate and yield a value several times from this object.

So, we’ve decided that we need an Interface, but how do we actually load these dll’s at run time? It can be a big question at first, (it was for me) – but after consulting with Dr. Google I found the classes I needed.

First, System.Assembly. It provides us with all the gubbins we need to load and inspect an assembly dynamically at run time.

assemblyToLoad = System.Reflection.Assembly.LoadFile(file)

This function will physically load the CLR with this assembly, in order for us to inspect it using the System.Type class.

Dim interfaces() As System.Type
interfaces = assemblyToLoad.GetExportedTypes()

So a couple things to note on the above example, first, we are using “GetExportedTypes.” The reason you want this method is because it only returns the types that are availiable to anything external. If you use the other methods, you may find more interface implementations than you were supposed to, or, you’ll find internal .NET generated classes like MySettings classes. Public declarations were invented for a reason – Make sure you use them correctly!

So, if we put what we know together we could make this a nice generic function, and for extra type safety we include a base “IPlugin” interface, it allows us both sides to ensure the class/interface we are loaded was meant to be a plugin. Here’s the code in full:

Public Class Plugins

    Public Interface IPlugin
        Property AssemblyPath As String
    End Interface

    Public Shared Function EnumerateFolder(Of T As IPlugin)(ByVal directory As String) As List(Of T)
        Dim assembly As Reflection.Assembly
        Dim foundPlugins As New List(Of T)
        Dim types() As Type
        Dim filter As Reflection.TypeFilter
        Dim plugin As T

        filter = New Reflection.TypeFilter(Function(m As Type, criteria As Object)
                                               Return True
                                           End Function)

        For Each file In IO.Directory.EnumerateFiles(directory, "*.dll", IO.SearchOption.TopDirectoryOnly)
            Try
                assembly = System.Reflection.Assembly.LoadFile(file)

                For Each foundType As System.Type In assembly.GetExportedTypes
                    types = foundType.FindInterfaces(filter, Nothing)

                    If types.Contains(GetType(T)) And types.Contains(GetType(IPlugin)) Then
                        plugin = Activator.CreateInstance(foundType)
                        plugin.AssemblyPath = file
                        foundPlugins.Add(plugin)
                    End If

                Next
            Catch ex As Exception
                'not a .net assembly
            End Try
        Next

        Return foundPlugins
    End Function

End Class
Enjoy.

Wow, that was quick.

Hey, no wise cracks on this blog title.

Oh wait, that wasn’t any better.

This afternoon I’m writing about a quick problem I had with SQL and colours. Visual Basic 6 is notorious for storing colours, you can only store them as an integral value – a 64 bit integer (a whole number for you non-techies.)

Obviously, some critter decided it would be a wise idea to store the value in the database in it’s obsolete form. I say obsolete, because even Microsoft have moved to Hexadecimal string values as a default value for WPF colour values and brushes.

So, what’s the problem?

We have reports that are required by clients, on these reports a colour is displayed that should be shown from the database. The problem being, however, is that the data type that we store the value as (int in SQL) actually means that the report can’t show this format. Instead, what has happened is that extra fields have been added to the database for customers.

This is bad.

Not only does it create a problem for continuous integration (software updates and database schemas) – but it also results in non-maintainable data in the database. What happens when the customer changes the colours, or adds a new one. This new “special hex string field that someone thought was a good idea” immediately becomes wrong. And if there’s one thing worse than non-maintainable data, it’s wrong non-maintainable data.

Why is this bad I hear you say

This is one of the most common problems with software development. When you create a new entity that no one else knows about, it means that it will break. Software breaking = bad. The value will be wrong, the user experience will be terrible (Fancy that, some text saying the colour is Yellow when in-fact the colour is something totally different and irrelevant. This confuses users and only makes your software look bad.

The golden answer.

OK – OK, I hear you, you’re a developer you already know all the nuances of the trade, tell me how to god’damn fix it.

Fair enough. One of the nicest features I’ve found for problems like this is a little thing known as “User Defined Functions” (MSDN Link). You can create one of these to execute a function on a specific value in your database. Ah, I hear you say, let’s convert the value to a HEX string in the function, then we don’t need to add new columns, all the existing applications continue to work as expected. Everyone wins.

The code looks a little like this:

CREATE FUNCTION ToHexColor(@value int)
    RETURNS varchar(50)
AS
BEGIN
   DECLARE @result varchar(50)
   SET @result = [master].dbo.fn_varbintohexstr(@value)
   SET @result = '#' + UPPER(RIGHT(@result, 6))
   RETURN @result
END

This snippet uses a built-in function “fn_varbintohexstr” that actually does most of the heavy lifting for us. This converts our integer value to HEX as so: 0x00ffffff – which is good but not quite there. The 0x signifies the value is a Hexadecimal value, so that can go. Second, HTML does not support alpha blending in it’s colour representations. So we crop these off, add a hash and the database value is now directly bindable.

Lovely.

The moral of this story, check with your developers before adding new fields, and always remember the simplest, easiest solution to maintain is always the best.

Abiento!

myFirstBlogPost.publish()

Being tradition I’m going to use my first blog post as a bit of an introduction about myself, what I do, and where I’m going.

So my name’s James, I’m 23 as of writing this blog post. (Yeah, I know I’m a youngster, and I might not know what I’m talking about) However, unlike most my age I’m mature enough to listen and take in advice if I’m wrong about something so please feel free to correct me. The sole purpose for my blog is education, to make being a great software developer an easy and achievable task!

I work in Leeds, a city in England at a software house that produces management and data capture software for the print & media industry. I’m the youngest developer at the company, but (without bigging myself up too much) I’m probably one of the most competent there. (Hey, when it comes to your job confidence is good!) We’ve got a few skilled people here, and we consistently work as a team and produce some of the best products availiable in our industry, breaking bounds and introducing new technologies to make our customers more effective.

That being said, my particular areas that I specialise at my work are:

  1. VB6 development (You may say “Yawn” or you may say “WTF, you’re a little too young for VB6?”) I’ll start by saying you’re right, on both counts. Visual Basic 6 is tedious and slow. But what do you expect for a product that was release when I was 9. I know this stuff, because I learnt Visual Basic 5 (Yep, even older) when I was at Junior School. (Forgive the UK/US school grades, whatever grade you were when you were 10)
  2. VB.NET Development. This ones a lot more up to date. I work with most versions, starting at 2.0, through to 4.5 (the latest one).
  3. WPF Development. This has been a personal passion of mine, ever since I first laid eyes on the technology in use (those lovely looking Windows messenger UIs when they first came out) I’ve wanted to duplicate it.
  4. ASP development. Oh, yeah, did I say I was old skool? I’ve got dozens of projects written using classic ASP, and ASP WebForms. One of my aims over the next few years it to work on more MVC webs, and make use of the benefits of a loosely coupled architecture brings.
  5. SQL Server. Lucky you. I’ll be providing some resources on SQL Server, (specifically Microsoft SQL Server) – and Azure. (I’ll also touch on some No-SQL alternatives)
  6. ORM wrappers. (For those of you who’re unsure, that stands for Object Relational Mapper)
  7. And the rest that I don’t have time to go into more detail today; JavaScript, HTML, CSS, XML/XSL, PLC, Micro framework, Win Mobile, and Windows 8 development.

Anyway, I could ramble all day, but I think that’ll do for my first post.

I hope you enjoy the deliciousness of my blog, as much as I enjoy sharing the information.

Until next time!