Friday, September 26, 2008
Silverlight 2 Release Candidate Now Available
Monday, September 22, 2008
Manipulating bitmap images with pointers uh oh
There are two ways to do this. You can either use the bitmaps SetPixel and GetPixel methods or pointers. Pointers have better performance. I will be using this in Silverlight over a webservice which will be slow anyway so I am going to go with pointers.
- Its not the most straight forward thing but here is the basic concepts
- Your image is essentially a byte array
- In a (RGB) image 3 values from 0-255 make up the image (you could also have a 4th for gamma I think)
- Depending on the strenth of these values it makes a color e.g. 255 0 0 would be red
- For some reason when you read these values they come out back to front e.g. BGR 0 0 255 for Red (?)
- As .net is managed code and we are using pointers we need to mark it as unsafe and click the allow unsafe code
- To manipulate these values you load up the image, Fix its place in memory then get a pointer to the start of it (scan0)
- Each line of the image from the top is the width of the image * 3 (in 24 bit image)
- This number must be divisible by 4 otherwise it will have a padding bit
Belows the code I used to convert an imagr to greyscale. I have commented out brightness adjustment (just add to each value) and some other stuff I was playing with.
using System.Drawing.Imaging;
int intStride = 0;
int intBrightness = -150;
System.IntPtr Scan0;
Bitmap objBitmap = new Bitmap(@"C:\\testPhoto.jpg");
BitmapData objBitmapData = objBitmap.LockBits(new Rectangle(0, 0, objBitmap.Width, objBitmap.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
//For 24 bit formats (RGB) stride=imageWidth * 3 (note if this isnt a number divisible by 4 an offset will be added to make it so)
//For 32 bit formats (RGB) stride=imageWidth * 4
intStride = objBitmapData.Stride;
Scan0 = objBitmapData.Scan0;
unsafe
{
//Pointer to start of image
byte* p = (byte*)Scan0;
//Calculate offset
int nOffset = intStride - (objBitmap.Width * 3);
int nWidth = (objBitmap.Width * 3);
int intRed = 0;
int intGreen = 0;
int intBlue = 0;
for (int y = 0; y < x =" 0;" intred =" p[2];" intgreen =" p[1];" intblue =" p[0];"> 255) intRed = 255;
if (intGreen > 255) intGreen = 255;
if (intBlue > 255) intBlue = 255;
if (intRed < intred =" 0;" intgreen =" 0;" intblue =" 0;">
http://www.bobpowell.net/lockingbits.htm
http://www2.sys-con.com/ITSG/virtualcd/Dotnet/archives/0104/brown/index.html
http://www.codeproject.com/KB/GDI-plus/csharpgraphicfilters11.aspx
Thursday, September 18, 2008
Remix 08 Day 2
We started of day to of Remix with a talk on MVC. I havent had a chance to play with MVC yet so was quite interested in this talk. MVC stands for Model View Controller and is ASP.net's implementation of an architecture designed in the 1970s. But dont let that put you off!
In relation to standard ASP.net
- Model is your data
- View is your aspx and ascx controls
- Controller is your business objects, managers etc
The main advantage of using MVC are that:
- As each unit is independent they are easy to change
- Seperation suited to unit tests
- Better search engine optimization due to url parsing
The main conclusions were:
- Dont make unnecessary http requests e.g. consider combining js and css files
- Place js and css files at bottom of home page so they are preloaded and due to page position dont interrupt user experience
- Careful with use of update panel as it posts back whole page, use [webmethod] attribute instead
- Implement http compression
- Implement compression in asp.net side
- Silverlight can be used to preload stuff and appears quicker than javascript
- Use caching - duh!
This was very impressive:
- Silvelight can refer to, add, modify & hook up to events on the external html page
- The html page can talk to silverlight
- Call web services
- Listen on sockets
Remix 08 Day 1
I drove down to Brighton the night before Remix in order to avoid the traffic and be awake for the sessions. I spent Wed evening in a very strange hotel talking to some very drunk people in the hotel bar .
My weird Dr Who esque bed:

After meeting up with Howard just outside the exhibition hall the day began with an excellent key note speech given by Bill Buxton ( usability and industrial design expert) Bill has written an interesting looking book called Sketching user experiences which I purchased.
Bill argued that in many places the design phase occurs after the product development and that it was a mistake to let non experts be too involved in design (e.g. the FD on a project being involved to the level of screen design). He argued that good design was dependent on many aspects citing Apples Ipod. Prior to this Apple had been in decline. At this time a number of key personnel Jonathan Ive had been at Apple some time but the Ipod wouldnt become a success until a combination of events such as:
- Jobs empowering the designers
- Lawyers negotiated with record labels $99 per track
- Ives and his team creating the design
After this we attnded 2 sessions by Scott Gu on Silverlight. I have spent some time with Silverlight lately and would highly recommend the video tutorials. Scott said that Silverlight 2 was due to be released shortly (somewhat non committal!). Other items that looked interesting were IE 8 which includes a javascript profiler and useful looking development tools, Visual studio intellisense support for javascript frameworks such as prototype, about 50 new silverlight controls including graphing components coming.
We then saw a session on Sql data services (astoria). Astoria is basically a REST api to query sql server. I am not sure what I would use this for but it may be useful for example in a silverlight situation to avoid writing a web service interface for every crud query.The final session was on Visual Studio IDE tips given by Sara Ford. This was very interesting and contained several time saving tips. I suggest you look at her blog which has a tip a day http://blogs.msdn.com/saraford/default.aspx
After we left this session I managed to talk to Scott Gu. One of the great things about Remix was how accessible all the presenters were. To have the chance to talk to Microsoft's VP was pretty cool.

I asked Scott about whether we should be using Web sites or Web application projects (a contentious issue in our company). Scott suggested web application projects where the dll is built is the better way to go. This was due to better performance and the ability to produce unit tests as a dll is built.
After the main sessions I had a few beers with Howard and had a chance to look at Microsoft Surface. There was an excellent demonstration given which had a virtual earth map. You could rotate it at any angle and even zoom into and walk inside buildings. At $13000 per unit they dont come cheap through.
I am looking forward to the MVC session tomorrow (finding out what exactly it is!)
Thursday, September 11, 2008
To thread or not to thread..
Threading is an immensely complex subject and one that is poorly understood by most developers (im certainly not claiming any expertiese). I suspect some implement threading just because they think its cool.
Threading can increase the performance of your application greatly especially with long running processes and may be very necessary depending on your requirements. However I would say its best avoided if possible.
Never under estimate the additional complexity that adding threading will add to your application in terms of development, debugging and testing.
Recently I have experienced a number of issues with programs (written by other people grrr) that have implemented threading.
The mistakes I have seen over the last few weeks include:
- Failure to lock resources accessed over multiple threads. This ends up with unexpected behaviour when 2 threads are altering the same variable. Various methods to solve inc sync lock, refactoring code, using patterns etc
- Not killing threads properly - Use finally statment etc. Never assume the thread will be killed
- Some interesting ways to manage multiple threads - make use of thread pool!
- Deadlocks - not one thats come up yet but something to be aware of
So always practice safe threading or refrain..
Wednesday, September 10, 2008
NUnit & WatiN basics
To let NUnit know what tests you want to run you need to annotate the methods with special attributes that are picked up by the NUnit test runner which then runs the tests individually.
But why would you want to use NUnit?
Yes there is a bit of upfront work but if you are going to test anyway (and you should) why not make the test repeatable in the future?
Once a test is written you can run it as many times as you like!
The test will be run the exact same way and wont make mistakes unlike people!
Let tests run overnight to pick up errors or integrate with your build process perhaps with CruiseControl.net
Tests can help pick up integration problems e.g. changes to libraries etc
So how do you use it?
Download and install NUnit from:
http://sourceforge.net/project/downloading.php?groupname=nunit&filename=NUnit-2.4.8-net-2.0.zip&use_mirror=kent
Create a new class project
In your project add a reference to Nunit.framework.dll
Add the following imports statements in your code:
Imports NUnit.Framework
Create a class with two methods:
Public Class Ben
Public Sub AddTwoNumbers()
Assert.AreEqual(1 + 1, 2)
End Sub
Public Sub MakeTea()
Throw new system.exception("Ben doesnt make tea")
End Sub
End Class
Add the test fixture attribute to the class and Test attribute to your methods.
<TestFixture()> _
Public Class Ben
< test()> _
Public Sub AddTwoNumbers()
Assert.AreEqual(1 + 1, 2)
End Sub
<test()> _
Public Sub MakeTea()
Throw new System.Exception(“Ben doesn’t make tea”)
End Sub
End Class
Compile your application
Open up Nunit
Click File Open Project, select the dll output of your project
Your screen should now look like below:
Notice how NUnit has divided up the tests by class and method.
Click AddTwoNumbers and then click the run button it should pass 1+1=2!
Click MakeTea
The test will fail (Ben doesn’t like to make tea!)
If you want to run both tests at once you can click Ben and then Run.
Congratulations you have now run your first NUnit test!
For further information about NUnit please refer to:
http://www.nunit.org/index.php?p=download
WatiN
Nunit on its own is great for running small class based tests but as most of our applications are web based we want to use a program called Watin as well. Watin is a helper class for using Internet Explorer and allows you to automate most internet explorer actions
First of all download Watin from:
http://watin.sourceforge.net/
Download Watin Test recorder from:
http://downloads.sourceforge.net/watintestrecord/TestRecorder101b.msi?modtime=1190992400&big_mirror=0
Install Watin Test Recorder
In your project add a reference to Watin.core.dll
In your project add a reference to Interop.SHDocVw.dll
Add a new imports statement at the top of your class file:
Imports WatiN.Core
In your NUnit test project add a new method:
<test()>_
Public Sub IsGoogleWorking()
Dim objIE As New IE("http://www.google.com")
objIE.TextField(Find.ByName("q")).TypeText("Hicom")
objIE.Button(Find.ByName("btnG")).Click()
Assert.IsTrue(objIE.ContainsText("Hicom"))
End Sub
We want to run Watin with NUnit which opens up some funny threading issues we need to tell Nunit about. We do this by creating a configuration file called projectname.config.dll e.g. if my project was DE01Nunit the file would be called DE01Nunit.dll.config. Open this file in notepad and place the following:
< ?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configsections>
<sectiongroup name="NUnit">
<section name="TestRunner" type="System.Configuration.NameValueSectionHandler">
</sectiongroup>
</configsections>
<nunit>
<testrunner>
<!-- Valid values are STA,MTA. Others ignored. -->
<add value="STA" key="ApartmentState">
</testrunner>
</nunit>
</configuration>
Now run this test in NUnit and it should open up the web browser type Hicom in, search and check the search results contain Hicom.
Notes
The test recorder will generate some of this code for you but it will be in C# so VB users will need to change a few things
You might need to add a delay in to calls to pages (system.threading.sleep(1000) to give them a chance to load up
You can call javascript by using the runscript method
You can capture screen shots by using the CaptureWebPageToFile method
Sunday, September 07, 2008
New Sony Book Reader - some obvious flaws that should have been fixed
The reader device allows you to buy and download books which can then be read on the screen. Apparently it allows you to hold up to 160 ebooks and the battery lasts up to 7500 page turns. (further details at: http://www.waterstones.com/waterstonesweb/displayProductDetails.do?sku=6337796).

One of the most noticable things about this device is the screen is beautiful. I imagined it would be like a laptop or phone screen with horrible glare. Its not they have done a really good job on this.
However:
- Its £199, ouch!
- Books arent that much cheaper if at all (are you really asking me after paying 200 quid to pay 12.99 for a book?)
- It needs to be plugged in to download new books
- Books are not like music where you want to keep lots of songs. At most people are reading 2 or 3 books at a time and who cares if you can store 160 books your not going to flick through them unless they are some kind of reference.
- Not touch screen - why?
Nice try Sony but I dont think its there yet...
Friday, September 05, 2008
Book Review - The Career Programmer: Guerilla Tactics for an Imperfect World
(http://www.amazon.co.uk/Career-Programmer-Guerilla-Tactics-Imperfect/dp/1590596242/ref=sr_1_1?ie=UTF8&s=books&qid=1220614735&sr=8-1)
With development its quite easy to become engulffed in the technical aspects of the job, forgetting that it just exists as a small part of a business. This book is about these business aspects you need to be aware of and how best to deal with them from a development perspective.
I have heard much praise about this book and it got 4.5 out of 5 on Amazon so I thought it worth a read. Whilst the book raises some very good points I cant help but think it could have been written in about 20 pages. Some of the book is quite amusing, particularly the author recollecting their own personal experience but it really does waffle on and some jokes are very overused. It is obviously written by an American for an American audience which may irritate some UK readers. On the whole I found it quite negative at times about programming as a career - or maybe on the whole I have worked for decent companies (you know who you are non decent places...)
From the book these are the useful points I took away:
- When estimating time to complete a task estimate that only 60% of your day will be spent actually coding the rest on fixing, meetings, browsing adult sites etc
- Choose your battles - its not worth arguing every point even if you "know" you are right -something I know I can be drawn into :)
- Many times the ideas that are chosen are not necessarily the best - just the best presented and argued (all the more reason to practice speaking/presentation abilities!)
- Its important to be able to speak both tech and business (obvious but have seen many developers forget this)
- Testers should be made to feel part of the team - What you work in a company where they actually employ testers you lucky thing!
- You are not going to change some places, if you dont like it leave!

.gif)
