KIS Systems, Inc - Contract Programming for Unix/Windows/Web in C++/C#/PHP/Qt/.NET and other technologies.

KIS Technoblog

Technical ruminations from our chief codemeister – Rick Berger

Archive for the '.NET' Category

Namespaces – A Good Thing

Posted by rickb on 30th November 2007

I’m becoming more of an advocate of namespaces.

Traditionally, they’ve been defined informally by prefixing function and/or variable names with some unique mnemonic – such as ‘Q’ for Qt stuff, ‘wx’ for wxWidgets stuff, or even something as potentially ambiguous as ‘C’ for MFC stuff.

All well and fine and helpful, but you can still run into name collisions. For instance, I was browsing the mac utility headers a while ago and ran into a raft of ‘QT’ names – for QuickTime. Dangerously close to ‘Qt’.

The newer languages, such as C# and Java, enforce namespaces. In C#, you can’t write a single line of code, unless it’s wrapped in a namespace.

The usefulness was heightened for me in a recent project with C#: we were attempting to use an underlying module for statistical binning and drawing. But, we needed a highly optimized version so we could dynamically select bins and draw the results on the fly.

Some customization was in order.

Now, in an ideal world, we would go to the creators, explain what we needed, and collaborate with them to get the enhancements we needed. In the real world, though, the creators are off doing something else highly urgent, and we’re not on their ‘to-do’ list.

So, we did the undesirable: clone the module and get the modifications in, ourselves.

Of course, we didn’t want our version to collide with the older version. How to avoid? Simple: since it’s C#, there’s guaranteed to be a namespace associated with the module. Just change the namespace of our cloned module and proceed.

Voila! (I’m writing this in Paris, so I get to stick in my bit of francaise.)

Of course, things aren’t quite so simple – the binning module used several namespaces (a bit of fragmentation overkill, IMHO), and relied on other underlying modules, which had to be detected and determined if they needed cloning, namespace changes, et al. It still can get pretty ugly. But the namespace feature helped.

Another time when namespaces would have been useful was when a somewhat recalcitrant vendor provided a package with a modified libjpg. Naturally, none of our stuff that relied on libjpg worked any more after we integrated their new code…

After the initial shock and dismay, we had to come up with a solution – the vendor was in Germany and were perfectly happy with the solution, as it was, so were disinclined to make changes. In that case, I think we isolated their libjpg into a fully resolved dynamic library along with their system, and didn’t export the jpeg functions. A pain in the ass, to be sure.

Back then, namespaces weren’t widely supported in the compilers (notably, Microsoft), but had they been, it could have been a better solution. Granted, libjpg is in C, but it can be compiled as C++ and then wrapped in a namespace that would prevent it from colliding with our libjpg (assuming we could get the vendor to cooperate.)

As software grows, and applications become more of a ‘mash-up’ of different modules, namespaces can become an increasingly important construct to eliminate conflicts. For instance, if Trolltech wrapped everything in a ‘TT’ namespace, or, better yet, a ‘TT_QT’ namespace, it would disambiguate them from any other code that might just happen to start with ‘Q’. Like ‘QT’ for QuickTime.

So, in my current effort (creating an extension for Qt), I’m wrapping everything in a namespace (’KIS_QX’). It means users will have to sprinkle ‘using’ statements in their code. A bit onerous, admittedly, but I think utimately that namespace usage is a good habit to get into.

Posted in .NET, C++, CSharp, Programming, Qt, Software Development, software, wxWidgets | No Comments »

Pointers in C#-land – Episode II

Posted by admin on 7th December 2006

So, I’ve been a bit derelict (and busy).

Pointers, Cont’d

Let’s see – when last we left, we were discussing pointers in C#, how they’re used properly and all of that. Now, we’ll look at some improper usage.

Recall we can create a ‘fix’ block tied to a pointer, thus:

   float[] fAry;
   ...
   fix (float *pAry = fAry)
   {
      // reference (but not change) the pointer.
   }

All well and good, but, what if we do something like this?

   class AClass
   {
      private float[] fAry;

      float *GetArray()
      {
         fix (float *pAry = fAry)
         {
            return pAry;
         }
      }
   }

If little bells aren’t going off in your head, they should be. What happens when we return a pointer from a fixed block? Think local variable – when you return a local variable, it’s abandoned on the stack and no longer guaranteed to hold the value set while the function block was active (in scope.)

Well, the same thing happens to fixed pointers. They’re abandoned out of scope, and the includes a return – they’re only valid while the blocked scope is active. You can pass them down, but you can’t pass them up, because the scope is gone on return.

(This, parenthetically, is what the aforementioned system I was using was doing. Instead of taking it at face value, I should have scrutinized the pointer return more closely…)

Another Way

You could do the above the following way:

   class AClass
   {
      private float[] fAry;
      private GCHandle hAry;

      float *GetArray()
      {
         hAry = Alloc(fAry, GCHandleType.Pinned);
         float *pAry = (float *)hFloatBuf.AddrOfPinnedObject().ToPointer();
         return pAry;
      }

      void ReleaseArray()
      {
         hAry.Free();
      }
   }

The returned pointer can be used to the caller’s heart’s content.

Of course, the rub is that ReleaseArray() has to be called when the caller is done. Otherwise, the memory is pinned forever and things start slowing up, because the garbage collector has to work around the pinned block. There are a lot of things that can cause that to happen – an uncaught exception, a premature return out of an ‘if’ block or loop, or just plain forgot that was how we implemented it (my personal bane.)

So, we need something a bit safer, with no funky policy to define.

We could try something like this:

   class AClass
   {
      private float[] fAry;
      private GCHandle hAry;

      GCHandle &GetArrayHandle()
      {
         return hAry;
         // return the handle.
      }
   }

Now, the caller gets a handle, and they can pin/unpin the memory as they wish. But, what’s the point? If we’re going to give the caller control, just return a reference to the item and be done with it:

   class AClass
   {
      private float[] fAry;
      float[] FAry { get { return fAry; } }
   }

   ....

   // caller code
   AClass aClass;

   fix (float *pAry = aClass.FAry)
   {
       // reference the pointer.
   }

Or they can lock it with a GCHandle or whatever. The main thing is that the caller has declared the pointer, and in so doing, know they are responsible for it’s un-pinning/un-fixing. That keeps the pointer locking/unlocking in the same block or at least in the same context, if not scope.

rickb

Posted in .NET, CSharp, Programming | No Comments »

Back to the Metal

Posted by admin on 11th November 2006

Had to put together a small Open Inventor demo program, the other day, using the straight Win32 API.

It’s jarring, to say the least, to go from a fluid development environment like C# back to the cranky C/C++ world – compounded by going from .NET to WinAPI. I had to take a few moments to recollect myself, reset my head to having to deal with synchronizing header files and long builds and the myriad things that can go wrong when they’re out of sync. Like accidentally declaring a pointer outside of a class in a header file. (multiply-defined objects – remember extern?).

But, the reason I had to do this is illuminating, as well: I had to divide the development between the client’s environment, which has the C# adapter for Open Inventor, and my local environment, which does not (cost issues.) Qt might have been a reasonable choice, but 1) Qt isn’t available at the client’s location and, 2) it isn’t available on my home system co-joined with Open Inventor, either.

So, those are always the trade-offs – compatibility with baseline systems at little or no up-front cost (but more work), or shell out the bucks (mucho, in the case of Open Inventor and Qt) to have everything work seamlessly across the board.

Turns out there is, I believe, an alternative set of tools. I’ll be exploring them over the next few weeks.

Stay tuned.

rickb

Posted in .NET, C++, CSharp, Programming | No Comments »

Win32 API – Can’t Get Away

Posted by admin on 27th September 2006

Ran into a window controlling problem with C#/.NET – a couple of things in the API aren’t exposed. The first is (are, really), the messages WM_NC* (used to detect non-client mouse hits, etc.) The second is the ability to set window settings via the SystemParametersInfo call. In this case, I want to use SPI_{SET/GET}DRAGFULLWINDOWS. C#/.NET exposes the GET functionality, but not the SET.

The first case is handled relatively painlessly – simply a matter of putting a message filter on the app and then watching for the hwnd and WM_ message of interest. You don’t want to get too carried away with message filters – every message that goes through the message pump is forwarded to the filter, first, once installed. So, you install it only when you need it, and remove it when you don’t. And just do minimal processing, while you’re in there.

The second problem requires an interop call to the user32 dll and getting that all set up properly. Not terrifically taxing, but not perfectly straightforward, either. It’s unfortunate the named constants for the SPI_, WM_, etc values aren’t available in the toolkit. You have to redeclare them in your code, somewhere (don’t want to use raw numbers, for sure.)

On one hand it points out the shortcomings of a kit like C#/.NET – on the other, it’s always nice to know I can get under the cover/lift the hood when I need to.

rickb

Posted in .NET, Programming, Win32 API, Windows, software | No Comments »

The ‘new’ keyword – an oddity in C#

Posted by admin on 17th September 2006

Here’s something different: The ‘new’ keyword can have different semantics in C#, depending on the context:

  • As an instantiator – the normal context you would think of, ie:

    'new String'

    .

  • As an explicit member hider – a different context, ie:

    'new public func(int iarg)'

    where ‘func’ is something that is defined in a base class and may or may not be overrideable.

It’s no big deal, just an oddity. I’m trying to think of another language where a keyword has completely different semantics depending on context. I can’t think of any, of the top of my head.

The former definition and usage is something that’s familiar to anyone versed in OOP methodology and languages: instantiate me an object of the named type.

The latter is something that is basically a tell to the compiler – your saying, in effect, “Yes, I am hiding a member and I’m doing it intentionally, and please don’t bug me with any more warnings about it,” and the compiler acknowledges the usage and doesn’t say anything more about it.

You wonder if, during the design hammer sessions deep in the bowels of MS, whether anyone balked at this and proposed a different keyword to fit the different semantic: ‘hider’ or ‘cover’ or some such thing.

Only the MS insiders know. Meanwhile, we’ll ‘new’ a class for an instance, and ‘new’ a member we intentionally want to hide in that class and move on, happily.

rickb

Posted in .NET, CSharp, Programming | No Comments »

.NET ‘Validating’ event and ‘ErrorProvider’ class

Posted by admin on 29th August 2006

Found this little gem while looking to constrain textbox input to numeric.

It works by constructing an ErrorProvider instance in the container form, and then specifying and setting validation states during the ‘validating’ and ‘validated’ messages sent from the control. ErrorProvider is a generally available class that signals the error by flashing an icon next to the control with the offending input

It has some interesting points – ErrorProvider can be used in anything, not just textboxes. It locks focus and input to the control until you correct the input, and puts up a little blinking icon (which you can specify), to draw your attention to the offending input

Not quite the same as the Qt validator mechanism. I think Qt’s is better in that invalid input is suppressed by the supplied filter and won’t echo (it’s filtered out), however, it is very specific to textboxes.

In .NET, the invalid input is still echoed and the invalid state isn’t flagged until you move focus off the offending control. There may be a way around that (to provide a keystroke filtering behavior), but the standard implementation doesn’t appear to provide for it, that I can see.

Under the ErrorProvider topic in the MS documentation, there’s a lengthy example. You can reduce it to the following though (to restrict input in a textbox to numeric, for example):


  private Textbox inputTB;
  private ErrorProvider numberInputErrorProvider;
  private Regex regxNumeric;
              // declare these somewhere in your class...
              // the regular expression is used to qualify the validation.

  ...
  ...

  numberInputErrorProvider = new ErrorProvider();
              // create in the constructor of your *container* class

  regxNumeric = new Regex("^[0-9]*(\.[0-9]*){0,1}$");
              // ditto this - keeps it from having to be re-compiled
              // on every invocation.

  inputTB = new Textbox();
  inputTB.Validating += new
                  System.ComponentModel.CancelEventHandler(NumericTB_Validating);
  inputTB.Validated += new EventHandler(inlineFilterTB_Validated);
              // set up the textbox and add the event handlers.

  ...
  ...

  // gets called on focus loss
  //
  private void inputTB_Validating(object sender,
                                  System.ComponentModel.CancelEventArgs e)
  {
     TextBox tb = sender as TextBox;
     if (! regxNumeric.IsMatch(tb.Text))  // this is the test against the textbox text
     {
        e.Cancel = true;
        numberInputErrorProvider.SetError(tb, "Input must be numeric.");
                // this sets the error
     }
  }

  // Don't forget to add this!!  You need it to clear the error...
  //
  private void inputTB_Validated(object sender, EventArgs e)
  {
     TextBox tb = sender as TextBox;
     numberInputErrorProvider.SetError(tb, "");
  }

And, that’s pretty much all there is to it.

Posted in .NET, CSharp, Programming | No Comments »

On C#/.NET

Posted by admin on 28th August 2006

The current contract brings us into the C#/.NET world. Now that I’m up somewhat up to speed on it, I have a few first-blush thoughts:

The Language

First off, I can say I like the language. As in PHP and Java, the joy of being able to code and re-factor in almost “stream-of-consciousness” mode, without concern of headers and without long compile times is wonderful.

Syntactically, it is close enough to C++ that the transition is almost transparent, not unlike PHP and Java. Major differences are lack of pointers (except in ‘unsafe’ mode), and a larger number of access modifier keywords. Static vs. Dynamic is very well supported (although it would be nice to be able to declare a class ’static’, just for clarity.

What am I missing? For one, the inability to specify explicit ‘friends’ is a drawback. I can use (and am using) the ‘internal’ accessor keyword to restrict access to the current assembly, and that’s ok, but not completely sufficient.

This project is in 1.1: that means no ‘generic’ classes – the semi-equivalent of the C++ ‘template’ keyword. That is unfortunate. I’m having to write a few classes that vary only in type and are just screaming, “GENERIC”.

The ‘delegate’ type is equivalent to Qt’s signal/slot mechanism, although I don’t know if it’s as efficiently implemented, especially in 1.1. Syntactically, it is a bit clumsy, especially in the declarations, but adding and removing listeners is pure simplicity, using the ‘+=’ keyword (a far cry from the incredibly clumsy Visual Basic syntax to achieve the same thing, especially in the multi-cast scenario.)

Namespace support is very good and simple. I like that.

.NET

Another framework, another ‘App/Main Window/Supporting code/Dialog’ architecture, although the App class is a bit removed from the developer. You can access it, but not derive from it – you have to put working code elsewhere. Mostly I need it to clear messages Application.DoEvents(); before doing something heavy.

Thread support is good – named threads facilitate debugging. The UI thread is separate from all other threads and anything UI-ish must be done on the UI thread. In general, I don’t mind that – it does mean a bit more complication if you want to tie a UI piece, like a dialog, to a specific thread. I understand 2.0 has better support in this area, as well.

There’s a good, rich suite of controls and windows. They are more interchangeable than in the MFC construct, and dialogs are just a special type of window, rather than their own entity. It makes construction of dialog-based or other window-based applications much simpler.

Development Environment

I have some love-hate issues with the IDE: to begin, due to the verbosity and complexity of the language, it is almost indispensible. As big a fan of vi that I am, I wouldn’t want to try coding a lot of C# with it, at least not without a lot of ‘using’ keywords at the top. And, the language (again, like Java) encourages ‘onionskin’ layering of classes. With the proliferation of classes and interfaces, you’d be forever looking up names and members without the completion feature of the IDE.

Perhaps the most infuriating thing about the environment is the debugger – more often than not, when you get a crash, it can’t find the source. This is likely because the ‘real windows’ implementation is buried down in a system assembly, somewhere, and the debugger doesn’t see it. You resort to setting ever closer and closer breakpoints to discover the problem – almost, but not quite, as bad as print statements.

Summary

All in all, it’s a good environment and I like working in it. Of course, I have the normal “Microsoft Only” issues with it – I’d like to see a cross-platform implementation, but it will never come from Microsoft. There are open-source efforts, but they’re slow and will never catch up with the million-monkey-programmer army in Redmond.

Posted in .NET, CSharp, Programming | No Comments »