Posts

Showing posts with the label C#

Printing bitmaps using CPCL

I've had no end of grief trying to print a PCX to a Zebra Printer using the CPCL printer language. Silly me, didn't notice the EG command (expanded graphics) so there was no need to convert my BMP to a PCX and then struggle with binary data. I still had a bit of grief working out how to print using the EG command because the documentation is quite frankly crap. The expected command format is EG {WidthInBytes} {HeightInPixels} {XPos} {YPos} {Data}\r\n The printer expects a 1 bit pixel matrix. So if pixel(0, 0) is set you will set "80" in the data. If pixel(0, 0) is set and pixel (7, 0) is also set you would sent "81". Basically what you need to do is to read each set of 8 horizontal pixels and then use bit operations to create a byte value 0..255, and then output this as hex 00..FF. Here's the routine :-) public void DrawBitmap(Bitmap bmp, int xPosition, int yPosition) { if (bmp == null) throw new ArgumentNullException("bmp");

The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

This new compile error was driving me mad! My project used to work, then I upgraded to a newer version of ECO. There were 3 projects using an EcoSpace, 2 would compile but not the 3rd. In the end the solution was simple but annoying to track down so I thought I'd mention it here just in case anyone ever strolls across it and finds it useful. In my licenses.licx files for the 2 projects I had the line Eco.Handles.DefaultEcoSpace, Eco.Handles but in the project that was failing somehow a strong name had been used, even though I originally entered it manually! Changing it back to the weak name fixed the problem.

Source control

At work we use SourceSafe for our version control, and I used SourceAnyWhere as the client. I would like to outline the facts and let you decide what happened for yourself. 01: I checked out my model (EcoModeler) 02: I added a new class. 03: Generated code. 04: Checked in the mode. 05: Checked out. 06: Added two new associations 07: Generated code. 08: Checked in. 09: Checked out. 10: Added a parameter to a method. 11: Changes a state machine diagram. 12: Checked in. After each of the changes I would implement code in my application that used them, so if the changes were lost at any point during this process then I would notice because my app would no longer compile. Today I checked out the model and noticed that my new class was missing. I backed up my generated source code and then regenerated code from the model. Using BeyondCompare I checked for differences and came up with the list of changes in the steps above. Somehow the model in my source control had 3 revisions missing. I

I've changed my mind on MonoRail

It is amazing! I'll leave that previous post just in case anyone ever needs to create an ECO object instance first and then connect it with an EcoSpace afterwards, but you don't need it for MonoRail! public void Join([EcoDataBind("User")]User user) { PropertyBag["User"] = user; if (this.Params["User.FirstName"] != null) { GetErrors(user.AsIObject(), Errors); if (Context.Params["ConfirmEmailAddress"] != user.EmailAddress) Errors.Add("Email address confirmation does not match email address."); if (Errors.Count == 0) { //TODO EcoSpace.UpdateDatabase(); Redirect("Account", "Home"); }//No errors } } That's all there is to it now! I have created a small set of classes to enable ECO support in MonoRail. Instead of descending your controllers from SmartDispatcherController you will now descend from EcoSmartDispatcherController . This gives the following abi

MonoRails, loving it

So I didn't like Ruby on Rails much. More accurately I didn't like the Ruby language or ActiveRecord much, but the "Rails" part I really quite liked! So my investigation continues and I have found myself looking at MonoRails. MonoRails is what I would have as a child called "a rip off", but these days it is known as a "clone" :-) It's basically a .NET version of Rails, which obviously appeals to me because I liked the Model-View-Controller approach of Rails and I obviously like C#. MonoRails has its own version of ActiveRecord (which I shall be avoiding) and an interface into NHibernate too (which I haven't looked at in great depth, but it certainly doesn't look as powerful as ECO). So I have been trying to get MonoRails working with ECO instead. Considering I don't know MonoRails at all I am surprised at how quickly I managed to do what I wanted. Take the following controller method as an example, when the user visits localho

Quantum bugs

I've just been driven mad by a "Quantum bug". What is a quantum bug? Well, it's a bug that doesn't exist unless you look at it :-) I kept getting a NullReferenceException in my code. It happened whenever I changed a property of a class. I assumed it was something in the framework, but it was in fact in a library of my own. When the property changed it would trigger an observer I had attached, the purpose of this observer is to check if the form that owns my component is the active form, if it is then it records the object that changed; the purpose is to know which objects were modified by which form. Anyway, to check if the form is active I do this Form activeForm = System.Windows.Forms.Form.ActiveForm; Form activeMdiChildForm = activeForm.ActiveMdiChild; if (activeForm == this.Form || activeMdiChildForm == this.Form) ..... Now the quantum! If you are debugging your app Form.ActiveForm will always return null! How useful is that eh? :-) So, when debugging

Convert absolute path to relative path

Today I needed to convert an absolute path to a relative path based on a specified base path. E.g. c:\a\b\c -> c:\a\b\c\d\file.txt = d\file.txt c:\a\b\c -> c:\a\file.txt = ..\..\file.txt c:\a\b\c -> c:\a\x\file.txt = ..\..\x\file.txt I am surprised there is nothing in the .NET framework so I had a hunt around and converted the code from the following URL ( http://www.vergentsoftware.com/blogs/ckinsman/default.aspx?date=2006-08-07 ) into C#.... private string RelativePath(string absolutePath, string relativeTo) { string[] absoluteDirectories = absolutePath.Split('\\'); string[] relativeDirectories = relativeTo.Split('\\'); //Get the shortest of the two paths int length = absoluteDirectories.Length < relativeDirectories.Length ? absoluteDirectories.Length : relativeDirectories.Length; //Use to determine where in the loop we exited int lastCommonRoot = -1; int i

Calling base constructors in C#

I occasionally find it annoying that I cannot specify at which point in a class's constructor I wish to invoke the base constructor. Having C# always invoke it before any of the code in my descendant constructor is executed sometimes causes me problems. Considering .NET is capable of calling the ancestor constructor at any point I wondered why C# wont allow it. I contacted Anders Hejlsberg and he was kind enough to reply, unfortunately he seems to have answered a question I didn't ask :-) Anyway, I have been deleting some old emails today and I came across his response, which he gave me permission to publish: The problem with Delphi's model (allowing constructors to be called on an already constructed object) is that it makes it impossible to have provably immutable objects. Immutability is an important concept because it allows applications to hand objects to an external party without first copying those objects and still have a guarantee that the objects won't be m

Delegates

I just remembered another technique for calling methods discovered via reflection! It is possible to convert a MethodInfo to a delegate and call it, this is just as fast as calling the method directly. So if you have a method that you call often which was discovered via reflection you should try this.... private delegate bool DoSomethingDelegate(object a, object b); MethodInfo methodInfo = type.GetMethod(.........); DoSomethingDelegate method = (DoSomethingDelegate) Delegate.CreateDelegate(typeof(DoSomethingDelegate), methodInfo); for (int i = 0; i < 1000000, i++) method(this, this);

Seven deadly sins of application development

Here is a list off the top of my head 1 - Ugly code! Why do some people set local variables to null when they have finished with them? This is .NET! The garbage collector will collect "unreferenced" objects when it is ready, an object is unreferenced if you no longer use the variable that holds the reference to it! Why do people name variables so poorly? Firstly I *hate* Hungarian notation. C# is a strongly typed language so I cannot multiply a boolean by a string, so why do people use variable names like "bIsMale" and "iAge"? 2 - Catching all exceptions An exception is something you expect to happen, but shouldn't happen if all goes well. If such an exception occurs you might know how to solve the problem and enable your application to continue, but if the exception type was unexpected how can you possibly know the cause of the error or what state your application is now in? Therefore I hate code like this try { DoSomething(); } catch { } 3 -

WeakReference woes!

Take a look at the following code if (myWeakReference.IsAlive) (myWeakReference.Target as SomeClass).DoSomething(); Do you see the mistake? The WeakReference may return "true" for IsAlive, but because the garbage collector runs within its own thread the value may actually get collected before the next line (because WeakReference.Target does not prevent the GC from collecting the value). I've been using WeakReferences quite a lot recently so I was happy to see that the following changes fixed the occasional NullReferenceException occurencies I had been seeing which were quite difficult to track down! SomeClass myInstance = (SomeClass)myWeakReference.Target; if (myInstance != null) myInstance.DoSomething(); The IsAlive property in my opinion is utterly useless (it is the same implementation as Target). I think MS should just remove it, you could say it would break existing code, but I say it would force people to fix it!