Archive for the ‘.NET’ Category

The Mandelbrot Set meets Rapid Development Tools

The first time I wrote this program, it was a DOS-based program. I wrote my own putpixel routine in x86 assembly for it (among other things). It took me a few sleepless nights to finish writing it.

Today I got bored and wrote it again. It took less than a half hour this time.

The Mandelbrot Set in C#

Somehow, it was more satisfying the first time.

Four Irritating Lines of Code

At many places in the framework, you’ll see properties of types named for the enumerations or types they receive. I was indifferent to that until just now.

I just wrote these four lines of code. It took much longer than it needed to.

BinaryFormatter f = new BinaryFormatter();
f.FilterLevel = TypeFilterLevel.Low;
f.TypeFormat = FormatterTypeStyle.TypesWhenNeeded;
f.AssemblyFormat = FormatterAssemblyStyle.Simple;

Consider the last three lines. None of the enumeration names are even close to the corresponding property on the formatter.

For all three of these, I typed out something like this:

f.FilterLevel = FilterLevel.

[No Intellisense, there’s a problem]

[Backspace repeatedly]

f.

[Intellisense shows up; oh, it’s “TypeFilterLevel”]

f.FilterLevel = TypeFilterLevel.Low;

Maybe the usability studies didn’t make it to System.Runtime.

WTF

This Daily WTF reminded me of a guy I used to work with who would use this pattern in every single function he wrote.

Public Const cSTRINGFOO As String = "foo"

Public Function Foo() As Boolean
    Dim ret As Boolean = False
    Try
        Console.WriteLine(cSTRINGFOO)
        ret = True
    Catch ex As Exception
        ret = False
        Throw New Exception("", ex)
    End Try
    Foo = ret
    Exit Function
End Function

I’m not sure what he was expecting to happen here, but there were some clues:

  • Every function he wrote returned true or false to indicate that it had successfully completed without an exception.
  • Every exception was wrapped in another, except where he forgot and swallowed the exceptions.
  • He would always use constants for string literals, even if he only used the literal once (like above), and even if the constant was much longer than the literal.

Mind you, I discovered this self-imposed standard a while after he quit, so I never really got to the bottom of it.

Bizarro TypeInitializationException in System.Runtime.Remoting

We’ve seen this exception on two occasions in three months in a production environment. I’m going to throw it up here since there are no Google hits on it so far, at least that I can find.

System.Reflection.TargetInvocationException:
Exception has been thrown by the target of an invocation. ---> 

System.TypeInitializationException: The type initializer for
"System.Runtime.Remoting.Channels.Http.HttpRemotingHandlerFactory" threw an exception. --->
System.MissingFieldException: Field not found: ?.s_webServicesFactoryType.

   at System.Runtime.Remoting.Channels.Http.HttpRemotingHandlerFactory..cctor()

   --- End of inner exception stack trace ---

   --- End of inner exception stack trace ---

   at System.RuntimeType.CreateInstanceImpl(Boolean publicOnly)

   at System.Activator.CreateInstance(Type type, Boolean nonPublic)

   at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr,
Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)

   at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr,
Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)

   at System.Web.Configuration.HandlerMapping.Create()

   at System.Web.Configuration.HandlerFactoryCache..ctor(HandlerMapping mapping)

   at System.Web.HttpApplication.GetFactory(HandlerMapping mapping)

   at System.Web.HttpApplication.MapHttpHandler(HttpContext context,
String requestType, String path, String pathTranslated, Boolean useAppConfig)

   at System.Web.MapHandlerExecutionStep.System.Web.HttpApplication+IExecutionStep.Execute()

   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

This is a type initializer (.cctor) in System.Runtime.Remoting throwing up because one of the private fields cannot be found. Here’s the type in Reflector, proof that something is definitely rotten in the state of Denmark.

The s_webServicesFactoryType static field

The type initializer is just trying to set this field to null.

HttpRemotingHandlerFactory static initializer

Here are some more of the details:

  • The servers were different, but running the same application. Their windows patch levels would have been the same.
  • w3wp is set to recycle on these servers. This exception will happen constantly (thousands of times) until the recycle happens forcibly or on its own, then it goes away.

So, I think this is definitely a JIT or assembly loader bug related to some obscure timing issues. If I can get the native image or a full process dump while this is happening, presumably this could be tracked down.

Console.WriteLine with Wordwrap

Here’s a class I wrote that will write with wordwrap to standard out in a .NET console app. There are a few other nifty options.

using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;

namespace McKinley
{
    public sealed class Out
    {
        [StructLayout(LayoutKind.Sequential)]
        private struct COORD
        {
            public short X;
            public short Y;
        }

        [StructLayout(LayoutKind.Sequential)]
        private struct CONSOLE_SCREEN_BUFFER_INFO
        {
            public COORD dwSize;
            public COORD dwCursorPosition;
            public short  wAttributes;
            public SMALL_RECT srWindow;
            public COORD dwMaximumWindowSize;
        }

        [StructLayout(LayoutKind.Sequential)]
        private struct SMALL_RECT
        {
            public short Left;
            public short Top;
            public short Right;
            public short Bottom;
        }

        private const int STD_OUTPUT_HANDLE = -11;

        [DllImport("kernel32.dll")]
        private static extern IntPtr GetConsoleWindow();

        [DllImport("kernel32.dll")]
        private static extern bool GetConsoleScreenBufferInfo(IntPtr hConsoleOutput,
            out CONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo);

        [DllImport("kernel32.dll")]
        private static extern IntPtr GetStdHandle(int nStdHandle);

        private static CONSOLE_SCREEN_BUFFER_INFO StdOutInfo()
        {
            IntPtr hOut = GetStdHandle(STD_OUTPUT_HANDLE);
            if(hOut != IntPtr.Zero)
            {
                 CONSOLE_SCREEN_BUFFER_INFO info;
                 if(GetConsoleScreenBufferInfo(hOut, out info))
                 {
                     return info;
                 }
            }
            return new CONSOLE_SCREEN_BUFFER_INFO();
        }

        private static Point GetCursorPosition()
        {
            CONSOLE_SCREEN_BUFFER_INFO info = StdOutInfo();
            return new Point(info.dwCursorPosition.X, info.dwCursorPosition.Y);
        }

        private static Point GetConsoleWindowSize()
        {
            CONSOLE_SCREEN_BUFFER_INFO info = StdOutInfo();
            return new Point(info.dwSize.X, info.dwSize.Y);
        }

        /// <summary>
        /// Writes <paramref name="val" /> to standard output with word wrap.
        /// Each line is indented by <paramref name="indent" /> characters,
        /// and is prefixed by the string specified by <paramref name="prefix"/>.
        /// </summary>
        public static void WordWrap(string val, int indent, string prefix)
        {
            int max = (GetConsoleWindowSize()).X;
            string pad = new string(' ', indent)+prefix;

            Regex r = new Regex(@"([\w\.]*(\s)?)");
            Match words = r.Match(val);

            int count = (GetCursorPosition()).X;
            if(count == 0)
            {
                 Console.Write(pad);
            }
            else
            {
                 Console.Write(prefix);
            }
            count = (GetCursorPosition()).X;
            while(words.Success)
            {
                 string word = words.Value;
                 count += word.Length;
                 if(count >= max-1)
                 {
                     Console.WriteLine();
                     Console.Write(pad);
                     count = word.Length + pad.Length;
                 }
                 Console.Write(word);
                 words = words.NextMatch();
            }
        }

        /// <summary>
        /// Writes <paramref name="val"/> to the standard output
        /// with word wrap. Each line is indented by
        /// <paramref name="indent"/> characters.
        /// </summary>
        public static void WordWrap(string val, int indent)
        {
            WordWrap(val, indent, string.Empty);
        }

        /// <summary>
        /// Writes <paramref name="val"/> to the standard output
        /// with word wrap.
        /// </summary>
        public static void WordWrap(string val)
        {
            WordWrap(val,0);
        }

        private Out() { }
    }
}

Remoting Email Thread

Here is an email thread I had recently with some good information in it. Rather than try to condense it, I’ll just post the thread.

Things I need

It would be really great if any of these things existed. Some of them might, but I’ve been unsuccessful in finding any of them.

  1. A utility that finds/cleans files that are in Visual Sourcesafe, but are not found in Visual Studio projects and/or solutions. When a file is ‘deleted’ in VS2003, it’s not removed from VSS. Repeated on a vast scale, this gets annoying and throws a wrench into some other things that I’m trying to do.
  2. A NAnt task that lets me use csc/vbc for all files in a Visual Studio project. I need the command line arguments (ie, /debug:pdbonly) for both of those, and the convenience of the solution task. (Of all of these, it seems like this is the most likely to exist and I just haven’t found it.)
  3. DebugEngine extensions intended for ASP.NET apps. They should be able to show me the pages that are running, the HttpContext for each request, the items that are in session, and so forth.
  4. Someone who can take difficult, complex programming tasks from me. Ideally they would be smart enough that I would trust them implicitly, rather than agonize about the projects on a daily basis.
  5. A Visual Studio project type for managing a number of XML files. By that I mean, a bunch of NAnt scripts. Actually, any tool that has a solution-like treeview and a document outline utility will work.
  6. PowerCollections, but for .NET 1.1. (Yeah, yeah, it might not be too hard to port them myself).
  7. An “Add New Item…” item in Visual Studio that has NO default name set (like “Class1.cs”), NO autogenerated comments, and has internal access by default. If I call the item IAnything, it should figure out that the item is an interface and not a class.

I’ve had some success lately eliciting comments from knowledgeable googlers, and I have high hopes for this post.

No True Object Programmer, Part Deux

Edit (2/28): What I have to say about raising an event asynchronously in VB is very incorrect. If you got here by googling “raise event async VB“ (or thereabouts), do not listen to me. Read Bill McCarthy's comment about it.


Well, Bill loves VB.NET, and knows a lot about it. I am in a slightly different camp, in that I (arguably) know a lot about it because I am forced to use it at work, but I haven’t grown to love it very much.

But as to your difficulty in parsing VB.NET code, well as you said, VB.NET is actually more natural. It is probably more that you need practice reading and writing the code.

I concede that this is probably true. I’ve been staring at C/C++/Java/C# since I was 11 years old, so it’s quite likely that’s the only reason I find it more natural. It doesn’t really help that I switch between VB.NET and C# projects on an almost hourly basis these days. I’ll jump to the VB project and start typing:

StringBuilder sb = …

Whoops. Wrong one. Apparently I can’t make the jump as effortlessly as the woman shouting into a cellphone on the train next to me last week weaved an intricate and impressive unbroken stream of Spanish/English (“Spanglish?”).

So yes. Readability is probably a personal problem.

This started out, I guess, as a discussion about which language was “more OO.” That’s may be a vague metric, so I’ll try to limit the discussion here to which language lets you accomplish the task at hand in the simplest possible way with minimal connectivity and shared knowledge between your objects.

In the case of events, I think that at best, this is a draw. This is an opinion.

VB wins when it comes to a few useful abstractions: the RaiseEvent keyword, and declarative event handling (the WithEvents/Handles keywords).

In a comment on Bill’s blog, I referred to these as “leaky abstractions” (to borrow shamelessly from Joel). What I mean by that is, they work beautifully in the simple cases, but in more sophisticated situations they break down and you’re forced to understand what is actually going on. VB may or may not leave you with a way out, once you’ve done the learning bit.

My first example here was raising an event asynchronously. Here is code that accomplishes calling event handlers on another thread in C#.

internal class MyClass
{
    public event EventHandler MyEvent;

    protected virtual void OnMyEvent(EventArgs e)
    {
        this.MyEvent.BeginInvoke(this, e, null, null);
    }
}

Here is code that accomplishes the same task in VB.NET.

Friend Class SomeClass
    Public Event MyEvent As EventHandler
    Private Delegate Sub EventRaiserDelegate(ByVal e As EventArgs)

    Protected Overridable Sub OnMyEvent(ByVal e As EventArgs)
        RaiseEvent MyEvent(Me, e)
    End Sub

    Protected Overridable Sub OnMyEventAsync(ByVal e As EventArgs)
        Dim del As EventRaiserDelegate = AddressOf OnMyEvent
        del.BeginInvoke(e, Nothing, Nothing)
    End Sub
End Class

Bill’s correct, you can raise an event asynchronously in VB.NET, albeit in a roundabout way. Unless there's a radically different method I haven't thought of, I need to write and then call OnMyEventAsync, which calls a traditional event raiser on another thread.

Here is where I think the claim that VB is “more OO” breaks down. The representation of the event as a list of functions (which is what C# gives you) was significantly simpler for us in this case. We got the job done with less code, so in my mind C# wins the OO battle here.

As to events in Vb.NET, I'm sorry but there is no "inadvertant GC rooting". I don't know who told you that, but you/they were sorely mislead.

On serialization, Vb.NET has absolutely no problems with XML serialization. There is however an issue with binary serialization and MarshalByRef classes. The real problem is MarhsalByRef classes, eg a Windows.Form, cannot be binary serialized. If you need to work around that, you can do so in Vb.NET 2005, and more elegantly than C#.

Poor terminology on my part, I guess. What I was referring to with “GC rooting” was the situations where a programmer attempts to dereference an expensive object so that it may be collected. A common mistake is leaving events wired up (and hence, a reference that has a gc root).

Is that any more difficult to deal with in VB than it is in C#? No, not really. Touché. But am I justified in calling an event a “leaky abstraction” if they require a deeper understanding of function pointers and GC in order to keep your program from hogging memory? I think so.

So that leaves the last sitch: serialization. MarshalByRef is actually not what I was thinking about, but it’s closely related. MarshalByRefObjects are at least serializable, and unless you are persisting to a storage medium you will succeed in serializing a graph if your only mistake is having a ObjRef going along for the ride.

Objects that are not [Serializable()] at all are a bit more problematic. You’ll get an exception which will be difficult to track down if you have event handlers wired up to any of these. C#’s got an easy way out (google it; my post is getting really long, dammit). The hacks VB will force you into in some cases is likely to make you cry. I know it made me cry.

So which language is “more OO?” That’s impossible to answer objectively, and it probably makes no sense to even try, but I’ll tender a personal opinion.

My feeling is that VB gives you some keywords that are useful for simple OO. Unfortunately, it obscures some of the underlying nuts and bolts, and this gets in the way of your own attempts at OO abstraction. C#, on the other hand, is a little better at ensuring that the realities of the CLR are quickly accessible if you need them.

In an ideal world, we’d have both in one language. But forced into a choice, I’ll opt for seamless access to the guts. Keeping my own objects as loosely coupled as possible is what I’m most interested in doing.

No True Object Programmer

Did you love the No True Scotsman argument? Well, get ready for the arguments!!

Explicit Interface mapping. This is incredibly cool. Unfortunately a lot of people just don’t get how important this concept is to true OO.

He continues:

As to VB.NET over C#, VB.NET is actually a far more OO language when you look at the actual implementation details.

(did I hear a record scratch?)

Far more?

At the risk of Ad Verecundiam, I’ve actually been on the phone with a Microsoft employee who said these words: “C# is a much better choice if you intend to do object development.”

Bill doesn’t expand on that argument really, other than the appeal of the End keyword. It would be a silly thing to get into an argument about, but my feeling is that End XXX makes VB code less readable. I would like to see more reasons why this could be true.

I apologize for any haughty, dismissive tone. I wrote this while working on a brick of Parmigiano Reggiano and sucking down a bottle of Chianti, so it just kind of came out that way.

N-Tier Remoting Frustrations

Link.

People DO want n-layer, because that provides reuse, maintainability and overall lower costs. Logical separation of UI, business logic, data access and data storage is almost always of tremendous benefit.

People MIGHT want n-tier if they need the scalability or security it can offer, and if those benefits outweigh the high cost of building a physically distributed system. But the cost/benefit isn’t there as often as people think, so a lot of people build physical n-tier systems for no good reason. They waste time and money for no real gain. This is sad, and is something we should all fight against.

I think I agree with this in total.

The project I work on has hit basically every problem with Remoting that exists.

  • Unbelievably slow dataset serialization (see KB829740). Kind of a big issue for us because many of our developers aren’t so comfortable with creating their own data structures / objects, and consequently were relying very heavily on ADO objects. I resolved the speed issue by implementing my own formatter sink.
  • SocketExceptions (specifically, WSAENOBUFS) when transporting huge amounts of data. To some extent this is mitigated by better hardware. Although Q322975 refers to this as a “BUG,” we spoke with the Remoting development team through our premier support guys and they refer to this as designed behavior. There isn’t a quick fix (ie, registry change) here, so I’m going to have to try putting in a compression sink to get us some headroom.
  • The lack of a default remote call timeout. This killed us in production because of 1) a network problem and 2) some bad codes that circumvented the HttpRuntime’s executionTimeout in a very unfortunate way. It took us 4 horrendous days of the servers crashing every 20 minutes with three Microsoft CPR people on-site to finally figure out what the problem was.

There are probably a few others which I am forgetting now. I am still talking to MSFT reps about the second, but I have no expectations that that will get anywhere.

But getting back to my main point (yes, I had one). The really frustrating part about this for me is that I don’t even consider our middle tier to be necessary. We put it there primarily for security purposes, and I don’t know, maybe we get that. But with respect to the way most of our developers write code, this is no help. It doesn’t necessarily create a logical service boundary, because nobody really gave them the direction to do that. To an extent it just makes the spaghetti worse.

Now for my secondary point. A lot of this is certainly our fault. But what drives me crazy is comments like this one:

This does assume you listened to advice from people like Ingo Rammer, Richard Turner and myself and avoided creating custom sinks, custom formatters or custom channels. If you ignored all this good advice then you’ll get what you deserve I guess…

It’s frustrating as hell to be backed into creating workarounds for lousy performance which you (well, your boss, who mandated this architecture) were never warned about and then to be openly mocked for doing so by the ‘experts.’ If we had known that Remoting would be throwing us this many problems, we probably would not have tried to use it for n-tier, and maybe with a little luck we would have decided against our flavor of n-tier altogether.

Get us some better advice, folks.