.NET

Entity Framework Cheatsheet

This is my cheatsheet for using Microsoft's Entity Framework API.

(The existence of this page should not be taken as an endorsement of Entity Framework. It's not something you should learn more about if you don't have to. It's just another complicated ORM framework with its own quirks and annoyances.)

Measuring Elapsed Time in C# Methods

When determining why some damned thing in my .NET programs is taking so damned long, it is useful to be able to look at the elapsed time for various sections of code. The straightforward way to do this is to create an instance of System.Diagnostics.Stopwatch, start it, do the thing, then stop the Stopwatch and print out the elapsed time.

But it gets tedious to keep adding those var stopwatch = new Stopwatch(); stopwatch.Start(); and stopwatch.Stop(); Print(stopwatch.ElapsedMilliseconds); lines all over the place, and it also makes the code less readable, so I made a little class to simplify things.

Creating .NET Remoting IPC Channels

Yet another C# code snippet. I'm developing a service and an accompanying UI that always run on the same physical box, and it was suggested that I implement the communication between them using .NET Remoting and the IPC channel type, which is a supposedly-easy way to get processes on the same machine to talk to one another.

Of course, it wasn't easy, because if you simply create and register an IpcChannel with default parameters, you get security-related exceptions when you try to do anything with it. You have to delve through documentation and online forums to figure out what underdocumented magic is required to get the stuff to actually work.

There were two obstacles I had to overcome:

  • By default, user-defined types will not be deserialized, to prevent deserialization-based attacks by malicious clients. To disable this "feature", one must set the TypeFilterLevel to Full.
  • My service runs as the LocalSystem user, whereas the client application runs in the logged-in user's security context. By default, the user's account would not be able open the IPC port that the service creates. The fix to this is to set the channel's authorizedGroup to the name of a user group that is allowed to open the port.

So, as usual, the resulting code looks simple, but it took a couple of hours to figure out what had to be written.

Pretty-formatting XML in C#

I had a need to convert an XML string to a nice, indented format. It was a little more complicated than I expected, so I'm posting this snippet here where I can find it again when I need it.

using System;
using System.Text;
using System.Xml;
using System.Xml.Linq;

static string PrettyXml(string xml)
{
    var stringBuilder = new StringBuilder();

    var element = XElement.Parse(xml);

    var settings = new XmlWriterSettings();
    settings.OmitXmlDeclaration = true;
    settings.Indent = true;
    settings.NewLineOnAttributes = true;

    using (var xmlWriter = XmlWriter.Create(stringBuilder, settings))
    {
        element.Save(xmlWriter);
    }

    return stringBuilder.ToString();
}

Note that this method can throw exceptions for a variety of reasons.

Remoting.Corba

[Note: The Remoting.Corba project is "dead", and has not been active for several years. If you need .NET-CORBA interoperability, I recommend checking out IIOP.NET. Archived Remoting.Corba documentation is still available via The Wayback Machine.]

Remoting.Corba is an open-source .NET library that provides interoperability between the .NET Framework and CORBA servers/clients, using the .NET Remoting architecture.

I started this project to learn more about .NET Remoting and to apply my knowledge of CORBA. My basic goal was to be able to write .NET programs that interacted with CORBA-based applications using typical .NET Remoting code. For example, if a CORBA server supported this IDL:

// CORBA IDL
interface Adder {
    long add_longs(in long arg1, in long arg2);
    double add_doubles(in double arg1, in double arg2);
};

then one could write a C# program that invoked the server, without need for an ORB, using code something like this:

// standard .NET Remoting stuff
using System;
using System.IO;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Messaging;

// Remoting.Corba
using Remoting.Corba.Channels.Iiop;

namespace MyExample
{
    // define .NET interface mapping for IDL interface
    interface Adder {
        int add_longs(int arg1, int arg2);
        double add_doubles(double arg1, double arg2);
    };

    class App {
        // entry point
        static void Main(string[] args)
        {
            try
            {
                // register IIOP channel with Remoting
                ChannelServices.RegisterChannel(new IiopClientChannel());

                // Use a standard CORBA stringified object reference for the server
                string ior = "corbaloc:iiop:localhost:9999/Adder";

                // create the proxy to the server object
                Adder server = (Adder) Activator.GetObject(typeof(Adder), ior);

                // execute some methods on the remote object
                Console.Out.WriteLine("1 + 2 = {0}", server.add_longs(1, 2));
                Console.Out.WriteLine("1.0 + 2.0 = {0}", server.add_doubles(1.0, 2.0));
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("Exception: " + ex.ToString());
            }
        }
    }
}

The IiopClientChannel class from the R.C library takes care of generating and interpreting the CORBA IIOP (Internet Inter-ORB Protocol) messages and pumping them through the .NET runtime. There is also an IiopServerChannel class that can be used to implement CORBA servers using .NET Remoting.

It was pretty cool when it worked. The .NET Framework's Remoting architecture is very open, allowing programmers to plug in their own network protocols and messaging formats. I used some custom attributes to provide information needed by the CORBA engine that could not be gleaned via data types and reflection mechanisms.

Unfortunately, while the .NET Remoting architecture is open, it is not well documented. If all you want to do is send a SOAP message via some protocol other than HTTP (for example, via UDP, via message queues, via e-mail, etc.), then it is pretty easy to plug your own stuff in. But if you are doing anything more complicated, then you will quickly discover that the only way to figure out what's going on inside .NET is to look at the Rotor source code.

The project was valuable to me in that I learned a lot about .NET and C#. It was also gratifying to see other people using it and expressing interest in it. I was especially excited when it was mentioned in Don Box's Spoutlet, and when Miguel Icaza started playing around with it in Mono. It even got a few pages devoted to it in a Microsoft Press book!

I wrote this code during a period when I was not working any paying jobs, so I was always hoping I would find somebody willing to pay me to add features. There were a few nibbles, but users were generally able to add features themselves instead of hiring me to do so. I talked to some people at Microsoft and Inprise about potential deals, but nothing came of it.

I have put a few projects on SourceForge, but this was the first one where I got any significant contributions from other developers. Michael Sawczyn created an IDL compiler. Other developers did some bug fixing, refactoring, and feature additions. It never reached the "critical mass" needed to keep it going after I lost interest, but I think it was close.

I worked on R.C for a few months. I lost interest in it due to several factors:

  • No paying customers.
  • No real need to use it myself.
  • All the low-hanging fruit was gone; further development would have involved a lot of very technical work with little tangible benefit.
  • The appearance of commercial CORBA ORBs for .NET from Borland and others.
  • Limitations of the .NET framework

We hit limitations of the .NET framework when trying to figure out how to map remote object references back to objects in the same process. The only way to do it was to use reflection to invoke private methods of internal .NET classes. That prospect triggered enough of an "Ewww!" response that I decided further work was only going to make me feel worse.

I used a wiki to distribute the "documentation" for the project. I liked how the wiki turned out, but there were few contributions to it from anyone except myself.

So what did I get out of Remoting.Corba? Obviously, I learned about .NET Remoting and some more about the internals of CORBA. I got practice writing C# networking code. I made some contacts in the industry. I wish I could have used R.C on a real project, but that might have taken the fun out of it.

Syndicate content