Monday, December 20, 2010

C# form topmost in application scope only

I was creating a little "Find" dialog box for my recent treeview application. I wanted the box to be like in Visual Studio itself, in the fact that the find box is topmost for anything in Visual Studio, but not over the rest of the programs that are running.

In the C# form designer, you can set the form to have "Topmost = true", which places the form on top of every window in the entire Windows scope. Not quite what I wanted...

To get it to be topmost, you need to call the Show() method when displaying the form, passing to it a reference to the parent form that it will always be on top of. Like so:

FindForm frm = new FindForm();

frm.Show(this);


(FindForm is my search dialog, and this is the parent form calling it)

Now it's topmost in the application scope but not in the Windows scope!

Wednesday, December 15, 2010

C# GUI Hangs on Invoke

If you've ever tried doing any advanced work using GUIs in C#, you'll be friends/enemies with the good old fashioned Cross-thread operation not valid exceptions. GUI controls run on their own thread and any other thread can't access them.

The great work around is to invoke the control. For instance, I use the following method to update a richTextBox control from any thread I happen to be in:

public delegate void StringParameterDelegate(string value);

public void UpdateRichTextBoxStatus(string value)

{

if (InvokeRequired)

{

// We're not in the UI thread, so we need to call Invoke

Invoke(new StringParameterDelegate(UpdateRichTextBoxStatus), new object[] { value });

return;

}

// Must be on the UI thread if we've got this far

richTextBoxStatus.Text = value + richTextBoxStatus.Text;

}



It checks to see if the control needs invoking (to avoid the cross-thread exception). If it does, it will reursively call itself again using a delegate and then update the richTextBox.

This worked fine and dandy most of the time. However, I had one condition where different invocations were happening at the same time, on different controls, but being invoked from an external, managed DLL. What happened is the invoke occured, but then the whole program hung on a call to the DLL.

Further investigation (god bless the parallel stacks threading debugging view) showed that one of the invocations went into a sleep state, waiting for the other invocation to finish. The Invoke call itself is synchronous, so the next invoke call was waiting for the original to finish. And hence the program just hung there. Waiting... waiting... never finishing.

Well there's an easy workaround for this. Instead of calling Invoke, call BeginInvoke! This makes the call asynchronous. The function thus becomes:

public delegate void StringParameterDelegate(string value);

public void UpdateRichTextBoxStatus(string value)

{

if (InvokeRequired)

{

// We're not in the UI thread, so we need to call BeginInvoke

BeginInvoke(new StringParameterDelegate(UpdateRichTextBoxStatus), new object[] { value });

return;

}

// Must be on the UI thread if we've got this far

richTextBoxStatus.Text = value + richTextBoxStatus.Text;

}

Tuesday, November 2, 2010

Icons for Nokia S60 applications

The Nokia Carbide designer can be a bit of a pain in the bit for anyone like me that is used to the ease of Visual Studio.

I recently spent half a day trying to get icons to show up for my applications, but it just caused it to keep crashing. Luckily I found this: http://tamss60.tamoggemon.com/2009/07/14/bitmap-application-icons-for-s60-symbian/

Saved me more hours of frustration.

Thursday, October 28, 2010

Nokia Carbide Errors x 650

I am shockingly new to Nokia development. Like, as in I started learning on Tuesday and today is Thursday new. My only experience with mobile development before was on Windows Mobile 6 and CE, which thanks to the brilliance that is .NET, was a piece of cake.

Nokia C++ (for Symbian S60, 3rd Edition, Feature Pack 2) is not. For starters, there's no strings. Just descriptors pointing to lots of things. And only once you get your head around this will any programming make sense. This website: http://descriptors.blogspot.com/ made everything make sense. Consider it the "Nokia C++ programming bible" if you will. At least the gospels according to descriptors.

Anyway, there I was programming some examples, when I got errors. A lot of them. 636 to be exact:

Errors such as:
declaration syntax error
(included from:
C:\S60\devices\S60_3rd_FP2_SDK_v1.1\epoc32\include\e32cmn.h:8
C:\S60\devices\S60_3rd_FP2_SDK_v1.1\epoc32\include\e32std.h:13
C:\S60\devices\S60_3rd_FP2_SDK_v1.1\epoc32\include\e32base.h:8
I spent hours and hours pulling my hair out fretting over these hundreds of errors! Why could these examples not compile! I DIDN'T CHANGE ANYTHING.

And then I solved it. It was embarassing. Are you ready?

I named my files with an extension .C. Not the .CPP which is the norm for C++. Once I changed to .CPP everything work fine.

This children, is why you must have cafienne before programming.

Thursday, October 14, 2010

Sync Toy = crap

I've recently got Windows 7. I went to sync all my pictures onto my backup harddrive, but found that briefcases are gone! As old and impractical as they were, they were perfect for just backing up pictures. They did all the hard work for me, albeit somewhat slow.

So I had a google, and found Windows had a new thing called Sync Toy. I loaded it up, started the sync and was told it was going to take a few hours. I left it going, but at some point I lost power and the sync didn't finish. Thinking it was like the briefcase, I went back later and just started it again. I figured it would just finish off.

But alas, no. It thought that since half the files weren't in the folder, that they'd been deleted. So Sync Toy went and deleted the original files that were never backed up!

I was lucky enough to have another backup on my recently abandoned computer, so I hardly lost anything. But I'm never using it again. From now on, purely going to Ctrl+c, Ctrl+v

Monday, September 20, 2010

C# Serialization problem

The core of the messaging program I am working on right now involves messages being encapsulated in XML. C# makes it really easy with their System.XML.Serialization classes. You just have to create a class, populate it, and feed it into :
XmlSerializer serializer
Then by running the Serialize() command you can turn it into XML data. Simple! Of course there's lots of customisation you can do with it, and then it becomes a powerful tool. However, this entry is not discussing the basics, just do a web search for it and you can find 100 of great examples.

My problem came from serializing my message classes. I had one base class, with lots of inherited classes. The very first time I ran either serialize() or deserialize() in my program, it would take up to 15 seconds to complete. But only for the first serialize/deserialize. Every subsequent one was quick.

A bit of research showed that C# builds up assemblies for the XML at runtime, only when needed. With the inheritance of my multiple classes, there was a lot of reflection and recursion done to build the assembly. And since I had it in my startup, my program would take 15 seconds to start up! Not acceptable.

It turns out there is a way to precompile these custom serialization assemblies, but it requires the construction of an additional DLL.

Since .Net 2.0, Microsoft has included a little executable in it's SDK to do it. It's in the SDK folder, so it may be different to my examples on your computer. The program is called SGen. It looks into any of your assemblies and builds up the serialization assemblies required. To use it, run the following command:
"C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 tools\sgen.exe" /f /v /a:
The flags are:
  1. /f = forces a rewrite of the file
  2. /v = verbose output, it's handy for figuring out problems with the serialisation
  3. /a: = the file to assemble the serialization assembly from. Replace with your .exe or .dll file.
Running this will create a a file with the assembly name followed by .XmlSerialisers.dll. Just place this DLL into the executable folder and it will load automatically on startup. On runtime, the program automatically checks for this file and no longer has to waste my 15 seconds compiling the serialisation data!

If you want to be tricky, move it into your post-build command:

Saturday, August 21, 2010

C# threads

For the last week or so I've been battling threads in C#. My background at university was largely in embedded programming, so the idea of parallel programming was not one I ventured into often apart from Java and GUI threads. When I did do parallelism, it was generally a quick hack using timers and poorly launched background workers or delegates. In this new program I'm working on however, I am developing a very safety-conscious service with lots of parallel threads, so I've been hitting the C# books virtually to learn my way through it. Here's some notes:

Timers
As I mentioned, I used to develop on GUIs. Moving to a service, you lose a lot of functionality if you are just copying and pasting a class over. One of these that I used to always depend on was the Windows.Forms.Timer. Apparently, when you switch over to a non-GUI program, it won't work. It won't even compile. (side note, I really need to change my AXIS camera control now. This last month of in depth C# programming has shown me the error of my previous ways.)

So I had to change all of my Forms.Timers to System.Threading.Timer. The problem is, it's not just simple swapping. There's no Tick method, there's no start or stop method. You initialise it and it starts running forever... Or does it?

Initialisation is easy. For a one shot timer you can use this, with TimeOut being an integer length of time in milliseconds, and timeOutTimer_Tick being the class that is called on tick.

_timeOutTimer = new Timer(timeOutTimer_Tick, null, TimeOut, TimeOut);

private void timeOutTimer_Tick(object state) {

if(Monitor.TryEnter(_timeOutTimer)) {

// do stuff
}
Monitor.Exit(_timeOutTimer);

}

In the initialisation call it is Timer(delegate, object, int, int). Obviously the delegate is the function to call on tick, the object is the state to be passed into our function (in my case null), the first integer is how long to wait until the first tick is fired (you can have a longer startup period) and the last integer is the tick length.

In the tick function you can see I have a Monitor.TryEnter() and a Monitor.Exit that passes the timer object itself. These calls try to place a lock on the timer object and only if locked willwe be allowed to process. This is very important in threading (it took me a few hours to find out) as it means no other thread can access it while you are working.

Two quick things.
  • For an one-shot timer, use Timeout.Infinite for the last integer
  • You can call _timeOutTimer.change() to change the timer length. It's very similar to the initialisation call.
Parallel Stacks
One of the great things about developing in Visual Studio 2010 is it's support for parallelism. In frustration I stumbled across some great debugging tools (I literally enabled every debugging window to see if there was anything there to help), the greatest being Parallel Stacks.


They let you visualise the parents/children of each thread and all of their current call stacks at once. If there are multiple of any thread, they are encapsulated in each bubble. Neato! You can read more about it here

Saturday, August 14, 2010

Windows forms styles in C#

Yesterday I was writing a nice little MDI form, and noticed something. My forms look like they were from the 80s. With blocked off group boxes instead of rounded and buttons from 3.1 days instead of the XP style they were supposed to be. On compilation and at runtime, they'd look nothing like they did in the designer.

So there were 2 ways you can get around this. Number 1 is a bit more effort, but it involves making a .exe.manifest file with the same name as your executable. In this manifest file you have some XML (http://www.dotnet247.com/247reference/msgs/15/79151.aspx, or http://www.codeproject.com/KB/cs/xpstyleui.aspx) which dictates how the controls appear. Then you have to change the "FlatStyle" property of each supported control to System.

That's great, it worked well, but it was fucking complicated.

Number 2 is much better. Call Application.EnableVisualStyles() before you launch the form. In my case, I called it before the parent MDI container was launched, and it fixed every internal form as well.

        [STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
And no having to change each control's style separately.

Thursday, July 22, 2010

Turn off the pesky internal speaker

One of my new projects has a pesky alarm that goes off through the internal speaker. When you're debugging and forcing errors on it, it drives the whole office crazy. Luckily, there's a way to turn off your internal speaker in Windows XP!

  1. Load up System Properties (start+pause break, or Control Panel>System)
  2. Go to the Hardware tab
  3. Press the Device Manager button
  4. In the drop down menu at the top, choose View>Show Hidden Devices
  5. In the window below, an option appears called Non-Plug and Play Devices
  6. One of the options will be Beep.
  7. Right click, choose Disable.
  8. Restart your computer if it asks
All annoyances gone!

Friday, July 2, 2010

Axis Camera Control

For my live image processing, I tend to use Axis products. Their cameras provide the images as a motion JPEG stream via Ethernet, while their video servers can convert full PAL/NTSC video to motion JPEG streams via Ethernet. It's handy, no real video converters required. Just plug your computer onto the same network as cameras, and bam!

There's a few way to get the images. Individual images can be accessed using an HTTP request:
http:///axis-cgi/jpg/image.cgi?resolution=704x576&camera=1
If you wanted to do that in C#:
System.Net.HttpWebRequest myReq;
System.Net.HttpWebResponse myResp;
myReq = (System.Net.HttpWebRequest)(System.Net.WebRequest.Create("http://136.18.33.16/axis-cgi/jpg/image.cgi?resolution=704x576&camera=1");
myReq.Timeout = 500;
myResp = (System.Net.HttpWebResponse)(myReq.GetResponse());
Bitmap bmp = new Bitmap(Image.FromStream(myResp.GetResponseStream()));
Easy. For easy access of motion video, Axis has provided the handy AxAxisMediaControl as part of their Windows SDK.

I've been using this for years, but have recently noticed a few problems. The main one being that the camera control has to always be visible in your form, otherwise it will just loop the last received image. So no screensavers, the program has to always be on top, and don't even think of hiding the Axis control (which is what I did, I wanted to hide the live stream). Also, to get the image into C# required some memory manipulation and even then the images were coming in upside down.

Despite trolling through the forums and support, there's no fix for this. It seems like I'm not the only one. Now this was a problem for me. I had a safety-critical program that was analysing 15+ frames a second 24 hours a day and could not be turned off. However, we needed to lock the computer up so that no one else could access the computer. Once we locked up the computer, the whole thing stopped working.

I tried work around, I tried accessing the image frame by frame using the HTTP request, but it was too slow. So in frustration, I created my own custom AxisCameraControl (download the code here).

Although not as complete as the Axis one (there's no audio or PTZ) it's perfect for receiving just motion JPEG streams. It has support for
  • multiple camers for video servers
  • password protected devices
  • limiting of maximum frame rate
  • different video sizes
  • autoreconnect on stream loss
  • limiting JPEG compression
The control is not a visible control, unlike the Axis one. It is more of a background threaded class. It has a lot of the same options as the original Axis control, but the following are always required:
public string IP;
public int Width;
public int Height;
public int Framerate;
When running (by calling public void Start()), a worker thread runs in the background. It opens up a motion JPEG stream to the device and looks for the start of each image. At this point, I have to credit/thank http://www.codeproject.com/KB/audio-video/cameraviewer.aspx for providing me with the motion JPEG code.

Once an individual JPEG is decoded from the stream, it throws an event.
Bitmap bmp = (Bitmap)Bitmap.FromStream(new MemoryStream(buffer, start, stop - start));
AxisArgs ax = new AxisArgs(bmp);
OnNewImage(this, ax);
The argument for the event (AxisArgs) is a Bitmap, allowing the image to be passed by value, not by reference like the old Axis control. After all of this, the image is disposed and everything is started again.

Usage in a program is fairly easy:
AxisCameraControl.Camera axisCameraControl1 = new AxisCameraControl.Camera();
axisCameraControl1.IP = "136.18.33.16";

axisCameraControl1.Width = width;
axisCameraControl1.Height = height;
axisCameraControl1.Framerate = frameRate;
axisCameraControl1.OnNewImage += new AxisCameraControl.Camera.NewImage(axisCameraControl1_OnNewImage);
if (!axisCameraControl1.IsPlaying())
axisCameraControl1.Start();

void axisCameraControl1_OnNewImage(object sender, AxisCameraControl.AxisArgs args)
{
Bitmap bmp = new Bitmap(args.Image());
//do something with bmp
pictureBox1.Image = bmp;
}
Simple! And it doesn't have to be visible to work. I've been testing this for the last month, and so far there seems to be nothing wrong with it. I've got a lot more work to do before it has the same functionality as the original AxAxisCameraControl, so I will update as it progresses.

Download the C# camera control class

Bugs:
  • On some servers, can take a few seconds to get the image started
  • If updating to a pictureBox with a high frame rate, the maximum frame rate drops dramatically for large images. Better to update pictureBox with an image every few frames for a frame rate over 8 FPS at an image size greater then 640x480

Thursday, July 1, 2010

RSLinx v Windows XP SP3

I'm in charge of a little, fully automated system that has it's own PLC and computer interfacing to it. The computer runs RSLogix 500/RSLinx and it communicates with a MicroLogix 1500 PLC.

The computer recently imploded (quite literally), so I migrated everything over to a new computer we had lying around. Everything was installed and running nicely in the office, I sent it off to site (in another state) to install the new PC, but we could not communicate with the PLC.

According to my site contact, the error we kept getting was something like (she spelt it out over the phone to me, it won't be exact):
initDriver failed code:-1
parentdriver (linx gateway may not be running)
After a few hours on the phone with Rockwell (we didn't have the tech support package, which made it difficult), I learnt something amazing.

RSLinx cannot communicate to devices using Windows XP SP3. Amazing. Our PC was recently rolled back from Windows 7 to XP, and I guess it was SP3 that was installed. Everything else works beautifully, but the RSLinx communications drivers (at least for Ethernet) will not.

So now I'm trying to figure out how to roll back to SP2 without losing anything. I'll keep you posted

Friday, June 11, 2010

C#, searching for an element in a list

The List class is mighty powerful. It can make an arraylist out of any class. The problem is that it's not always easy finding some internal class value in an object in that list.

Say I have an alarm class:
public class Alarms
{
public DateTime time;
public enum alarmType { major, minor };
public string originator;
}
And a lot of these are encapsulated in a list:
List alarmList;
If a user is looking at this list (probably in a listview) and has modified a value of an individual alarm in the list, how do we find that alarm in the list? (In my program, it's a temporary buffer which multiple threads write to and from)

Simply put, we use delegates.

If the user has extracted an alarm from the list called "al" and modified the values, and then wants to put it back to a list that has probably been modified and has new index values, use this:
int indexToLookFor = alarmList.FindIndex(delegate(Alarms alarm)
{
return alarm.time == al.time && alarm.alarmType == al.alarmType && alarm.originator == al.originator;
});
if (indexToLookFor >= 0)
{
//the alarm has been looked at, make it a minor one
alarmList[indexToLookFor].alarmType = alarmType.minor;
}
It uses the FindIndex function of , comparing each variable of the class. Granted, you could write your own For loop to do it, but this is much quicker, and in my opinion, more grand.

Tuesday, June 8, 2010

Catching the enter key in a C# textbox

It's simple, but useful:

     private void textBoxProductKey_KeyPress(object sender, KeyPressEventArgs e)
             {
                 //pressing the enter key, ladies.
                 if (e.KeyChar == 13) {
                     //do your thing

                 }
                 e.Handled = true;
             }


The keyboard code for enter is 13.

Thursday, June 3, 2010

C# Bitmap manipulation

I tend to do a bit of image processing in C#. Using SetPixel() and GetPixel() is such a time consuming process, especially when you are image processing live video streams.

The solution? Do it in pointers. I could go into detail using pointers in C#, but that's everywhere else on the net. So just know that you do it in Unsafe mode. Don't forget to enable Unsafe mode. Go to Project>Properties>Build and check Allow Unsafe Code in Visual Studio.

The following block of code will then enable you to edit a single pixel:
        Bitmap theImage = new Bitmap("C:\\theimage.jpg");
        int stride; //stride of the image for processing (basically padding at the sides of images
        BitmapData bmData = theImage.LockBits(new Rectangle(0, 0, theImage.Width, theImage.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
        stride = bmData.Stride;
        System.IntPtr Scan0 = bmData.Scan0; //pointer to the pixels of the image
        int width = theImage.Width;
        int height = this.Height;
        unsafe
        {
            //code is "unsafe" as it has pointer operations
            //don't freak out too much, "unsafe" doesn't mean this will blow up in your face
            byte red, green, blue;
            byte* p = (byte*)(void*)Scan0;  //pointer to the first pixel of the bitmap
            byte* pOriginal = (byte*)(void*)Scan0;
            int nOffset = stride - width * 3;    //offeset increment for each line
            p = pOriginal + 3 * (x) + stride * y;
            blue = p[0];
            green = p[1];
            red = p[2];
            //do whatever
        }
        theImage.UnlockBits(bmData);
This will do one pixel, of a 24 bits per pixel bitmap, with the Byte* variables blue, green and red being that particular colour of the pixel from 0 to 255. The variables are:
  • theImage - a Bitmap file that you are manipulating
  • stride - how wide the image is, in padding terms
  • bmData - the raw bitmap data
  • Scan0 - pointer to the first bite of the pixel
  • p - the byte address of the individual pixel you want to work on
  • pOriginal - the byte address of the first pixel. If you are doing iterative work, it's easier just to have this as a pointer variable for the pointer math
  • x and y - integer values for the x and y co-ordinate of the pixel being set
I tend to do iterations only over regions of interest, so I do iterative loops which just assign a new value for p (based off of x and y) and change the individual blue, green and red colours. To change the values of the colours, use code such as:

blue = (byte)255;
green = (byte)0;
red = byte(0);
That will make the pixel blue.