Form Showing As Class In Visual Studio 2010 Solution Explorer

Posted on Updated on

Sometimes while working on WinForms applications a very strange thing happens, when I add a new form to the project it shows up as a C# class. This is very annoying because I can not readily get to the design view for that form. Luckily there is a simple fix.

1. Unload the project.
2. Search for the specific form in the xml file.
3. Replace xml with following.

<Compile Include="[formname].cs">

4. Save and reload the project.

Particle Swarm Optimization (PSO)

Posted on Updated on

Nature is a great teacher as it relates to optimization and evolutionary computing. Among the many lessons taught by nature is the concept of the swarm; whether its a swarm of Locusts, school of Piranhas or a flock of birds the group and group conciousness serves a very important and dominating purpose. In case of the Locusts and Piranhas that purpose is embodied in their very optimized feeding technique which has evolved over millennia into the efficiency that we see today. Particle Swarm Optimization (PSO)  is just one of the many and varied optimization techniques borrowed from nature.  Many see Particle Swarm Optimization as a hybrid Genetic Algorithm(GA) implementation which allows a more deterministic search of the problems solution space.

Particle Swarm Optimization takes advantage of a mathematical formula that tells each candidate solution(CS) how far it is from optimal and what it needs to do to be to closer to the swarms optimal position. Depending on the calculated position of the CS and the speed of convergence the CS is guided to a new optimal position for each epoch.

We  can visualize this this by looking at a school of Mackerel trying to escape the jaws of a hungry great white shark. Each Mackerel is aware of its own position in the  school, the position of the shark and also the position and wellness of its neighbour. This swarm feature allows the  school to function as a single cohesive organism. It is quite obvious to the fish that  if their neighbour turns left and is still not eaten then it is a pretty safe bet that when it turns left it too may be swimming off into the sunset and not into the hungry jaws of the shark.

The PSO optimization is a much simplified expression of the previous narrative,  if you are already familiar with the workings of a Genetic algorithm you should be quite at home with this incarnation. A GA with some simple modifications can be converted into a PSO; by by modifying its operators so that each CS is aware of its immediate neighbours and their fitness. Another advantage with PSO’s is the reduced number of parameters which must be configured in order for the technique to work. Many different solutions can be solved without much modification to the algorithm.

Setting Up Visual Studio 10 for MASM32 Programming

Posted on Updated on

If you are like me and want the comfort and support that Microsoft’s Visual Studio 10 provides, then you will defiantly want that support in your MASM programming tasks. Visual studio makes this quite easy, with a couple of project property changes you will be on your way to MASM programming bliss.


  1. Create new Visual C++ Empty Project
  2. Right click on the newly created project and select Build Customizations; select masm option, press ok then save the project.
  3. Go to project properties and select linker->system then change subsystem to Windows (/SUBSYSTEM:CONSOLE)
  4. Download and install masm32 libraries then add them to your linker settings.
  5. Go to linker->Advanced and change Entry Point to main [this is what the linker will look for when mapping the entry point for your app.]
  6. Go to Linker->Input  and add masm32.lib to Additional Dependencies.
  7. Go to Microsoft Macro Assembler->General and add the masm32 libraries.
  8. Download and paste usertype.dat into C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE
  9. Go to Visual Studio Options->Text Editor->File Extensions: Type asm in the extension box then select Microsoft Visual  C++ from the list.
  10. Right click on project and select Add->New Item: Select Text File and save with *.asm
  11. Create, run and enjoy your code 🙂

In a future post I will show how to turn this project into a Visual Studio project template.

Reverse Polish Expression Parser in C#

Posted on Updated on

There comes a time in every programmers life when she needs a parser. More so if that programmer works for an accounting company. Its not enough to just do the obvious and use the Java Script expression evaluator, or some other third party library for that matter. After all you can do it yourself, with all the custom trimmings that you require for your current project. The key concept in any mathematical parser is the way it interprets the tokens given to it. In this post I will be using reverse polish notation to represent the expression; which will be evaluated and the answer returned. The code is pretty self explanatory so I will not go into details about how it works, remember this is just my first attempt at this so any recommendations or suggestions will be welcomed. I have also intentionally left out some features in the hopes that this will spur suggestions and recommendations.


public struct Token{
        public int _class;
        public string repr;


private bool RPN(string expression){
            Regex reg = new Regex(@"\[\b[A-Za-z]+\b(?![\d])\]|[\+\-/\*]|[\d]+(\.[\d]+)?|[()]");
            Stack op_stack = new Stack();

            foreach(Match token in reg.Matches(expression)){
                Token tok = new Token();
                string value = token.Captures[0].Value;

                    tok._class = (int)type.num;
                    tok.repr = value;

                }else if(IsOperator(value)){
                    while(op_stack.Count != 0 && op_stack.Peek().repr != "("){
                        if (HasPrecidenceOrEqual(op_stack.Peek().repr, value)){
                        else break;
                    tok._class = (int)type.op;
                    tok.repr = value;

                }else if (IsVariable(value)){
                    tok._class = (int)type.var;
                    tok.repr = value;

                }else if(value == "("){
                    tok._class = (int)type.var;
                    tok.repr = value;

                }else if(value == ")"){
                   while(op_stack.Count != 0 && op_stack.Peek().repr != "("){
                   if (op_stack.Count != 0) op_stack.Pop();
            while(op_stack.Count != 0){

            return true;

Full source code listing at github

Get A DLL’s Configuration Settings From The Calling Applications App.Config File.

Posted on Updated on

I had this problem recently, how do i read a dll’s configuration from the calling applications app.config file? It turns out to be quite easy, Just copy the .dll section from its app.config.

<section name="somedll.Properties.Settings"  type="System.Configuration.ClientSettingsSection, System, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowexedefinition="MachineToLocalUser" requirepermission="false"></section>

Then paste it into the the calling applications app config.

        <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089">
            <section name="someApp.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false"/>
            <section name="somedll.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
        <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
            <section name="someApp.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />

Then copy the setting from the dll’s such as its connection string and paste it into the


section.Then your are done, now when your run the application the loaded dll will read its configuration from the calling applications app.config file.

Using A Perceptron ANN With Genetic Algorithm Trainer To Solve Logical AND

Posted on Updated on

Neural nets (NN)  have always been a “black box” fascination for me until recently when i had my eureka moment. Neural Networks are mainly used for classification and prediction applications include stock market trends, feature recognition and some types of optimization techniques. A NN can be trained in two ways, supervised and unsupervised.

The NN is exposed to a dataset with the training values and the correct outputs to those values. A Training algorithm such as back propagation is used to minimize the error between resulting outputs and the correct outputs.

The NN is allowed to form its own conclusion based on the dataset provided. These types of networks are usually used for classification type problems, a very good example of this it the SOM (Self Organizing Map) network.

That said, if you have not already read my post on Genetic Algorithms (GA) please do so now, since we will be using GA’s as the means of optimizing the required weights for each input of the Perceptron.

Wow you are back already? Ok lets look at a simple NN to see how it works, the NN we will be reviewing is called the Perceptron this particular configuration has only two input neurons since we will be dealing with a binary operation and one output neuron.

Simple Perceptron

i = inputs
w = weights
o = output
b = bias

A bias is also associated with the network, this bias is simply a neuron with a constant multiplied by a weight, this bias is added to the activation function in order for the NN to recognize problems that are not linearly separable. Each input is multiplied by a corresponding weight, the weight is a small value which will be adjusted until the the output neuron is activated. Activation occurs when the activation function Σ(i1*w1+i2*w2)+b is greater than certain threshold. The output of the activation function is then sent to a transfer function which interprets that output as 1 or 0 depending on the inputs supplied to the NN.


Simple Genetic Algorithm To Evolve A String of Integers

Posted on Updated on

Genetic Algorithms are a means of optimization copied from the natural world. According to the theories of evolution, nature has a way of selecting the best (fittest) individuals to mate (Crossover) and reproduce; thus carrying on the best features of each selected individual. Even though traits from both parents are carried over into children there is still an element of randomness involved (Mutation) that gives their offspring the ability to explore their fitness landscape (adapt) to their environment. Genetic Algorithms tries to mimic this behavior with three common operators (1)Selection, (2)Crossover, (3)Mutation.

The selection operator determines how the individuals of a population are selected to mate, the most popular selection method is called elitism and this is the method that we will use in our genetic algorithm implementation.

The crossover operator determines how the parents are recombined to form offspring. We will be using single point crossover in this implementation.

Mutation inserts randomness into the genotype of each offspring giving it the ability to diversify from the features of its parents.

Implementing genetic algorithms can be seen as somewhat of an art because almost all of the code is boiler plate except for the chromosome representation used and how the fitness of each individual is calculated. These two factors usually have the most impact on the accuracy and speed of the genetic algorithm and are the most difficult to represent. These factors along with the mutation rate, crossover rate and selection method have to be tinkered with until a viable configuration is reached.

This implementation will evolve the number sequence 123456789 in that specific order.

Interesting Functions

private static void CalculateFitness(sequence seq)
var ordered = new sequence{buffer = new List<string>() {"1", "2", "3", "4", "5", "6", "7", "8", "9"}};

int result=0;
for (int i = 0; i < 9; i++)
if (ordered.buffer[i] == seq.buffer[i]) result++;
} = result;


private void Epoch(List<sequence> population)
            survivors.AddRange(population.Where(i => >= survivorThreshold));

            Mutate(population.Where(i => >= mutantThreshold));

            CrossOver(population.Where(i => >= crossoverThreshold) as IEnumerable);


            for (int i = 0; i < populationSize - survivors.Count; i++)
                var temp = GenerateSequence();

The full code listing can be found at github