Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Thursday, 27 February 2014

Winforms UI and the Double Buffered Panel

Session 2

The main task of this session was to link the new tile loader package to the WinForms user interface and display the new OS Terrain 50 data and existing Perlin noise terrain on the UI.  The first task was to remove the duplicated classes that were now in the tile loader package and to upgrade the UI so it can be used to display more than tile.  It also needs a bit of tidying up as it was developed fairly rapidly as a test bed for the A* algorithm.

The existing UI
Once the tile loading classes had been removed I reorganised the code behind to operate using the asynchronous tile loading package.  The main thing about user interfaces is that the main UI thread cannot be locked so the asynchronous calls to load tiles are crucial.

The other hurdle I faced was that the existing UI uses a basic panel to display the tile on.  When the UI scrolls the panel flickers so I had to create a new user control that is double buffered but inherits from the main .NET panel object.  This user control is then created dynamically on the UI loading so that it is tiled on the main pane. 

The second session overran slightly as I had underestimated how long it would take to change the UI over to using asynchronous calls. However, by the end of it I had the first sight of the terrain 50 data in the UI.  I had chosen the SU area tiles to begin the testing for two reasons, 1 it has a clear coast line which will help test the orientation is correct and 2 I am familiar with the area.

After session 2, the application only loads a single tile using the menu buttons so tomorrow I will be looking to load multiple tiles and change the UI slightly to load the data by double clicking the desired tile on the UI.  The background threads worked well and the performance is pretty good.  I will also be looking to improve the colour algorithm to give it more detail as the new data has a better fidelity which is not shown using the existing algorithm.
OS Terrain 50 in application


Tuesday, 25 February 2014

OS OpenData

I recently came across the Ordnance Surveys OpenData products and decided to look into how I could use some of the data in some of my existing projects.  In particular I have a personal project that I have been developing that uses an A* path finding algorithm with a heuristic that avoids steep inclines and declines, picking the most efficient route through a 3D terrain.

At the current time I have been using a Perlin noise algorithm to randomly generate terrain.  The weakness of this algorithm for generating the terrain is that, without some particular exceptions, it cannot produce certain terrain effects such as cliffs, inlets and sharp changes in terrain.  There are some techniques that can be employed to produce these effects after the Perlin noise has run but again they take some time to get a realistic looking terrain.  Using real terrain would be a great test for the algorithm.


Perlin noise generated terrain
A*algorithm avoiding the water and raised terrain
The OpenData products come in a number of formats and are continually updated to give information from postcodes and boundaries to digital maps.  The product that caught my eye was the OS Terrain 50 which gives height data at 1:50 scale across the whole of the UK. 

OS Terrain 50 is available as:
  • 50 metre grid in ASCII grid and GML 3.2.1
  • 10 metre contours in Esri® shapefile or GML 3.2.1
ASCII grid is a simple file format that specifies height data by storing tile information in a header block then a table of data in the body containing the payload. Geography Markup Language (GML) is an XML grammar to express geographical features. Esri shapefile is a geospatial vector data format for specifying shapes as points, lines and polygons that can be used to represent rivers, water wells and lakes.

My goal is to use one (or possibly all) of these file formats to produce some real terrain data to test my A* algorithm.  To do this I will use my existing test bed application written using WinForms and C# and modify it to read in the OS Terrain 50 data.  The existing test bed is a very simple application that produces a terrain object which is rendered in 2D and is colour coded to show different heights in different colours.  The terrain object is then used by the A* algorithm to calculate the most efficient route through the terrain.

The main tasks are:
  • A GML/ASCII/Shapefile reader will be developed.  There are a number of readers available but I am planning to write my own so that I can learn more about the file format.
  • The application will be redesigned so that a new layer is added that can feed the main application with either a terrain object that was produced by the Perlin noise algorithm or a terrain object built from the OS terrain 50.  In this way the A* algorithm will not be affected by the type of terrain data loaded.
  • The main user interface will be changed to display multiple tiles;
  • The application will be changed to use threads to load the tiles in the background.
  • The colour code will be updated to produce a better quality display.

I am planning to tackle these tasks in hour long sessions over a period of a week and see where I am after the week has finished.  The main risk to completion are finding the time in a week for an hour of coding and half an hour of blogging. 

Friday, 18 November 2011

Conditional Formatting Using RDLC

I recently came across a problem on a report we needed to run that returned either a date or some text. The return value of the data then needed to be colour coded in a traffic light style so that dates in the past were red, dates in the future were Green and dates within the next month were orange. Additionally if the value was set to N/A then the field was to be turned gray.

Looking at the problem it seemed straight forward and I headed straight to the expression field of the color parameter for the column. I entered a switch statement that cast the value to the appropriate type (Date or string) and then attempted to do the logic. This turned into a large dead end as the casting of one type then seemed to not allow any further casts! After a few searches I couldn't find the answer so posted on the MSDN forums. After about 6 months of no answer I had pulled the last of my hair out and had put in a compromised solution.

The problem still nagged at me until I came across using code and shared assemblies in RDLC. To solve the problem I simply put a function into the code block and set the color parameter of the field to the expression. At last, a fix (although really its a workaround as it should have worked in the expression). Here is the function I put in:

 Public Function ColorFormat(ByVal cellValue As Object) As String
  
     Dim cellDate As Date
     Dim cellString As String
  
     cellString = CStr(cellValue)
  
     If Date.TryParse(cellString, cellDate) Then
       If (cellDate < Date.Now.AddMonths(1)) Then
         If (cellDate < Date.Now) Then
           Return "Red"
         Else
           Return "Orange"
         End If
       End If
     Else
       If String.Compare(cellString, "EXPIRED", True) = 0 Then
         Return "Red"
       End If
     End If
  
     Return "Black"
  
   End Function  

The functions in the code block need to be in VB and debugging whilst running is impossible so putting into a shared assembly is the preferred option.

Thursday, 10 November 2011

Porting C++ to C#

Over the years I have built up a large portfolio of code in various languages.  A number of the projects I have reused a number of times and ported from one language to another.  Most of the projects are small scale two or three class applications or library's to perform small scale things like path finding libraries or file readers/parsers.  I recently got involved in a project where there was a potential that an old project may help solve some particular aspects of the application.  It turned out that the new project took a different direction but I had a quick look through the old C++ project and looked at building a quick test harness in C#. 

I looked at a number of options to call the old library from C# but the two options I came across ( wrap the C++ class in a COM object or expose the class through DLL exports) would probably take just as long to set up as to port the code.  The original project is around 20 years old and was originally written in C.  It was ported to C++ in 2000 and was highly optimised using pointers and threading.  There was no documentation on the project and although I had used it in a black box way for around 2 years I had never fully understood the internals.  Therefore, porting the project would also give me the opportunity to delve into the internals and check out exactly what it was doing.

The C++ project had about 8-10 classes and a few structures that needed to be converted.  In the past when I have ported projects I have gone for the big bang approach of copying the files into a new project and then tackling each class at a time.  The problem with the approach is that you soon become bogged down in errors and often you lose sight of the overall structure of the code.  There is basically no going back with this approach as it will not compile until everything has been tackled. With this in mind I went for a more evolutionary approach.  For this latest conversion I reverse engineered the C++ code into Enterprise Architect which gave me a good understanding of the structure and also enabled me to generate a skeleton C# project. 

Once I had the skeleton in place I tackled each class in turn starting with outer objects in the structure.  This enabled me to always have code that compiled after each class had been converted and I could also document each class at a time. 

The main problems I found when porting were relatively simple fixes.  The most difficult decisions came when working out whether pointers were pointing to objects, arrays or just simple types.  The existing code also use the STL in a number of areas for lists and maps so this was fairly simple to convert using the collections in C#.  The only other problems I had were operator overloading and tackling the threading.

The threading was very simple in that the system spawned a number of threads which ran a single function and then joined the threads after completion.  The thread function contained a critical section to thread safe a global object.  Using the System.threading library and the lock function gave me the threading and critical section so all that was left was the join.  The threads were in an array so I used the following technique:

TimeSpan timeout = new TimeSpan(200*numThreads)

foreach(Thread thread in threads)
{
    DateTime start = DateTime.Now

    if(!thred.Join(timeout))
    {
        throw new TimeoutException();
    }

    timeout -= (DateTime.Now - start);
}

The operator overloading was simple enough once that I found out that the operator needed to be static.

Overall the port went quite well and I was able to port the code fairly quickly.  Using EA to generate the skeleton saved a lot of time and by attacking it in a piecemeal approach was not only simpler to manage it was much better for morale as the problem never got too big.

Thursday, 23 June 2011

Upping the running

Been busy trying to increase the amount of running I've been doing and have moved to four days a week with two days playing football.  Feel tired at night after the third run but I am experiencing massive upsurges in motivation.  Lots of energy to focus on small projects I have been putting off for ages and tackling a mountain of paperwork.

Been using the endomondo app for my HTC wildfire S to track my runs and although the endomondo system is excellent the phone seems to lose my running track around half way around the route which is frustrating.

Reading has been put off for now and have some overdue library books to take back (another small job). All the reading means I have been going to bed exhausted so as soon as my head hits the pillow I'm asleep.  I also guess that A passage to India hasn't gripped me yet.

Been working on some more WCF applications at work and learning all about SQL server, stored procedures and all kinds of WinForms technology.  Really impressed so far and things are fairly quick to develop. Its my first venture into managed code after years of C++.  Working on some interesting designs for a generic rules engine.  Going OK at the moment and the design seems scalable but will be soon adding some complex rules to test the design is robust.