Friday, 30 March 2012

500 Mile Challenge

At the start of the year I was looking to give myself a small running challenge to motivate myself into increasing my running both in number of runs and length of run. After chatting to some friends I decided to go for 365 miles in a year which was achievable but also allowed for some time off due to holidays and any possible injuries.

I decided to mention it to the guys I regularly go running with (both better runners than myself) and they decided it was a good idea but 365 was a bit too easy. The 365 mile challenge was replaced with the 400 mile challenge. We decided to log this on Endomondo so we could track each others progress but found that someone had already posted a 500 mile challenge. This led to the 365 mile challenge becoming the 500 mile challenge.

It worked out at roughly 9 miles a week which is a mile more than what I usually do after completing two 4 mile runs at lunchtimes. It was good motivation so we upped our normal run to 5 miles so that we would be completing 10 miles a week on average. So far I am just about on track but I had to clock ~70 miles this month to make up for the short fall I had in January due to the birth of my son.

I also bought some new trainers for some extra motivation and finally ditched my 10 year old asics that had about 1000 miles on the clock. I went for the asics fuji es trail shoes as most of the running I do is on tracks in the forest. The shoes are really comfortable and have the usual asics excellent fit and are a lot lighter than my old shoes. 

For trail shoes they are great with good grip but the only gripe I have is that they should really be a lot more waterproof to be true trail shoes. 

T-SQL Replace String

On a recent project I was tasked with writing a simple string replace function for T-SQL.  On the surface it seemed a fairly straightforward task using either PatIndex or charindex.  However, some of the specific requirements proved problematic.  There could be multiple replaces of the same text throughout the string, the replacement text may be the same as the text to find and the word may contain numbers and underscores. 

Using patindex in a loop seemed the best way forward to deal with the multiple replacements and the numbers and underscore characters.  The other problem was that I had to step through the original text to do the replacements so that if a text was replaced with the same text then the function wouldn't get stuck.  I achieved this by using sub string to get the remaining text after each replacement.


@OrigString varchar(8000), 
@LookFor varchar(1000), 
@ReplaceWith varchar(1000))

returns varchar(8000)
BEGIN
DECLARE @findIndex int
DECLARE @lengthLookFor int
DECLARE @lengthReplace int
DECLARE @totalLength int
DECLARE @tempString as varchar(8000)
DECLARE @counter int

SET @OrigString = '(' + @OrigString + ')'

SET @lengthLookFor = LEN(@LookFor)
SET @lengthReplace = LEN(@ReplaceWith)
SET @totalLength = LEN(@OrigString)
SET @tempString = @OrigString
SET @counter = 0

DECLARE @stuffindex int
SET @stuffindex = 0

DECLARE @substring int
SET @substring = 0

WHILE PATINDEX('%' + @LookFor +'[^a-z0-9]%', @tempString) != 0
BEGIN
 SET @findIndex = PATINDEX('%[^a-z0-9]' + @LookFor +'[^a-z0-9]%', @tempString) + 1
--SELECT @findIndex as 'findIndex'

 set @stuffindex =  @findIndex + @substring 
 if(@counter >0)
  set @stuffindex = @stuffindex - 1

 --SELECT @stuffindex as stuffindex

 SET @OrigString = STUFF(@OrigString, @stuffindex , @lengthLookFor, @ReplaceWith)
--SELECT @OrigString as 'outputstring'

SET @substring = @stuffindex + @lengthReplace
--SELECT @substring as substring

SET @tempString = SUBSTRING(@OrigString,@substring,@totalLength - @findIndex)
--SELECT @tempString as 'tempstring'

SET @counter = @counter + 1


END

SET @OrigString = SUBSTRING( @OrigString, 2, LEN(@OrigString)- 2)

Thursday, 23 February 2012

Creating ASP.NET tables in SQL server

To create all of the user and membership tables in SQL Server 2010 there is a command line tool within the tools directory (use the link to the command prompt) that can be used.  The command to get the tool to create the tables is:

ASPNET_RegSQL.exe -S (Server) -d (Database) -A m -E

-A m creates the membership tables and -E uses a trusted connection.

The command creates the Applications, Membership, SchemaVersions and Users tables for ASP.NET.

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.

Saturday, 15 October 2011

RDLC and Sub Reports

This week I have been looking at sub reports within RDLC and specifically dynamic reports where the dimensions of a table within the report are not known until runtime.  I managed to solve the dynamic table problem from an article posted here and adjusted the example to show the formatting required.  However, the report needed header and footer information so this looked to be quite troublesome editing the dynamic code. I also wanted the same header and footer information on a number of dynamic reports. Thats when I came across sub reports.

I created a basic RDLC with the required parameters to support the header and footer info and added a sub report. In the code I then populate a dataset with all the data required from my WCF middle tier and use the dynamic table functions to generate the report definition stream. This stream is then fed into the sub report and the report is shown in report viewer.  The only tricky part was sending the dataset into the sub report and I found the solution on the MSDN forums. I'll post up some code next week

Running is going ok at the moment and I'm five miles short of two hundred miles for the year. However, had a a pretty bad fall on Thursday and injured my hand quite badly.  Healing ok now but I had to pull half a branch out of my wrist which wasn't nice. Should crack the two hundred mile mark this weekend with some friends.

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.