There’s more to parenting than fucking biology

It’s easy to make a kid; everybody can fuck. (And to be clear I’m only considering cases where this is something you both wanted.) If you’re a guy, just stick in your penis and wriggle it around until you cum. Wham bam, thank you man! Your work here is done! If you’re a gal, let him stick it in there. Admittedly, you get the bulk of the biological work and get to blow up like a balloon and go through literal Hell for nine months, get sore feet, get weird cravings and wild mood swings, then get to stretch a tiny little hole into a not so tiny one and go through some excruciating pain to shit out the little shit, but… Hey, you signed up for this!

After that, the real work of parenting begins. And thanks to the wonders of modern bottled milk, anyone, even a new mother, can ditch the kid and the other parent, and leave them to it.

I wasn’t the best dad at the start. In fact, I was terrible. But I did my best even when I was an addict, and did a lot better the last few years, raising kiddo by myself. I think of life like having to cross an endless series of treacherous roads. At first, kiddo needs to be carried. Then he or she can crawl. Then they walk, with you holding their hand all the way, teaching them about the racing cars that will mow them down, the tanks that will squash them to bits, and the weird old men with their trucks that they pull over to slide open the door and say, “Welcome to the joy mobile where the ice cream is free and the fun never ends! Come on in.” Then one day they will be able to walk by themselves, but always with you to help them as long as you’re still alive.

Seriously, parenting is hard work, much harder than the brief bit of pleasure it took to make the child. That why messages like this make no sense:

No

“No, I’m still the mother of your child”. Biologically, yes. But was she ever his parent? I don’t fucking think so.


I should probably delete this horrible post.

 

 

 

My other blog is now private, until further notice

My programming blog is now private, and will remain as such until I can review its content.

This is due to a new confidentiality agreement sent to everyone by my employer. The terms used to describe intellectual property are ambiguous, and while its concept of proprietary information does exclude “generic knowledge that I would have learned in the course of similar employment elsewhere”, the clauses about source code are ambiguous enough to warrant a concern.

While I feel that the source code and programming examples I shared were generic, and were written at home to describe solutions for programming problems I solved at work, coded into examples that referred to no proprietary information from my employer, I can’t be certain that the content doesn’t contravene their definition of intellectual property.

My apologies to anyone who found this looking for the other blog, and to my followers of the other blog.

It’s too easy to judge addicts, but we shouldn’t.

Every so often I’m reminded how we judge addicts. We all do it – look down on them because it makes us feel a little better. Even I did it last week; shared a meme with an image that was trending on Facebook, of a girl with a trolley more or less attached to her, and some condescending text about meth. Now I’m sorry I shared it.

People used to judge me too, and write me off, but last night I was reminded of some stuff I achieved on meth. I was looking around on my hard drive because it’s getting full and I need to delete some old files, when I found a backup directory, a backup of my old drive from a few years ago, because I gave the drive to my ex…

It contained a lot of evidence, not of my drug use, but of the results of my tweaking on the computer. Besides the movies and downloads, there was also some source code I’d forgotten about.

I’ll try to make this as simple as possible, but that isn’t easy. I’d written my own video player, in c# using DirectShow. It’s not great, but it works, and it works pretty well. But it only plays video files directly. At some point, I was interested in playing DVDs too. So I found source code that I could use, a tutorial with some sample code on playing DVDs from c#. The only problem was, my video player code was “tightly coupled” to the form that uses it. So the form, which should just be the user interface (with the buttons to play and so on) included all the code for playing videos. Not only that, but it does some funky stuff with background threads, for example so that if you click “next”, it already knows all the files in the directory. Plus it has features like frame stepping and player speed that aren’t necessarily implemented in the DVD player code.

So, to change my player so that it could play files or DVDs, I had two options:

  1. Use inheritance. This would involve defining a base “player” class, and having two derived classes. One would be the file player, with all the existing code moved to it, and another would be a DVD player class.
  2. Define a “player” interface. This interface would contain the definitions for all the stuff the player did, but only the definitions. Then I’d have two implementations of this interface, one with my existing code, and another for DVDs. (The DVD player would then not implement the methods or properties that were specific to the file player, or at least fail gracefully at those things.)

Apparently I decided on option two. “Apparently” is quoted because I was so high, I don’t remember any of that. But it’s there – I found that I went as far as defining the interface. Then I stopped there, because it would be a couple more days work to refactor my code, and then implement the DVD playing code, as well as having some way (an “abstract factory” probably) of deciding an runtime which implementation to use based on what was being played. The bulk of the work would be the refactoring… There’s a lot more that I’m not mentioning, such as the peripheral details around the two kinds of players. The file player has a concept of play lists, which involves relative paths to the locations of files on disk, and it can also persist the starting position (and ending position which allows for playback loops because I was tweaking) within files, while a DVD player would need to be able to navigate a menu system, and switch between different tracks. The code for the file player to “know” the difference between playing files in a list verses playing whatever is in the directory, is messy. Not to mention repeat modes… on reaching the end of a file, it must decide, based on the repeat mode, whether to go to the next file, or repeat the file, or if set to repeat the whole list/directory, decide what to do then based on the index within the list/directory (and lastly if super-duper tweaker pervert porno repeat cumshot loop is engaged, repeat that part of the file when it gets to the end of the section, or check if there is a loop to repeat when loading a new file. Sigh… Tweaking leads to strange complications). That shit would be complicated to refactor, and even on meth I was too lazy to do all that.

The point is, I did some hard-core programming shit on meth. This is unfinished code, but I have had the dubious “pleasure” of working with some less talented programmers over the years, programmers who were incapable of doing what I could do when I was on meth.

Don’t judge people just because they’re on drugs. Being an addict doesn’t make anyone stupid, although it certainly does lead to them doing some stupid things. (For example, writing video players when you’re tweaking on porn – then not actually watching the porn but rather going off on a tangent writing a fairly feature-rich video player.) While you’re laughing at people and putting them down, there are some good people out there who just made some bad choices. Some of them are more clever or gifted than you can imagine, and a little empathy goes a long way.

Another way addicts are often judged, and sorry if you’ve read what I’ve written about this before, is the so called “faces of meth”, photos shared online with the pretence of it being about deterring others from using meth. It’s never about that. It’s about laughing at people less fortunate than yourself. It’s also about missing the point.

I won’t share such images myself, but I will state an example. I remember seeing one of those images of a girl who supposedly used meth for ten years. She was a pretty girl, probably about seventeen in the first image, then more or less a year older in every subsequent image. But here’s the problem: The first image, where she looked pretty, was a police mug shot. She was arrested for drug possession and prostitution, and was probably already living on the street. Do you see where I’m going with this? In the before image, she was probably already using meth for at least five years, maybe longer. And as for the rest, they were pictures of a woman living on the street, most likely using multiple drugs, including but not limited to meth. Once you get to the point of living on the street, meth is soon out of range of what you can afford, unless of course you happen to be a career criminal. And of course, career criminals and long time prostitutes have more factors affecting their appearance than the number of years they use meth.

Edit: This needs to be expanded on… Career criminals and the people associated with them, who are committing crimes for their drugs, don’t have normal lives. Contrast this with normal people who happen to be addicts… who still go home to their houses where they shower, brush their teeth, get dressed and go to work every day. (And then maybe party all night and every weekend, sometimes disappearing for a day or two each month after they get paid.) They’re nothing like those pitiful looking photos you see in mug shots online.

So while you look at those photos and laugh at the subjects in them, you miss that most addicts look nothing like those people. Most addicts are working normal jobs, and you would never guess they’re using drugs. People might work while using for up to twenty years, before they reach that point where they can’t work any more. And it’s all too easy to judge them while you have a drink every day, or do cocaine occasionally. You might find yourself judging them even after you’ve already become one of them. And when that happens, you might realize as I did, that those “photos of meth” are not a deterrent at all. They’re one of many ways to misunderstand how widespread and dangerous addiction really is, allowing you to see addicts in terms of stereotypes rather than reality.

More good code I wrote when I was high

Again I was surprised to find some good code that I wrote way back when I was high. I might post this one to my programming blog tomorrow as well, slightly repurposed without the mention of drugs, and a title “How to load a cursor from embedded resources in C#”.

Anyway, that’s what it does. Via some code that I found and then modified, my image viewer, when viewing an image that’s larger than the viewable area, allows you to use the mouse to drag around and pan to different parts of the image. When doing this, the program changes the mouse cursor, to one of two cursor images that I designed myself and drew pixel-by-pixel (I was indeed tweaking my ass off), one for a hand that’s up and one for a hand that’s down.

Here’s what it looks like when the hand down cursor is displayed. (Main mouse button is pressed so you can pan the image… in the application – not here because this is just a fucking screenshot.)

Viewer

And here’s the code (that I took ages to figure out) that loads the cursor, which is saved as a file resource, from the applications resources:

using System;
using System.Runtime.InteropServices;
using System.Security;
using System.Windows.Forms;

namespace Romy.Core
{
    public static class CursorResourceLoader
    {
        #region Methods

        public static Cursor LoadEmbeddedCursor(byte[] cursorResource, int imageIndex = 0)
        {
            var resourceHandle = GCHandle.Alloc(cursorResource, GCHandleType.Pinned);
            var iconImage = IntPtr.Zero;
            var cursorHandle = IntPtr.Zero;

            try
            {
                var header = (IconHeader)Marshal.PtrToStructure(resourceHandle.AddrOfPinnedObject(), typeof(IconHeader));

                if (imageIndex >= header.count)
                    throw new ArgumentOutOfRangeException("imageIndex");

                var iconInfoPtr = resourceHandle.AddrOfPinnedObject() + Marshal.SizeOf(typeof(IconHeader)) + imageIndex * Marshal.SizeOf(typeof(IconInfo));
                var info = (IconInfo)Marshal.PtrToStructure(iconInfoPtr, typeof(IconInfo));

                iconImage = Marshal.AllocHGlobal(info.size + 4);
                Marshal.WriteInt16(iconImage + 0, info.hotspot_x);
                Marshal.WriteInt16(iconImage + 2, info.hotspot_y);
                Marshal.Copy(cursorResource, info.offset, iconImage + 4, info.size);

                cursorHandle = NativeMethods.CreateIconFromResource(iconImage, info.size + 4, false, 0x30000);
                return new Cursor(cursorHandle);
            }
            finally
            {
                if (cursorHandle != IntPtr.Zero)
                    NativeMethods.DestroyIcon(cursorHandle);

                if (iconImage != IntPtr.Zero)
                    Marshal.FreeHGlobal(iconImage);

                if (resourceHandle.IsAllocated)
                    resourceHandle.Free();
            }
        }

        #endregion Methods

        #region Native Methods

        [SuppressUnmanagedCodeSecurity]
        static class NativeMethods
        {
            [DllImportAttribute("user32.dll", CharSet = CharSet.Unicode)]
            [return: MarshalAs(UnmanagedType.Bool)]
            public static extern bool DestroyIcon(IntPtr hIcon);

            [DllImport("user32.dll", SetLastError = true)]
            public static extern IntPtr CreateIconFromResource(IntPtr pbIconBits, int dwResSize, bool fIcon, int dwVer);
        }

        #endregion Native Methods

        #region Native Structures

        [StructLayout(LayoutKind.Explicit, Pack = 1)]
        struct IconHeader
        {
            [FieldOffset(0)]
            public short reserved;

            [FieldOffset(2)]
            public short type;

            [FieldOffset(4)]
            public short count;
        }

        /// <summary>Union structure for icons and cursors.</summary>
        /// <remarks>For icons, field offset 4 is used for planes and field offset 6 for 
        /// bits-per-pixel, while for cursors field offset 4 is used for the x coordinate 
        /// of the hotspot, and field offset 6 is used for the y coordinate.</remarks>
        [StructLayout(LayoutKind.Explicit, Pack = 1)]
        struct IconInfo
        {
            [FieldOffset(0)]
            public byte width;

            [FieldOffset(1)]
            public byte height;

            [FieldOffset(2)]
            public byte colors;

            [FieldOffset(3)]
            public byte reserved;

            [FieldOffset(4)]
            public short planes;

            [FieldOffset(6)]
            public short bpp;

            [FieldOffset(4)]
            public short hotspot_x;

            [FieldOffset(6)]
            public short hotspot_y;

            [FieldOffset(8)]
            public int size;

            [FieldOffset(12)]
            public int offset;
        }

        #endregion Native Structures
    }
}

The code that uses it, in another class, is just this:

        /// <summary>Loads the two hand cursors from project resources.</summary>
        private static void InitializePanBoxCursors()
        {
            if (handUpCursor == null && handDownCursor == null)
            {
                handUpCursor = CursorResourceLoader.LoadEmbeddedCursor(Properties.Resources.Hand_up);
                handDownCursor = CursorResourceLoader.LoadEmbeddedCursor(Properties.Resources.Hand_down);
            }
        }

It still amazes me that I wrote some more than decent code back when I was tweaking my stupid head off.

This will be the last late night post for a while. My son gets back tomorrow, and since we share a room, I normally go to bed the same time he does. Actually I’m tired and am going to sleep right after posting this. Good night…

I’m still baffled by source code I wrote when I was on meth

Apologies to most people reading this who are not programmers. This post won’t make much sense. But I try to avoid drug references on my programming blog, so this belongs here… And also an apology to anyone who saw this post published by mistake the first time, before I added the image.

I still use this monstrosity of a program I wrote a few years ago. I shouldn’t, because it tries to do too many different things in that it was my scratchpad for all new code I learned for a few years, but it works well for some of them, so I use it even though I know it has its quirks. It’s more or less a file browser, image viewer, video and audio player (via Direct Show which is now obsolete), and can do some minor image editing. But mostly it’s an image viewer. It builds and maintains its own cache of thumbnails, which looks kind of like the large icons view in Windows Explorer. Then double-clicking those thumbnails opens the program’s built in image viewer.

Here’s what it looks like:

RomyView

Anyway, one of its quirks is that there’s a bug somewhere in the custom TaskScheduler (I think) and that can have weird effects like hanging the whole application after deleting a directory. (Sometimes.) So while looking at all the code that references my own TaskSchedulers, I came across this code, written while I was super duper high…

/// <summary>Load a Shell thumbnail image and add it to the cache.</summary>
public static async Task<ThumbnailCacheItem> LoadAndCacheThumbnailAsync(string path, CancellationToken token, bool requiresCurrentDirectory = false)
{
    var item = ThumbnailCacheItem.Invalid;
    var tcs = new TaskCompletionSource<ThumbnailCacheItem>();
    var isSmallImage = false;
    var failed = false;

    try
    {
        using (CancellationTokenSource cts = new CancellationTokenSource(),
            linked = CancellationTokenSource.CreateLinkedTokenSource(token, cts.Token))
        {
            Action checkCancelled = () =>
            {
                if (requiresCurrentDirectory && !Path.GetDirectoryName(path).EqualsIgnoreCultureAndCase(IO.CurrentDirectory))
                    linked.Cancel();

                linked.Token.ThrowIfCancellationRequested();
            };

            await Tasks.Run(() =>
            {
                checkCancelled();
                var fileSystemInfo = IO.Exists(path);

                if (!fileSystemInfo.Item1)
                {
                    /* Neither a file nor a directory exists. This is possible if it was deleted after this 
                        * method was called but before we got here, and just means we have nothing to do here. */
                    linked.Cancel();
                    linked.Token.ThrowIfCancellationRequested();
                }

                var isDirectory = fileSystemInfo.Item2;
                var isFile = fileSystemInfo.Item3;

                var fileSystemType = isDirectory ? FileSystemType.Directory : FileSystemType.File;

                var isMedia = isFile && IO.IsMediaFile(path);
                var isImage = isFile && IO.IsImageFile(path);
                var isPng = isImage && IO.IsPng(path);
                var isZip = isFile && IO.IsZip(path);
                var isPsd = isFile && IO.IsPsdFile(path);
                var isTextFile = IO.IsTextFile(path);

                Bitmap cacheBitmap = null;
                Bitmap fullsizeImage = null;
                try
                {
                    // For simplicity, we define a small bitmap as one with file size less than 1MB.
                    var isBitmapGlyph = IO.IsBmp(path) && new FileInfo(path).Length < 1024L * 1024L;

                    /* Don't use the shell for icon images. It will
                        * display them with shadows and looks like shit. */
                    if (isFile && IO.IsIcon(path))
                    {
                        // Load the largest icon.
                        using (var iconImage = (new IconFileReader { Filename = path }.FirstIcon).ToBitmap())
                        {
                            if (iconImage == null)
                                throw new FileReadException(string.Format("Error reading '{0}'", path));

                            fullsizeImage = iconImage.Clone() as Bitmap;
                            isSmallImage = true;
                        }
                    }
                    else if (isPng || isBitmapGlyph || isPsd)
                    {
                        /* Also don't use the shell for png images, or gifs, for similar reasons as for icons. */
                        fullsizeImage = ImageFile.OpenBitmap(path);

                        if (isBitmapGlyph)
                            isSmallImage = true;

                        if (fullsizeImage == null)
                            throw new FileReadException(string.Format("Error reading '{0}'", path));
                    }
                    checkCancelled();

                    isSmallImage |= IO.IsGif(path);

                    if (fullsizeImage != null && (isSmallImage || isPng || isPsd))
                    {
                        /* If this is a small image, or if it is likely that conversion to jpeg will
                            * produce a thumbnail of inferior quality, we store the actual image in the
                            * cache, instead of a thumbnail.
                            *
                            * Also, the method to get the thumbnail from the shell below will lose the
                            * transparency for small png images, whereas this way, we will display them
                            * with transparency, even in the thumbnails. */
                        cacheBitmap = new Bitmap(fullsizeImage);

                        if (cacheBitmap.Width > 256 || cacheBitmap.Height > 256)
                            cacheBitmap = cacheBitmap.Resize(256, 256) as Bitmap;
                    }
                    else
                    {
                        cacheBitmap = !isZip ? ShellItemImageFactory.GetImage(path) : Icon.ExtractAssociatedIcon(path).ToBitmap();

                        if (cacheBitmap == null)
                            throw new FileReadException(string.Format("Error reading '{0}'", path));
                    }

                    checkCancelled();

                    if (cacheBitmap != null)
                        item = ThumbnailCache.AddNewCacheItem(path, cacheBitmap, fileSystemType, isSmallImage);
                }
                catch (Exception ex)
                {
                    /* An exception here is not necesarily an error. e.g. It will throw 
                        * if you deliberately delete images as they're being cached. */
                    ex.Log();
                    failed = tcs.TrySetException(ex);
                }
                finally
                {
                    if (fullsizeImage != null)
                        fullsizeImage.Dispose();
                }
                return Task.FromResult(item);
            }, token, TaskCreationOptions.LongRunning | TaskCreationOptions.PreferFairness).ConfigureAwait(false);

            /* The TaskCreationOptions are critically important here.
                * We do not want to be running on the main thread. */

            if (!failed)
                tcs.TrySetResult(item);
        }
    }
    catch (OperationCanceledException) { tcs.TrySetCanceled(); }

    // Prevent the UI from becoming unresponsive when adding many thumbnails.
    await tcs.Task.YieldTo(uiScheduler);

    return await tcs.Task;
}

That’s the code that adds a new thumbnail object to the thumbnail cache, which is a special kind of object cache where the objects are reused once the configurable size is exceeded, and is also persisted to disk, in my own bastardized binary format.

This code showed up in my search results because I was looking for all references to Tasks.Run, which is not standard code, but that calls my own TaskScheduler instead of the built in one.

And yet, this is good code. It’s not verbose, which is surprising. The code is easy to read and it calls out to loads of extension methods and other complex code. So depending on the file type that it finds, it might decide to cache the actual image directly for small files, use my custom icon reader that reads all icons from an ICO file directly, use my custom image reader that can read all kinds of image files, including PSD (Photoshop files), or invoke the Windows shell interfaces, in code that I also managed to figure out myself (because that shit is not implemented in the dot net Framework), which then uses different interfaces depending on the version of Windows. All in all, this is really good code… better than what I write at work nowadays.

I’m baffled.


Also, I found that the bug has nothing to do with my custom TaskScheduler, because it still happens after all references to it are removed. I’ve given up looking for the bug for now.

Found some source code I wrote while high that I don’t understand

I have a long and difficult post in mind… It’s been in the back of my head for over a week now and still not getting anywhere. I haven’t had time to write lately, but I did think this code I just found, which baffles me, might be worth sharing.

I’m doing something at work where I need to decrement a counter from multiple threads, and I knew I did something like this before, so I decided to search through my project of old code… Believe it or not, I wrote a lot of good code around 2011 to 2012, while I was very very high. I also wrote plenty bad code too, some of it bad because, well, it’s just fucking bad, some of it bad because it is so complicated that I can no longer understand it, although it works and does what it was designed to do, and some of it that leaves me wondering what the fuck I was thinking.

This is one of the latter examples… It wraps some Windows API code to suspend or resume the drawing of a window (I don’t remember why I would do this), and was written in such a way that this could be called from multiple threads… Enjoy.

Of interest here is the comment in the remarks section of the comment block describing the class:

Calls may be nested, but should not be made from any other than the GUI thread. (This code tries to work around such an error,  but is not guaranteed to succeed.)

Also, the way it works around the issue is, um… creative.
 

using System;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
using System.Windows.Forms;

namespace Romy.Controls
{
    /// <summary>Allows suspending and resuming redrawing a Windows Forms window via the <b>WM_SETREDRAW</b> 
    /// Windows message.</summary>
    /// <remarks>Usage: The window for which drawing will be suspended and resumed needs to instantiate this type, 
    /// passing a reference to itself to the constructor, then call either of the public methods. For each call to 
    /// <b>SuspendDrawing</b>, a corresponding <b>ResumeDrawing</b> call must be made. Calls may be nested, but
    /// should not be made from any other than the GUI thread. (This code tries to work around such an error, but 
    /// is not guaranteed to succeed.)</remarks>
    public class DrawingHelper
    {
        #region Fields

        private int suspendCounter;

        private const int WM_SETREDRAW = 11;

        private IWin32Window owner;

        private SynchronizationContext synchronizationContext = SynchronizationContext.Current;

        #endregion Fields

        #region Constructors

        public DrawingHelper(IWin32Window owner)
        {
            this.owner = owner;
        }

        #endregion Constructors

        #region Methods

        /// <summary>This overload allows you to specify whether the optimal flags for a container 
        /// or child control should be used. To specify custom flags, use the overload that accepts 
        /// a <see cref="Romy.Controls.RedrawWindowFlags"/> parameter.</summary>
        /// <param name="isContainer">When <b>true</b>, the optimal flags for redrawing a container 
        /// control are used; otherwise the optimal flags for a child control are used.</param>
        public void ResumeDrawing(bool isContainer = false)
        {
            ResumeDrawing(isContainer ? RedrawWindowFlags.Erase | RedrawWindowFlags.Frame | RedrawWindowFlags.Invalidate | RedrawWindowFlags.AllChildren :
                RedrawWindowFlags.NoErase | RedrawWindowFlags.Invalidate | RedrawWindowFlags.InternalPaint);
        }

        [CLSCompliant(false)]
        public void ResumeDrawing(RedrawWindowFlags flags)
        {
            Interlocked.Decrement(ref suspendCounter);

            if (suspendCounter == 0)
            {
                Action resume = new Action(() =>
                {
                    NativeMethods.SendMessage(owner.Handle, WM_SETREDRAW, new IntPtr(1), IntPtr.Zero);
                    NativeMethods.RedrawWindow(owner.Handle, IntPtr.Zero, IntPtr.Zero, flags);
                });
                try { resume(); }
                catch (InvalidOperationException)
                {
                    synchronizationContext.Post(s => ((Action)s)(), resume);
                }
            }
        }

        public void SuspendDrawing()
        {
            try
            {
                if (suspendCounter == 0)
                {
                    Action suspend = new Action(() => NativeMethods.SendMessage(owner.Handle, WM_SETREDRAW, IntPtr.Zero, IntPtr.Zero));
                    try { suspend(); }

                    catch (InvalidOperationException)
                    {
                        synchronizationContext.Post(s => ((Action)s)(), suspend);
                    }
                }
            }
            finally { Interlocked.Increment(ref suspendCounter); }
        }

        #endregion Methods

        #region NativeMethods

        [SuppressUnmanagedCodeSecurity]
        internal static class NativeMethods
        {
            [DllImport("user32.dll")]
            public static extern bool RedrawWindow(IntPtr hWnd, IntPtr lprcUpdate, IntPtr hrgnUpdate, RedrawWindowFlags flags);

            [DllImport("user32.dll")]
            public static extern IntPtr SendMessage(IntPtr hWnd, Int32 wMsg, IntPtr wParam, IntPtr lParam);
        }

        #endregion NativeMethods
    }

    #region RedrawWindowFlags

    [Flags(), CLSCompliant(false)]
    public enum RedrawWindowFlags : uint
    {
        ///<summary>Invalidates lprcUpdate or hrgnUpdate (only one may be non-NULL). 
        ///If both are NULL, the entire window is invalidated.</summary>
        Invalidate = 0x1,

        ///<summary>Causes a WM_PAINT message to be posted to the window regardless of 
        ///whether any portion of the window is invalid.</summary>
        InternalPaint = 0x2,

        ///<summary>Causes the window to receive a WM_ERASEBKGND message when the window 
        ///is repainted. The <b>Invalidate</b> flag must also be specified; otherwise, 
        ///<b>Erase</b> has no effect.</summary>
        Erase = 0x4,

        ///<summary>Validates lprcUpdate or hrgnUpdate (only one may be non-NULL). If both 
        ///are NULL, the entire window is validated. This flag does not affect internal 
        ///WM_PAINT messages.</summary>
        Validate = 0x8,

        ///<summary>Suppresses any pending internal WM_PAINT messages. This flag does not 
        ///affect WM_PAINT messages resulting from a non-NULL update area.</summary>
        NoInternalPaint = 0x10,

        ///<summary>Suppresses any pending WM_ERASEBKGND messages.</summary>
        NoErase = 0x20,

        ///<summary>Excludes child windows, if any, from the repainting operation.</summary>
        NoChildren = 0x40,

        ///<summary>Includes child windows, if any, in the repainting operation.</summary>
        AllChildren = 0x80,

        ///<summary>Causes the affected windows (as specified by the <b>AllChildren</b> and <b>NoChildren</b> flags) to 
        ///receive WM_NCPAINT, WM_ERASEBKGND, and WM_PAINT messages, if necessary, before the function returns.</summary>
        UpdateNow = 0x100,

        ///<summary>Causes the affected windows (as specified by the <b>AllChildren</b> and <b>NoChildren</b> flags) 
        ///to receive WM_NCPAINT and WM_ERASEBKGND messages, if necessary, before the function returns. 
        ///WM_PAINT messages are received at the ordinary time.</summary>
        EraseNow = 0x200,

        ///<summary>Causes any part of the nonclient area of the window that intersects the update region 
        ///to receive a WM_NCPAINT message. The <b>Invalidate</b> flag must also be specified; otherwise, 
        ///<b>Frame</b> has no effect. The WM_NCPAINT message is typically not sent during the execution of 
        ///RedrawWindow unless either <b>UpdateNow</b> or <b>EraseNow</b> is specified.</summary>
        Frame = 0x400,

        ///<summary>Suppresses any pending WM_NCPAINT messages. This flag must be used with <b>Validate</b> and 
        ///is typically used with <b>NoChildren</b>. <b>NoFrame</b> should be used with care, as it could cause parts 
        ///of a window to be painted improperly.</summary>
        NoFrame = 0x800
    }

    #endregion RedrawWindowFlags
}

An example of madness. Some c# code I wrote a few years ago when I was ridiculously high.

I’m not posting this to my programming blog because it’s an example of really really bad code.

It seems that one fine morning while tweaking on having my source code all be perfectly formatted, I created this monstrosity. It compiles to a console application that’s included in my solution, one that searches back a couple of directories and formats all the source code files that it finds according to my drug-induced maniacal specifications. That is, it modifies hundreds of my source code files in parallel in a few milliseconds. By some miracle it works. Had it failed, the results would have been spectacular.

(Here’s the kicker… It doesn’t really format anything. The tool I used for formatting code inserted blank lines and omitted blank lines where I wanted extra whitespace. So all this does is insert and remove empty lines. So it parses files and determines where to insert and where to delete lines. That’s why it had the potential, if my calculations while coding when I was super-high, of deleting source code and making the files useless. But somehow it worked as intended.)

I can’t even understand this code while I am clean and sober (and sane).

There are some ridiculously long logic statements in this code. Also check out my essay-style comments. As I recall, I was explaining the code to the voices in my head.

The main file:

using System;
using System.IO;
using System.Linq;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace FormatCSFiles
{
    /// <summary>Some quick 'n dirty CS code formatting.</summary>
    /// <remarks>Because the RegionErate Addin that I use to sort my code into regions does some screwy
    /// things with blank lines, and I am obsessively fussy about my code format. This processes all CS
    /// files in the solution in parallel and fixes what it can. This is not an extension. I don't know
    /// how to write one. This processes <b>files</b>, so save all before running this in the debugger,
    /// or wave your latest changes goodbye.</remarks>
    internal class Program : Romy.Core.Console.ConsoleApplicationBase
    {
        [STAThread, SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlAppDomain)]
        private static void Main()
        {
            var program = new Program();
            program.InitializeConsoleApplication();

            /* I'm being lazy and assuming this project is always in a child directory of my solution and processing the parent directory
             * (+ all the parent's siblings, as well as children, which includes this file). i.e. 4 levels up from the Debug directory. */
            var directory = Environment.GetCommandLineArgs()[0];

            for (var i = 0; i < 4; i++)
            {
                directory = Path.GetDirectoryName(directory);
            }

            LogInfo("FormatCSFiles\tProcessing the .CS files in \"{0}\" and its subdirectories.", directory);

            var files = Directory.GetFiles(directory, "*.cs", SearchOption.AllDirectories).Where(
                f => !Path.GetFileName(f).StartsWith("TemporaryGeneratedFile"));

            Parallel.ForEach(files, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount * 2 }, f => ProcessFile(directory, f));

            LogInfo("FormatCSFiles\tDone processing the .CS files in \"{0}\" and its subdirectories.", directory);
        }

        private static string Pad(string textToPad, int length)
        {
            var builder = new StringBuilder();
            builder.Append(textToPad);
            while (builder.Length < length)
            {
                builder.Append(' ');
            }
            return builder.ToString();
        }

        // My one and only failed attempt at reducing the code complexity made it even more complex.
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
        private static void ProcessFile(string directory, string filename)
        {
            try
            {
                var formattedThreadId = Thread.CurrentThread.ManagedThreadId.ToString().PadLeft(2, '0');
                var formattedFilename = filename.Substring(directory.Length + 1);
                LogInfo(Pad(string.Format("Thread {0}", formattedThreadId), "FormatCSFiles".Length) + string.Format("\tProcessing \"{0}\"", formattedFilename));

                var lines = File.ReadAllLines(filename, Encoding.Default).ToList();

                for (var i = lines.Count - 1; i >= 0; i--)
                {
                    var results = new AnalysisResults();
                    var line = lines[i].Trim();

                    if (i < lines.Count - 1)
                    {
                        var nextLine = lines[i + 1].Trim();
                        var lineIsEmpty = string.IsNullOrEmpty(line);
                        var nextLineIsEmpty = string.IsNullOrEmpty(nextLine);
                        var lineAfterNext = i < lines.Count - 2 ? lines[i + 2].Trim() : string.Empty;

                        results.RemoveNext = (!lineIsEmpty && line.StartsWith("[STAThread") && nextLineIsEmpty) || // Remove blank line below STAThread attribute.
                            // Remove a blank line between a property getter and setter.
                            (!lineIsEmpty && nextLineIsEmpty && line.StartsWith("get") && i < lines.Count + 2 && !string.IsNullOrEmpty(lineAfterNext) &&
                            (lineAfterNext.StartsWith("set") || lineAfterNext.StartsWith("private set") || lineAfterNext.StartsWith("protected set") ||
                            lineAfterNext.StartsWith("internal set") || lineAfterNext.StartsWith("public set"))) ||
                            (!lineIsEmpty && line.StartsWith("[") && nextLineIsEmpty && !string.IsNullOrEmpty(lineAfterNext)) ||
                            (!lineIsEmpty && line.StartsWith("{") && nextLineIsEmpty) ||
                            (!lineIsEmpty && line.StartsWith("[STAThread]") && nextLineIsEmpty);

                        if (!results.RemoveNext)
                        {
                            results.RemoveCurrent = (lineIsEmpty && nextLineIsEmpty) ||      // Remove extra blank line.
                                (i == 0 && lineIsEmpty) ||                                   // Remove empty first line.
                                (lineIsEmpty && !nextLineIsEmpty && nextLine.EndsWith("}")) || // Remove blank line before closing brace.
                                (lineIsEmpty && !nextLineIsEmpty && nextLine.StartsWith("static void Main("));

                            if (!results.RemoveCurrent)
                            {
                                results.InsertNext = (!lineIsEmpty && nextLine.StartsWith("static") && !nextLine.StartsWith("static void Main(") && nextLine.EndsWith("()")) || // Add a blank line before a static constructor.
                                    ((line.EndsWith("}") || line.EndsWith(";")) && nextLine.StartsWith("[")) || // Insert blank lines between consecutively declared structs. (Regionerate removed them.)
                                    (line.EndsWith(";") && (nextLine.StartsWith("public") || nextLine.StartsWith("private") ||
                                    nextLine.StartsWith("internal") || nextLine.StartsWith("protected") || nextLine.StartsWith("~"))) || // Insert blank lines between class-level fields.
                                    (!lineIsEmpty && line.StartsWith("#endregion") && !nextLineIsEmpty &&
                                    !nextLine.StartsWith("{") && !nextLine.StartsWith("}")) || // Insert a blank line between two subregions and anything else that doesn't start with an opening brace.
                                    (!lineIsEmpty && !nextLineIsEmpty && line.StartsWith("}") && (nextLine.StartsWith("#endregion") || nextLine.StartsWith("#endif"))) || // Insert a blank line between a closing brace and an #endregion or #endif.
                                    (!lineIsEmpty && line.StartsWith("#region") && !nextLineIsEmpty && nextLine.StartsWith("[")) || // Insert a blank line between an #endregion and an attribute.
                                    (!lineIsEmpty && (line.StartsWith("#region") || line.StartsWith("#if")) && !nextLineIsEmpty) || // Add blank line after #region or #pragma or #if.
                                    (!nextLine.StartsWith("private set") &&
                                    line.EndsWith("}") && !line.StartsWith("///") &&
                                    (nextLine.StartsWith("public") || nextLine.StartsWith("internal") || nextLine.StartsWith("private") ||
                                    nextLine.StartsWith("protected") || nextLine.StartsWith("///") || nextLine.StartsWith("async"))) || // Insert a line between a closing brace and a method declaration.
                                    (!lineIsEmpty && !nextLineIsEmpty && nextLine.Length > 1 && line.Length > 2 &&
                                    line.Contains('{') && line.EndsWith("}") && !line.StartsWith("get {") && !line.StartsWith("catch") &&
                                    !line.StartsWith("try") && !line.StartsWith("finally")) ||                                         // Insert a blank line between properties declared in an interface.
                                    (!lineIsEmpty && line.Length > 1 && !line.StartsWith("///") && (nextLine.StartsWith("///") || nextLine.StartsWith("/*"))) || // Insert a blank line between a field and method declaration.
                                    (!lineIsEmpty && !nextLineIsEmpty && line.StartsWith("using") && nextLine.StartsWith("namespace")) || // Add a blank line between a using clause and namespace name
                                    (!lineIsEmpty && !nextLineIsEmpty && line.StartsWith("private") && nextLine.StartsWith("#endregion") ||
                                    !lineIsEmpty && !nextLineIsEmpty && nextLine.StartsWith("#endregion"));

                                if (!results.InsertNext)
                                {
                                    if (!lineIsEmpty && line.EndsWith("</summary>") && !nextLineIsEmpty && nextLine.EndsWith(";") && !nextLine.StartsWith("event") && !string.IsNullOrEmpty(lines[i + 2].Trim()))
                                    {
                                        /* If a field declaration has a summary XML comment, add a blank
                                         * line after it as well. It makes the code easier to follow. */
                                        results.InsertAfterNext = true;
                                    }
                                    else if (!lineIsEmpty && line.EndsWith("{") && !nextLineIsEmpty && nextLine.Equals("}"))
                                    {
                                        // I hate javascript style braces. Just because.
                                        lines[i] += nextLine;

                                        results.RemoveNext = true;
                                    }
                                }
                            }
                        }

                        if (results.RemoveCurrent)
                            lines.RemoveAt(i);
                        else if (results.RemoveNext)
                            lines.RemoveAt(i + 1);
                        else if (results.InsertNext)
                            lines.Insert(i + 1, string.Empty);
                        else if (results.InsertAfterNext)
                            lines.Insert(i + 2, string.Empty);
                    }
                }

                /* It seems that using any encoding other than Encoding.UTF8, including my failed attempts
                 * to detect it, end up encoding the text in such a way that the hidden unicode characters
                 * that Regionerate uses in its region names, get scrambled. */
                File.WriteAllLines(filename, lines, Encoding.UTF8);
                LogInfo(Pad(string.Format("Thread {0}", formattedThreadId), "FormatCSFiles".Length) + string.Format("\tSaved \"{0}\"", formattedFilename));
            }
            catch (Exception ex) { LogError(ex); }
        }

        private class AnalysisResults
        {
            public bool InsertAfterNext { get; set; }

            public bool InsertNext { get; set; }

            public bool RemoveCurrent { get; set; }

            public bool RemoveNext { get; set; }
        }
    }
}

And my base console application class that it derived from (which isn’t too bad).

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;

namespace Romy.Core.Console
{
    /// <summary>A base console type that enables some logging methods. Logs
    /// via TraceListener, to both the console and a file.</summary><remarks>
    /// See Zipper\Program.cs or FormatCSFiles\Program.cs for examples.</remarks>
    public class ConsoleApplicationBase
    {
        private string logFilename;

        /// <summary>Delete the file or directory specified,
        /// without throwing an exception on failure.</summary>
        public static bool DeleteFileSystemObject(string path)
        {
            try
            {
                /* File.Exists seems to return true for directories,
                 * so always check with Directory.Exists first... */
                if (Directory.Exists(path))
                {
                    var info = new DirectoryInfo(path);

                    // If path == current directory, change the current directory.
                    if (string.Compare(Directory.GetCurrentDirectory(), path, StringComparison.InvariantCultureIgnoreCase) == 0 && Directory.Exists(Path.GetDirectoryName(path)))
                        Directory.SetCurrentDirectory(Path.GetDirectoryName(path));

                    // Try to silently delete readonly/hidden directories.
                    if ((info.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly || (info.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
                        info.Attributes = FileAttributes.Directory & FileAttributes.Archive;

                    Directory.Delete(path, true);
                }
                else if (File.Exists(path))
                {
                    // Try to silently delete readonly/hidden files.
                    if ((File.GetAttributes(path) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly || (File.GetAttributes(path) & FileAttributes.Hidden) == FileAttributes.Hidden)
                        File.SetAttributes(path, FileAttributes.Normal);

                    File.Delete(path);
                }
                return true;
            }
            catch (IOException) { }
            catch (UnauthorizedAccessException) { }
            catch (Exception ex) { LogError(ex); }
            return false;
        }

        public static void LogError(Exception ex)
        {
            LogInfo("Error: {0}", ex.Message);
        }

        public static void LogError(string message)
        {
            LogInfo(message);
        }

        public static void LogInfo(IEnumerable<string> lines)
        {
            foreach (var line in lines)
            {
                Trace.WriteLine(line);
            }
        }

        public static void LogInfo(string format, params object[] args)
        {
            var formattedDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ff\t");
            Trace.WriteLine(formattedDate + (args.Length > 0 ? string.Format(format, args) : format));
        }

        /// <summary>This must be the first method called from Main,
        /// to be able to use the logging helper methods.</summary>
        public void InitializeConsoleApplication()
        {
            /* I prefer removing the parameters from Main and using this technique. It is always
             * consistent; the path to this exe is the first argument, and subsequent arguments
             * were passed by the user. */
            var args = Environment.GetCommandLineArgs();

            logFilename = Path.ChangeExtension(args[0], ".log");

            InitializeTraceListeners(logFilename);
        }

        private static void InitializeTraceListeners(string logFilename)
        {
            DeleteFileSystemObject(logFilename);

            Trace.Listeners.Clear();

            TextWriterTraceListener logFileTraceListener = new TextWriterTraceListener(logFilename);
            logFileTraceListener.Name = "FileLogger";

            ConsoleTraceListener consoleTraceListener = new ConsoleTraceListener(false);
            consoleTraceListener.Name = "ConsoleLogger";

            Trace.Listeners.Add(logFileTraceListener);
            Trace.Listeners.Add(consoleTraceListener);
            Trace.AutoFlush = true;
        }
    }
}