Category Archives: Development

An Error of Judgement

I recently came to work and found that I had unwittingly coded a bizarre occurrence.  Unsure as to how I came across it, but thankfully it was spotted while I am still developing the solution.


The above error came as a result of this, this isn’t the error I saw in my application before spotting it, thankfully I spotted it before I built and test run the code.  But using a demo, this is the error I got, just to show you the result of this.  Below is the code that causes this;

class Program
	static void Main(string[] args)
		TestClass tempClass = new TestClass();

public class TestClass
	public int Id { get; set; }
	public string Name { get; set; }

	public TestClass()

	public void LoadData()
		for (int i = 0; i < 10; i++)
			TestClass tempItem = new TestClass();
			tempItem.Id = i;
			tempitem.Name = string.Format("My Name - {0}", i);

It might not be completely obvious but there is an infinite loop there.  Not in the traditional sense which is why it might not seem too obvious.  In the Constructor of TestClass I call the method LoadData.  In which I create a new instance of TestClass, which them again calls LoadData and so on.

Like I said not your typical infinite loop;

while (true)

Like above we can see that is will not exit this loop, but this one, will just cause the application to hang there.  The other ran into an error but the error, though correct might have you going down the wrong path.  Suffice to say I have fixed this, called the LoadData from the code path that creates the instance of the data, and the constructor is now empty.

Sometimes as programmers you have dumb moments, thankfully it got caught before it gets put into a production environment.

XNA and Visual Studio

Much of what I might say will most certainly not be supported.  Which is not a big problem as the I am sure XNA is not properly supported at the moment.  But XNA is a VERY good set of tools to help people learn the process of games programming.

You might find that when trying to install XNA Game Studio 4.0

I found this post Installing XNA on Windows 8 with Visual Studio 2012.  I followed this very post for Visual Studio 2013 and despite the folder differences and one MSI not installing, it worked.

Visual Studio 2013 will be within;

  • \Program Files (for 32 bit versions of Windows)
  • \Program Files (x86) (for 64 bit versions of Windows)

The folder referenced in this post is

Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\Extensions\Microsoft

So follow the post as it states with the follow changes;

Step 6.  This MSI might not run.  I ran this MSI and I found it caused an error.  There could be a couple of reasons for this, the Main installed asks about enabling settings through the Windows Firewall before the installation starts but it might be just my machine.  Is this required?  My believe is, it enables the ability to communicate with the Xbox 360 components to perform debugging on a console (I did like this feature version much).  But as the Xbox One is the console of choice from Microsoft and their next version of Visual Studio will have the support for the DirectX 12 games this will be moot.

Step 9.  This is the path that will differ for Visual Studio 2013 over 2012.  So each reference to “Microsoft Visual Studio 11.0” in the path replace with “Microsoft Visual Studio 12.0’

Step 11.  Use the “Microsoft Visual Studio 12.0” path as opposed to “Microsoft Visual Studio 11”

Once this is complete then the framework will work in Visual Studio 2013 in Windows 8.

New Project

  1. Open Visual Studio (I was performing this in Visual Studio Community 2013 ). 
  2. Click File | New Project
  3. Under Templates, look for Visual C# and you will find XNA Game Studio 4.0, click that item.
  4. Click Windows Game (4.0)
  5. Click OK
  6. Wait until the project loads and Press F5 (Click Debug | Start Debugging)

You will find that wonderfully familiar but also quite strange blank screen of a blank XNA project looking at you.


Why would I use XNA in Visual Studio 2013?

It is an interesting question.  Microsoft has moved away from this framework in favour for a closer to metal approach with DirectX in Store/Phone or Universal Apps.

My opinion is, utilising the newer methods to create games is more difficult from an absolute beginner’s perspective.  Game Development is tricky for seasoned developers if you think you know the way it works, but when starting new the XNA Framework offered a very simple perspective to getting simple things working on screen.

There has been many games released that were made using the XNA Framework (See 6 Partial list of games that use XNA for more information).  But it is a shame in my opinion that Microsoft discontinued this as it was a great addition.  I know why, unified platform was the direction they were heading, which is why when Windows Phone was released, Windows 8 and then an update to the Xbox 360 OS saw a common look and with Windows 10 they have brought all their platforms together creating an App for Windows 10, Windows Phone and Xbox One should now provide a single set of source.  XNA thought simple merely muddied the waters as a game for Xbox and Windows had a the same content pipeline but created 2 different projects.

Why bother when the paradigm is changing with VS2015?

Visual Studio 2015 will provide support for DirectX 12 coming with Windows 10.  It will also provide additional frameworks for game development in Cocos2d, Unity and Unreal Engine 4.  Each of these frameworks are available and provide the ability.  The benefits of these frameworks is cross-platform compatibility, XNA is not that.

This starts to become a personal problem, do I learn with Unity or Cocos2d, hell why not go for learning with CryEngine.  You can and the tools are available there.  Many might think that it is better to use the tools you might be using later.  I can’t argue with that logic as it is sound.  As long as you don’t get bogged down in the tedium of ensuring the Graphics devices are setup right, the content pipeline is able to properly and quickly convert your content into assets available for your code to use then great.  XNA does this, setting up the graphics device is as simple as 2 lines of code.

GraphicsDeviceManager graphics;
graphics = new GraphicsDeviceManager(this);

Drawing something to the display is almost as simple with a few more lines of code.

SpriteBatch spriteBatch;
spriteBatch = new SpriteBatch(GraphicsDevice);
spriteBatch.Draw(Game1.SpriteSinglePixel, new Rectangle(0, 0, Game1.SCREEN_WDITH, Game1.SCREEN_HEIGHT), Color.DarkGreen);

And a blank provides you most of the code, lines 3 to 5 above are the only ones you need to add yourself to draw something to the screen.  This isn’t a tutorial on coding XNA merely an example of the simplicity of it.  I have yet to delve into Cocos or Unity to determine the simplicity or difficulty of it but I have had experience in XNA and have developed 3 games using it.  And being a 20 year veteran of commercial application development and I have been trying to get into the Game Development side of it.  I found personally XNA was simple enough to get me up and running quickly but also powerful enough to enable more complex things and larger games.

My games were nothing to write home about but I got them up and running in a short period of time.

But Why?

Why, because I can.  It has been a scourge of my industry for years the pace of technology and the people who use it, lag behind and you are lost.  I spent years developing Visual Basic 6 applications and when time to come to find new work I found I was on the outer, .NET had taken over and it took me a few year of different jobs to build up my experience enough to be able to secure a .NET development role.  So thinking alone these lines I should learnt to adapt quicker and move forward into using the new technology.  But when I do not have the fundamentals of game development down, understanding the graphics process the content pipelines the waiting for action as opposed to reacting to action, each of these are vastly different in the commercial world and thus I need to get my head around them, but in order to get my head around the concepts I need to remove elements that can trip me up, like the technology, like languages like platforms.

Understanding things without those distractions will make my process a less painful one.  And since I struggle to find time to be able to sit down and do any form of coding or learning in this area (let alone write a blog post, hence my LONG time absence) I need to be able to hit the ground running and get as much done as possible.

Want to go further

Once you have gotten into XNA you will find there is more to it than what Microsoft stopped with.  Check out MonoGame which provide that extension to more modern platforms and also that Cross-Platform extensibility of the newer frameworks.

End Goal

A game for my boys to play. 

The Scourge of the Google Coder

This above all””: to thine own self be true, and it must follow, as the night the day, though canst not then be false to any man.

William Shakespeare, Hamlet

There is much the internet has given us but one area which many people seem to lose site of, as its integration with the every day seems so entrenched that one doesn’t know life without it.  Why did I quote Shakespeare and then talk about the internet?  I will get there.

But first, the title.  The Google Coder and I am not referring to the person who does development work at Google.  I am talking about a person so adept at finding any piece of code on the internet and using it within their application.  What is wrong with this?  Lots.

See the code below.

Module Main

    Private Const DO_NOT_EXCEED As Integer = 4000000
    Sub Main()
        Dim firstNumber As Integer = 1
        Dim secondNumber As Integer = 2
        Dim newNumber As Integer = 0
        Dim evenSum As Integer = 2

        'Display the first number numbers

        'While the new calculated number does not exceed the max amount
        While newNumber < DO_NOT_EXCEED
            'Calculate the next number in the sequence
            newNumber = firstNumber + secondNumber

            'ouput the new number

            'Flip the values around for calculation
            firstNumber = secondNumber
            secondNumber = newNumber

            'Check to see if the number is an even one
            If newNumber Mod 2 = 0 Then
                'Check to seed if the number does not exceed our max
                If newNumber > DO_NOT_EXCEED Then
                    'if it does, exit the loop
                    Exit While
                End If

                'add the number as it is an even number.
                evenSum += newNumber
            End If

        End While

        'output the answer
        Console.WriteLine(String.Format("The sum of the even numbers in a fibonacci sequence that do no exceed {0}", DO_NOT_EXCEED.ToString()))
    End Sub

End Module

This is a solution to a problem posed;

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

This is my code, hand written without help from anyone.  The problem also comes from a site called Project Euler which sets out problems that is to be solved using a computer language.  The number of languages used is staggering for many they would be querying why are there so many languages when they all function to do the same thing, enable a computer to solve a problem.

But the purpose of it is to enable you as the developer to solve the problem using all your bags of tricks.  The problems are designed in a manner that often a large number are involved and often workout out problems based on these large numbers and working things out repetitively, the purpose built domain of the computer.  I might hear some people say, “why?”, “Why bother doing all that work, for nothing or doing all that work when you can easily look up the answer on Google?”.  True.

Why would I want to work out something on my own?  Why would I like to press submit on the answer screen and get a correct status up knowing that I did it, all by myself without any help and I got it right the first time.  I might not have been the first to do it, or written the prettiest code, the fastest code.  But to me, it isn’t the purpose.  When at work and I am writing code what is my objective with that specific problem.  Well to get the desire outcome.  It is a key for any developer to know the problem and understand it, then using the tools develop the solution.  Now often the problems are far more complex than determine the sum of the even Fibonacci numbers that is not greater than 4 million.

What would searching the answer or code to get the answer do for me?  Speed.  Nothing else, it doesn’t teach me anything, in fact I can go as far as saying many tutorials set up are great but don’t do much to aide in the learning process to enable proper retention, but that is something else.  I remember a while ago I competed in a coding competition which pitted developers against developers, with nothing but a barebones Windows PC and Visual Studio, no internet, no phones a pen and paper next to the PC.  We had to solve a problem, in a given timeframe.  I got into the top 10 but my time ran out.  But it was interesting to see that there were about 60% who dropped away after the first couple of problems, mutterings of it being impossible, anyone who solved it must have been cheating etc… I put these people into the Google coding camp, they were unable look for the solution on the internet and therefore they couldn’t work it out.

Is this detrimental to the overall coding quality?  Who knows?  I have seen some terribly written code in the years, not saying mine are works of art.  In fact the most efficient code is possibly not the easiest to maintain.  But it comes to this saying;

Only write the code that only you can write.

This comes back to the quote from Hamlet about being true to yourself.  In coding, one might think something like this

int myNumber = 10;

is the only way to increment 10 by one.  But what about the following;

int myNumber = 10;
myNumber += 1;


int myNumber = 10;
myNumber = myNumber + 1;


int myNumber = 10;
int i = 1;
myNumber = myNumber + i;

This is the issue as well.  Each of these do the right thing, they increment 10 by 1, but they use different methods to do this.  You might argue that the first version was the correct version.  But the others are also correct, they do the job, and if it is different to what you do, is it wrong no, it is an opinion.   But is that a problem for today where so many people believe their opinion is the right one and fail to understand that they have their opinion as well as I have mine and everyone else’s has theirs.

So, I guess what I am getting to is, write code, your way, the way you want to.  This might go against some other posts where I have spoken about terrible coding, but when you go to Google you aren’t writing your code.  By all means use it as a resource, find out the interface to the API workout what to put in, but don’t just copy and paste it as you will learn nothing.  Plagiarism is a problem with this world as we expand our use of the internet in all walks off life, it happened in University where there were always someone wanting to take the easy path, copy the code, rename the variables and move a few things around and boom, it is now yours.  But like all things it isn’t you if you do that, your techniques, approaches to development aren’t prevalent and if there is anyone who knows you will find that out.

Use the internet, but don’t rely on the internet and as technology becomes an ever increasing crutch the world relies on we will become more and more reliant on it being the correct answer to everything which puts Google (only because they are the dominant player in searching) in a position to fulfil any chosen agenda they wish and they are doing so, more than anyone knows.

The Patterns in a Practical Position

thc1bl12enPatterns, software development and the last 5-8 years have been pushing patterns.  Like Agile and SCRUMM (I know they are different), the new wave of development is the implementation of patterns into applications (they aren’t new, they are old but as we are developing more and more cross platform application across multiple devices it becomes more and more important to use familiar logic to hook our applications together with).

My biggest issue is not the use of them, they are great, they offer a wonderful reusable way of implementing common functionality throughout you application and then future applications with minimum fuss.  The best one recently I can think of is the MVVM/MVC and its purpose is to decouple the interface from the application, the purpose of this is to have a single backend code and the front end can be across multiple platforms and be native as they are all using the MVVM/MVC pattern.  But why am I?

Also note, MVC isn’t new (Circa. 1970s), but it has become an important part of mobile application development as you can’t always determine how you will connect to a backend and therefore keeping the UI separate means you, as the UI developer, only need to hook in the view to see it working and not concern yourself with calling specific methods, API calls or other more complex ways to get data in and out of an application.

So like Model View View-Model (Model View Controller) other pattern creep in and provide a mechanism to help make life easier for the developer, but there is one thing that irks me about new patterns.  Details, details and I will also say details.  It is all well and good to show me code, this is the way to implement the Snake Pattern; implement this interface, inherit these classes, create concrete classes from the interface, charm a snake and then, you will have your application.  Why?  Why am I doing this?  What purpose is the pattern in solving a problem, can this pattern be used on all applications across all platforms. 

I see code, it shows me how the person implemented this pattern.  I started by doing this, next I added this and this to implement this.  Next I, blah, blah and blah.  That is fine, following word for word code is fine, at the end I hit F5 and everything works, but why?    The one I see and it might be me and not understanding the purposes for such but a pattern was shown to me as a way of decoupling a class’s implementation from it’s abstraction enabling the two to vary from one another.  I understand abstraction, being a core component of object oriented programming, but the decoupling of it, my nature of the abstraction means no implementation of the class is in the definition of the abstraction (please tell me if I am wrong, I would like to know). 

But the remaining part of this article tells me how they did it, using a metaphor that isn’t common in the development of examples.  New technologies and learning new techniques and methodologies is difficult enough and keeping on top of them in an ever changing world is even more so.  So, telling me about useful patterns, Bridge, Adapter, MVC, whatever it might be is good, telling me it is for this, but tell me why, show me why, don’t make me just copy verbatim the code you have provided to make it work.  This means I won’t learn anything.

It has been a bug bear of mine over the many years of learning languages and learning how to program in those languages and it is the examples and the nature of telling me how to do this and that. 

When learning the basics, it is fine to say this is how you create variables

int varable = 1;

But when it comes to things more complex, give me more useful examples.  But it is a gripe and nothing to much other than this is the way I learn new things. 

Javascript Error in AjaxControlToolkit

thC1BL12ENDocumentation for this is sketchy at best, but I am unsure if this is the solution for all instances of the error.  The AjaxControlToolkit, is a nice addition to the ASP.NET stable, managed on Codeplex this enables you to include extenders that provide useful and sometimes just nice features to the existing toolkit of server side controls in ASP.NET.

Following their examples, I wanted to include a simple Password Strength extender to a password box.  Sounds simple, since as users type in their password it gives and indication of how good their password is.  This is merely a visual indicator and not anything to do with validation or what is acceptable.

I follow their coding example, which is below.

&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;;&gt;
&lt;html xmlns=&quot;;&gt;
&lt;head runat=&quot;server&quot;&gt;
&lt;title&gt;Control Toolkit&lt;/title&gt;
&lt;form id=&quot;form1&quot; runat=&quot;server&quot;&gt;
&lt;asp:ScriptManager ID=&quot;asm&quot; runat=&quot;server&quot; /&gt;
&lt;asp:TextBox ID=&quot;Password&quot; runat=&quot;server&quot; /&gt;
&lt;ajaxToolkit:PasswordStrength ID=&quot;ps1&quot; runat=&quot;server&quot; 
	TargetControlID=&quot;Password&quot; RequiresUpperAndLowerCaseCharacters=&quot;true&quot; 
	MinimumNumericCharacters=&quot;1&quot; MinimumSymbolCharacters=&quot;1&quot; 
	PreferredPasswordLength=&quot;8&quot; DisplayPosition=&quot;RightSide&quot; 
	StrengthIndicatorType=&quot;Text&quot; /&gt;

Straight from the horses mouth so to speak.  But you run this and you get a nice little error jumping out at you.  This isn’t an ASP.NET one but a JavaScript error so it only appears when you visit the page with the control on it.


What?  What does this mean? 

0x800a138f – JavaScript runtime error: Unable to get property ‘UI’; of undefined or null reference.

Hitting break shows me this line of JavaScript; (I added comments to prevent any browser issues.


Strangely looking into the data finds that Sys is fine but it is the Extended that is undefined.  So why is this happening?  Don’t know, following the exact sample there causes an error.  My opinion, the example doesn’t work, period OR, it is not meant for the version of .NET I am using (which is 3.5 SP1).

BUT I fixed it.  HOW?  Simple, maybe.


&lt;asp:ScriptManager ID=&quot;asm&quot; runat=&quot;server&quot;/&gt;


&lt;asp:ToolkitScriptManager ID=&quot;asm&quot; runat=&quot;server&quot;/&gt;

I am unable to properly determine why but it seems the standard one that ships with asp, this is the plain ScriptManager doesn’t have all the elements required for the one that ships with the Toolkit.  Therefore the ToolkitScriptManager is required.  There is also a reference to the ToolkitScriptManager on their site but examples use the ASP.NET one. 

SO, to put it as simple as possible ANY of the Toolkit objects you may want to use, USE the ToolkitScriptManager, place this just under the form and it should work.  Other Ajax controls that ship with ASP.NET the normal ScriptManager will work fine.

So even if you see this error on other controls you have used check the ScriptManage component in your code.  It might be the wrong one.  Might I say, since I am unsure if one might work in specific examples, all I know is the PasswordStrength one, this fixed it.

The Conservative Nature of VB (Part 4) – Use Before Assignment


Number 4, in my series regarding the Visual Basic warning settings.  This one is an interesting one but comes from a long held problem from the days of old in Visual Basic.  Using a variable before anything has been assigned to it.  In languages like C# and C++ variables need to be assigned before they can be used, in C# if you have some simple code;

int myNumber;
if (myNumber == null)
	Console.WriteLine("My number is null.");

There will be an error reporting the use of an unassigned variable.  Why?  Often it is the way the items are created in memory.  The application will request an address for the Integer (4 bytes) to store the value that will be aliased by myNumber.  You get the address space and it contains what WAS at that address, it could be nothing it might not be.

I am aware that int types are not nullable.  But it is an example only.

But in VB, this is a different kettle of fish.  All intrincic types are assigned a value when it is created.  Take the following code;

Dim myNumber As Integer
If myNumber = 0 Then
	Console.WriteLine("My number is 0")
	Console.WriteLine("My number is " & myNumber.ToString())
End If

Fairly simple as far as a VB application is concerned.  But if you open the the assembly of the application, you will notice;

mov	dword ptr [ebp-40h],0

This says, move the value 0 into a double word (32bits) pointing to the ebp (display the registers to see the value of this)minus 40H.  So, without performing any initialisation at all, I was able to declare the value and the compiler was able to pre-initialise it for me.

So a note, if you were to enter the above VB code into your VB application, set the value of the warning to match this;


But you might noticed no warning comes about regarding numeric types these include integral and floating point numbers.  In VB it seems that the gods have decreed

In Visual Basic whence a number variable has been declared, thus forth it shall be initialised with 0, and it is good.

So understanding this means that you don’t need to initialise these numeric data types.  But SHOULD you?  It is good programming practice to intiialise all variables before use because you can come unstuck quickly when using types that aren’t initialised.

Dim myList As List(Of Integer)

If myList.Count > 0 Then
	Console.WriteLine("There are items")
End If

So the above code, looks OK, but I am getting a warning telling me the use of an uninitialised variable could result in an error.  And in this instance, it will.


Well one might say that is poor coding since I didn’t catch the exception, but this is another conundrum of development should I make sure I catch all errors, or prevent errors from happening, which will be the subject of my next post.

Errors happen, but this error could have been prevented with one simple keyword.

Dim myList As New List(Of Integer)()

If myList.Count = 0 Then
	Console.WriteLine("There are NO items")
End If

New.  The code executes as intended and the warning goes away.  This is a handy item to have turned on, simply because it will allow you to know where there is the possibility of errors creeping into your code if the initialisation of this is dependant on the user. 

NOTE Just a quick note this will also look at variables that are passed by reference that has not been assigned.  These variables might be used as return values from calling procedures due to the reference being passed, but it still might be used before that, and the reference is unknown at compile time and therefore checks like that can’t be done until run time.

Another note, yeah I know.  This is one that I might recommend as an Error setting. The other languages, like C# and C++ will not compile if there are uninitialised variables, therefore it might be good to have VB not compile if it finds these errors too.  Though the main difference is the numeric types in VB are initialised, C# and C++ they are not.

An Occasion to Share


This is such an occasion I felt i needed to share this.  I have finally, though banging my head on the desk questioning why someone did this in a particular way I have ridded myself of the crap warnings, errors and information presented to me.

I could have turned a blind eye to this and turned the warning off for things like assumed objects and use of obsolete methods, non-CLS compliance member names and the list could go on.  But through my eventual progress I have fixed them.  The code, is better than it was when I received it.

By no means is this perfect, I have never claimed to write perfect code,  My code can be at times not the cleanest in some regards but it is always well documented and it is efficient to the point without sacrificing readability.  There is much to do, I am converting each of the pages to be within the HTML5 standard, include all the XML documents with all components, more properly document the code (which means replacing the wonderful titbits I see like;

'ReportID is unnecessary and should be removed
    Public Sub BuildReport _
		ByRef dsReportDefinition As ReportDefinitionDataSet, _
		Optional ByVal ReportID As Integer = -1

This is what I deal with, someone has commented it, but ReportID is still there, though, this is not a used feature of the application but it is an example of these comments throughout the application.

So I will continue to plough through all of the remaining clean up items on my list, improve scalability, efficiency from an application performance and a user using it and provide and application I am proud of, which I am thus far considering what I have achieved in such a short space of time.


I should bask in this glory for the moment Smile.

The Conservative Nature of VB (Part 3) – Implicit Type


Number 3 in my series of posts about VB having these options that enable certain warnings from telling the programming something isn’t quite right with the code, or supress them.  These aren’t errors in preventing the application from working, but errors might happen depending on the state of variables or, it is just a hangover from the origins of Visual Basic.

I am looking into the Implicit Type warning.  This is really a hangover from the days of VB yore.  Previously VB, including ASP would not be as strongly typed as the languages of today, evening Visual Basic 6 you could still declare variables without providing a data type


Dim myVariant

Yes, just like that.  It would be created as a Variant which has a massive overhead in comparisons to other data types.  So, why can I still do this in VB now.  Well, the reason is unknown, possibly because of the conversion process.  Applications converted from VB 6 or before to the new .NET version of VB, they might have thousands even more variables that have been declared that way.  These no way to determine the physical data type so they were just created as Objects, which  were the base class type for all data types in .NET

Are their issues with using Objects over the others, yes.  The main issue is an Object in Visual Basic version 7 or greater are not compatible with Objects from Version 6 or less.  So, accessing interop COM objects you can’t pass object variables.

A performance hit as you incur a penalty for late binding.  Since if any method calls occur a look up to the object needs to be done to verify validity.

Widening is done to aide in the prevention of Overflow Exceptions, but there is an additional performance hit to box and unbox values types to the inherent reference Object type.

So, having this warning come up and say we have found variables you haven’t explicitly given a type we will make them all Objects, well you should go and fix them.  It isn’t always clear what it might be, but sometimes providing and incorrect variable will cause an error in telling you that it can’t convert from this type into the type you provided. 

Dim ReasonId = CInt(dlMain.SelectedValue)

This is a crude example but it is there for me to show how you can determine the data type needed if it isn’t straight forward, which I know the above example is.

I have updated with an unlikely data type;

Dim ReasonId As DataView = CInt(dlMain.SelectedValue)

Doing this has now caused an error in the code telling me it can’t convert one type to another.


So, this tells me that it can’t be converted to this and it tells you the type it needs to be.  Update the code and everything will be OK.

Dim ReasonId As Integer = CInt(dlMain.SelectedValue)

Most of the time it is easy to tell but if using LINQ and other more complex types or collections (including the generics collection) then it isn’t as cut and dry.

Should you turn this option on to show a Warning or an Error.  Well this depends on the project and also the programmer.  Me, I am one who wants to fix this, and I am currently working on a project that has a LOT of these in it.  Even for data types where they immediately initialise the variable.

Dim myVariable = True

This in my understanding is silly.  Does it take that much effort to include As Boolean into the code.  So, in my learned opinion all variables should be declared with a data types and should be turned on as an Error  and converting older applications, turn it on as a Warning, as you can slowly go through and fix all the issues.

CLS Compliance? Whaaa?

vb-179What does this mean?  Why do I see this within some of my applications?  How do I fix this or how do I stop the message from showing.  I will get a little technical in my explanation before I answer those questions.

CLS is a Common Language specification, a document that specifies how multiple programming languages need to work to create a common byte-code.  We have been using .NET for so long, gotten used to the fact that manage applications work, write components in VB and you can use them in C# or C++ or other language that uses the CLS.

So, you write an application in your favourite (managed) language and the compiler will convert that application into IL or MSIL as it is called.  This is the byte-code, it is a common language specification that is JITed (or Compiled Just In Time, JIT), like Java.   This code is then converted into platform specific code to execute the application.  The purpose of it, but the real reality of it has not been seen in too many places is, if there was a full .NET Framework for Linux and Mac these applications created on Windows could execute there.  The code is not platform specific, the MSIL is converted into the object code for execution on that platform.

So, where does this fit in with the CLS problem?  Simple, the code that is created by the compiler is CLS compliant.  Meaning you can use it in other languages that compile for the MSIL.  This means following some rules that might not be common to all languages.

IF and this is a BIG IF, IF you do not plan on writing ANY components outside of VB then, in the AssemblyInfo.vb  file you can removed the line of code;

&lt;Assembly: CLSCompliant(True)&gt; 

Or, set it to False.  This means the rules for this assembly are ignored and warnings about CLS compliance will not be seen.  This is an assembly level attribute, and care should be taken to turn it off.

Often in VB, when creating classes we use the following for property declaration;

Public Class MySuperClass
    Private _tempValue As Integer
    Public Property TempValue() As String
            Return _tempValue
        End Get
        Set(value As String)
            _tempValue = value
        End Set
    End Property

End Class

Simple class definition, the temp variable, prefixed with an _ (underscore) because VB is not case sensitive.  In case sensitive languages you can distinguish them as;

public class Class1
        private int tempValue;
        public int TempValue 
        {   get { return tempValue; } 
                tempValue=  value;   

Since tempValue is different to TempValue in case sensitive code.  Both of these are CLS compliant code, both can be accessed from other CLS languages if required.

But a change to either of these to show

protected int tempValue;


Protected _tempValue As Integer

and suddenly both classes are not CLS compliant cannot be called by each other.  C# does not allow prefixed underscores (_) for use with variables and VB is not case sensitive and therefore there is not difference between tempValue and TempValue.

There are the following rules you should follow when making code CLS Compliant, which are as follows.

NOTE:  A note on the rules MOST of these pertain to publically exposed interfaces.  These are the areas that other languages can access if they import your class for use in their code.  If it can’t be accessed outside your application then use any/all of these.  But if you break one of them on public interfaces then you code can’t be considered CLS compliant.

NOTE 2: The default behaviour of the compilers is not to check for CLS Compliance and will allow you to break any of these rules.  Also note.  Unless All Warnings as errors is selected, then the application will compile happily and everything will work, until you try and access it from another CLS compliant language.

  1. Unsigned types should not be included in publically exposed interfaces.  So, ULong, UInt and o on are not CLS Compliant, why?  Possibly due to there being platforms that might not support unsigned numbers in certain types.  I am unsure why really, but it is part of the rule set.
  2. Unsafe types like pointer are a big no, no with public interfaces.  Why VB doesn’t support pointers directly but there is a CLS compliant structure called IntPtr which is CLS Compliant.  So if you use *pointers in C++/C#  and need to use them in VB then you will need to convert them to IntPtr (UIntPtr is not CLS Compliant, see rule 1.)
    int myVar = 25;
    int foo;
    foo = *myVar
    If (foo == myVar)
    	myVar = 100;

    This code shows the problems and this becomes a problem in VB.  Foo is not assigned the value 25, it is assigned the memory address of myVar so when the check happens, they will not be equal.

  3. It should NOT be case sensitive.  Simply put, anything that could be accessed outside the language you are writing in, can’t differ by only case.
    Dim tempValue as Integer
    Dim TEMPValue as Integer

    These are the same variable in VB and would cause an error in the compiler, but;

    int tempValue;
    int TEMPValue;

    Both are different in C++ but this isn’t CLS compliant and there would be complaints with this in non-case senstive languages.  There is MANY an argument that can be had with developers over real languages v toy languages and case sensitivity.

  4. Operators cannot be overloaded.  If in your class you are overriding an Operator like = or >= then you can only create one method. 
  5. Overloaded methods can’t differ by simply out or ref.  These are C# keywords which mean the same thing.  In VB, ByRef is the one name.   So;
    public int TempOut(int name, out int myMember)
    	myMember = name;
       if (name &gt; 0)
       		return name;
       	return 0;
    public int TempOut(int name, ref int myMember)
       myMember = name;
    	return name;

    Might look different they are the same.  The difference is this breaks the compiler and and error will be given to you.  It is a rule for CLS Compliance but it is also a rule in C# and VB (though VB has only the one keyword to mean the same thing)

  6. Publically exposed members starting with an underscore (_).  We have seen this one above.  _ is used mainly in VB to provide a differentiating mechanism between private and public properties.  But in VB, an understand is still valid on public members.  But using them means your code is not CLS compliant and will not work with other languages.
  7. This one is a funny one, but, ONLY members that are CLSCompliant can be abstract.  Mmm, I don’t really understand this, but strangely you can create, by default a class without any mention of CLSCompliant and the assembly not stipulated as CLSCompliant will quiet happily take abstract members, but specify an Assembly to be CLSComplaint and a class and then specify that a Member is not CLSCompliant then it complains. 

There are other rules, dealing with arrays, constructors, enumerations and other things but the main languages, by that I say (C#, C++ (managed) and VB) support these rules by default, in most cases, there are exceptions as always but you can check out the full specification here, if you want more information.  I am happy to expand these at anytime if more information is required.

The Conservative Nature of VB (Part 2) – Late Binding


I am now going to go into the next part of looking configuration of the warning options for the compiler.  In the previous post I spoke about the warning configurations and specifically the one for implicit conversion.

Late binding has been a stable of Visual Basic since the early days and in ASP it was the only way one could create objects.  Now in the old days late binding provided an ability to create instances of objects using a text value.

What is Late Binding?  It is the nature of binding the object to the instance at the very last possible moment, before execution.  Early Binding, the compile knows about the object, its methods and members and it can resolve this, perform optimisation if needed.  But Late Binding, the compiler only sees text, it knows it can’t do anything with it until it is run and the process of calling the COM process invokes this and verifies if the component exists.

Even if the object specified is incorrect, you will not know about it until an instance is being created.  Then in the examples I am using, if you get the class wrong you will then see an “Cannot create ActiveX component.” error, which once again I am sure most VB programmers has seen in their life.

Dim myObject = CreateObject(&quot;Scripting.FileSystemObject&quot;)

This is the example I am talking about.  I am sure most VB programmers who have been programming in VB since before .NET would be familiar with this syntax.  But putting this code in doesn’t cause anything happen.

So, this configuration item enables the environment/compiler to report on occurrences of late binding and report them to you.  But there is one instance it can’t report to you which I will get to.

Take the following code;

Dim myObject As Object = CreateObject(&quot;Scripting.FileSystemObject&quot;)

For Each tempName As Object In myObject.Drives

Fairly simple code, if you have used the file system object before you would recognise this. 


That code, with late binding Warnings on, will display the following warnings.  Note, there is also an implicit conversion happening but I have turned off these being reported.


The message displays as such.  Late bound resolution, runtime errors could occur.  Thankfully in this instance they don’t happen and if in a console application it will simply write the driver letters to the console window.   But what about;

Dim myObject As Object = CreateObject(&quot;Scripting.FileSystemObject&quot;)

For Each tempName As Object In myObject.Drives

Doesn’t look out of place, getting the drives putting the name to the console.  But Name isn’t a valid member of the Drive object.  So, the compiler tells me there is a problem with the resolution and an error could occur.  Run it and ;

Unhandled Exception: System.MissingMemberException: Public member ‘Name’ on type ‘Drive’ not found.

Yes, not a lot we can do other than fix it.  So, should I have it as an error or a warning.  Well for one, I would say you could turn it off as in my opinion we shouldn’t be late binding.  There is only a small number of instances where late binding is acceptable, scripting when objects have no type and for application add-ins where they are written for applications and are loaded using a binding reference stored as text.  But even in the latter scenario there are other ways to do this as well.

So my recommendation is, get out of any habit you have of late binding and import your objects, add references to COM components using interop.  There should be no late binding references in there.  If unsure, switch all other warning options to None except Late Binding and see what comes up. 

NOTE: The IDE has some wonderful features, one of which is IntelliSense.  Late binding removes this feature create a new Console application and put in the code from listing 2 (I have realised I do not name my listings, mmm, maybe I should.).  If you remove DriveLetter and the period and put a . down, you will see one thing, a drop down that contains the available members for Object.

Imports Scripting

Module Module1

    Sub Main()

        Dim myObject As New FileSystemObject()

        For Each tempName As Drive In myObject.Drives

    End Sub

End Module

Now, using the same project add a reference to the COM component Microsoft Scripting Runtime.  Include the import statement and using the code above, and you will see the drop down menu from tempName shows a great many more things.


The dropdown on the left is the Drive drop down members, the one on the right is the Object.  Not only that, you get the nice help as well.


So, this helps as you know it returns a string and is ReadOnly.  Handy.  I know which one I would prefer.