Monday, November 14, 2011

NLog Network Target

Recently at work, I'd been tasked with utilizing NLog's targeting system to dump data into our system.  NLog itself has been working really well for us, but the downside is that the documentation leaves a lot to be desired.  Furthermore, examples and samples are extremely limited.

So, how in the world do we utilize this?

My first thought was to tear everything open in .NET Reflector (ILSpy, since I can't find a free copy of .NET Reflector anymore) and then work to understand how it works.

The targets we were most interested in were the Network and Memory targets -- such that we could grab data that was being logged and then further process it.  Why not have our complex-event processing system also process logs as well?  A self-logging system.  Hell, why not?  Also, doing what your boss asks is generally a good way to stay employed.

The Network Target


So, the network target.  It handles several different variations of address -- UDP, TCP, variations of IP4/6.

The standard attack pattern for this is actually pretty much the same as any other TCP/UDP application.  Manage your clients (if necessary) and then process the data.


The only difference is that handling the data is different.  The chart above shows the general jist.

  1. When reading from the socket, convert your incoming data to a string.
  2. Ensure that it is decoded properly -- by default, your message will be in UTF8.
  3. Store message in a buffer.
  4. Scan for end of line characters and process as necessary.
It's pretty simple.  A very simple handler would look like the following:

  string incomingMessage = UTF8Encoding.ASCII.GetString(incomingSocketBuffer, 0, incomingLength);
  incomingStringBuffer.Append(incomingMessage);
  //Process and analyze for "\r\n"

Not bad, eh?  The above code assumes that incomingSocketBuffer is what was received from the Socket's Receive method, and the incomingLength is the length of what was received.  incomingStringBuffer is a StringBuilder that I use to store up the data.

Of course, there are much better ways of handling this, but this is the most simplistic and hopefully it demystifies NLog's Network target.

Friday, September 23, 2011

Heisenbugs! Schrödinbugs! Multi-Threading Programming, Quantum Mechanics, and You!

My team leader has a saying for strange bugs popping up -- Heisenbugs.  Your code is correct.  Everything should be fine.  However, for some reason...  BOOM!  Exception.  You lose some hair.  I think a more appropriate name is Schrödinbugs, though.  They appear to be correct and if you step through them, they'll work.  However, the second you stop observing them, they always seem to have the potential for a different result.  Ahhh...  unpredictability!

This is frustrating, but I've noticed one of the biggest problems generally stems from multi-threading.  Most developers aren't tuned to developing multi-threaded applications.  Even when they are, it's just another thing to watch out for when developing code.

So, you may be writing an application in WPF.  Say, it subscribes to an asynchronous TCP socket at the application level.  You have a callback on a user control.  Is there a potential problem?

YES.

Any time you have another resource that can act of its own accord and interface with another thread (events to the user interface, for example), you have a chance of having a Schrödinbug!  For example, at work I had a strange issue -- a control would hit the end of its life-cycle.  Disposed and all was well, right?  Well, not quite.  I had a DispatcherTimer that was syncing up some things for that control.  I stopped it in Dispose -- so the timer shouldn't be called, right?

Wrong.

The timer did stop -- but it had already entered its callback on the event thread.  The thread then swapped back to handle the Dispose that I had called.  It finished the Dispose, then went back to the event callback to finish.  Surprise surprise!  The control had been disposed and threw an exception.  So, how do we get around this?

I've developed a fairly simple pattern...  using a lock and the basic Disposable pattern.  I'm attaching the basic skeleton on how to implement this in your code:


    public class MyClass : IDisposable
    {  
        private object _lock = new object();
 
        #region IDisposable Pattern
 
        private Boolean _disposed = false;
 
        private void OnEventCallback(object sender, EventArgs e)
        {
            lock(_lock)
            {
                if( _disposed)
                    return;
 
                // Handle callback here
            }
        }
 
        /// <summary>
        /// When called, throws an ObjectDisposedException if the object has been disposed.
        /// </summary>
        protected virtual void CheckDisposed()
        {
            if (_disposed)
            {
                throw new ObjectDisposedException(this.GetType().Name);
            }
        }
 
        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
 
        /// <summary>
        /// Core dispose methods
        /// </summary>
        /// <param name="disposing">True if called from IDisposable::Dispose</param>
        protected virtual void Dispose(bool disposing)
        {
            lock (_lock)
            {
                if (disposing && !_disposed)
                {
                    // Clean up managed resources here
                }
 
                _disposed = true;
            }
        }
 
        /// <summary>
        /// Releases unmanaged resources and performs other cleanup operations before the
        /// <see cref="MyClass"/> is reclaimed by garbage collection.
        /// </summary>
        ~MyClass()
        {
            Dispose(false);
        }
 
        #endregion
    }


Notice the lock around the two most important parts -- I wanted to make sure that I have critical sections on the _disposed, such that I can break out as necessary.  Notice, if it enters the thread for the callback, we're fine.  If it disposes on the other thread, we can still break out before the code hits something disposed.  Essentially, we're making textbook critical sections and managing them appropriately.

Nothing unusual or entirely special -- just adapted to be mindful of another thread.

Wednesday, September 7, 2011

Control Lifecycle Gotcha's in Silverlight

I've come acrosss some more "fun" in Silverlight.  One of the most irritating (and not very well documented) pieces involves the tear-down and destruction of your controls.  Creation of controls is pretty simple, with a few caveats.

Control Creation


When a control or page is created in Silverlight, if the child controls are not visible, they are not "created."  Rather, they are created when they become visible.  For instance, if you have a Container control of some kind (Grid, etc) that is Collapsed, all of the child controls will not be created until it becomes visible.  Given how the rendering/layout engine works in WPF and Silverlight, this kind of makes sense -- only worry about what is visible.

Control Teardown and Destruction


The Unloading event occurs in a different order.


This is the most irritating part for me, as a developer.  Primarily because it doesn't make a whole lot of sense to me and is rather different compared to other frameworks.

Let's start with what we would think should happen, normally.  Supposing you had controls each in a hierarchy of:

A is the parent of B, which is the parent of C.

You would think C gets Unloaded first, then B, then A.

It's the exact opposite.

A is Unloaded, then B, then C.

If you have something, for instance, at point B that needs to be taken care of before C, you'll have some very frustrating issues ahead of you.  For example, C may consume resources that are created in B (such as a service).  Suppose the control is closed, B will attempt to clean up its resources before C does (assuming you've built your controls cleanly).  So, if C is still trying to access the resource created at the scope of B...  C will blow up with all kinds of exceptions.

Finalizers are called upon Application exit.

Not much to be said here -- whereas WPF and WinForms call finalizers generally as soon as the references disappear, Silverlight nukes them upon Application exit.  So, if you want to free up resources, you need to do that beforehand.

In Closing

In short, writing Silverlight is a bit more complicated and doesn't handle things quite as easily as other frameworks we're used to.  However, knowing the afore mentioned, you should be able to make your code cleaner and more efficient.

Tuesday, September 6, 2011

'x' was already registered by 'y' in Silverlight and WPF

So, I've had the extreme pleasure of working with a lot of Silverlight recently -- and my code in WPF had never been tested with multiple controls (stupid me).  When I did, I got all kinds of errors about properties not being set correctly, and eventually, after commenting out enough, I received the error

"'X' was already registered by 'Y.'"

So looking deeper, I notice it always happens on the second element.  Weird.  Looking further, I notice that my DependencyProperty pattern is basically declared at a private-instance level, i.e.:
DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof(string), typeof(SomeControl), new PropertyMetadata(string.Empty));
In Silverlight, this isn't a big deal.  In WPF, it's a deal-breaker.  It appears that Silverlight can automatically handle instance-level dependency properties (or more likely, translating bad code into them).  In WPF, it's not as forgiving and needs to be prefaced by:
public static readonly 
i.e.,
public static readonly DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof(string), typeof(SomeControl), new PropertyMetadata(string.Empty));

With that, everything works again and my Silverlight code doesn't break either.

Interesting difference between WPF and Silverlight, for sure.

Tuesday, August 23, 2011

Thank you Bing Maps!

After enough crying from developers, Bing Maps has apparently *finally* released a WPF control.

I had my solution *nearly* working -- with a few bugs I was going to ask Microsoft about in relation to accessing via quad-keys and getting a tile based on latitude/longitude via their web services.  Go to the blog and ten minutes prior to me arriving, they announced the official Bing Maps control for WPF.

Rejoice, friends!  Go get it!

http://www.bing.com/community/site_blogs/b/maps/archive/2011/08/23/announcing-the-bing-maps-wpf-control.aspx

Friday, August 19, 2011

I Want the World - A Thought Exercise in Building Map Controls for WPF and Silverlight

My latest task has been to build a Map control for our API at work, which has proven to be quite challenging.  Given that the Silverlight Toolkit is open source, it's easy to take the code, recompile it, adjust it so that it works for WPF, and then run with the customizations.

However, no developer has a good implementation of an open source map control that spans both Silverlight and WPF at the moment, which is a pain at the moment.

I've come up with the following plan to build something based off of Bing Maps:


  1. Use Bing Maps for Silverlight, but abstract all control/controls (except for the DeepZoom map tiles) out.
  2. Implement the map tiles via the WPF Bing Maps bindings.
  3. All layers on top will have to be built separately.
So, my first task has been to extract a lot of the functionality out of what has been given at Bing Maps (http://msdn.microsoft.com/en-us/library/bb259689.aspx).  Bing Maps works in a very interesting way.  At each "zoom level," the map's true size in pixel's increases.  At the base level (1 -- highest out), it is 512 x 512. For each level after that, the dimensions are multiplied by 2 (zoom level 2 = 1024 x 1024; zoom level 3 = 2048 x 2048; etc).  The highest zoom makes the map EXCESSIVELY large.  Mind you, only a few tiles in that space have been loaded though.

So, we need to make sure all "layers" on top of the map are done independently of the natural API of the Bing Maps control provided in Silverlight.  As such, I've built a wrapper to handle converting latitude/longitude to the pixel-based coordinate system that Bing Maps likes to use.  When the view is changed, the map will then update all controls as it moves.

If I can get my architect's permission, I'll likely be taking some of this code (only for the WPF version) and dropping it into CodePlex and/or MSDN, given that nobody has written a *decent* WPF Bing Maps control that's open.  I know there are quite a few on CodePlex, but the issue is that they're either shoddy implementations (too many layers of code/disorganization, poor code, running the AJAX version through a web browser control), or they're outdated and will stop working as the end of 2011, due to lack of support for the old Virtual Earth API.  Rather than any of these indirect implementations, I'll hopefully be posting a true WPF-based solution that relies on the Bing Maps web services with native WPF controls.

Wednesday, July 20, 2011

Silverlight and WPF Measurement Pain

One of the more irritating things I've been dealing with in Silverlight and WPF is that sizing and automatic content placement is a pain.  Don't get me wrong -- I love the new rendering engine and how it works to update the layout, but it can be a pain to "think in terms of WPF or Silverlight."  Especially when the two don't exactly have the same methods of working.

I made a decision fairly early on to build a static Utilities class, which holds all of my ugly code where I have to use the very, very, very fun

#if SILVERLIGHT            

#else

#endif

constructs, which gets me to the point of this post.

It's difficult to determine the size of a control -- especially the size it wants to be.  Ideally, yes, the DesiredSize will have that exact size.  Unfortunately, the DesiredSize is somewhat misleading -- it's the DesiredSize of the space it's confined to.  In addition, it works totally different between Silverlight and WPF.

I was primarily concerned with sizing things before they are rendered (they have no parent).  This is drastically different from figuring out a size once they are in the layout tree and the control itself has a parent.

In any case, I'm only going to cover the basics.  The most simple way to determine the size something wants to take up is to do artificially measure the element and then check the desired size.  Assuming I have a TextBlock named Frank, the following code would determine the size Frank really wants:

Frank.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
Frank.Height = Frank.DesiredSize.Height;
Frank.Width = Frank.DesiredSize.Width;

Ah, a crafty trick (and it works in both Silverlight and WPF without a hitch; if Frank didn't have a parent, the code would be different between the two platforms).  We make the control believe it has unlimited space, and then we can use DesiredSize.  Play with it a little bit -- set a breakpoint on DesiredSize before and after this call and see the difference.

For more information about how the Layout system works (which is an excellent read for understanding how WPF/Silverlight work), check out this MSDN article: http://msdn.microsoft.com/en-us/library/ms745058.aspx