Microsoft Windows and all that goes with it

How to Initialize Disk

Illustration

When new EMPTY disk is added to Windows first thing that needs to be done is initialization. Only after this step Windows will recognize disk as their own and allow you to create partitions.

Part of (bigger) script was automatic disk initialization. Surfing Internet yielded just few results for this particular problem. Most of them were using DISKPART and this was not acceptable. I needed something in Win32 API.

Theory is simple enough. Single function that does it all is DeviceIoControl. Unfortunately this function is ridiculously overloaded. Little bit of investigation will bring us to IOCTL_DISK_CREATE_DISK control code which does disk initialization. Even better - almost all parameters can be ignored or set to default.

Only parameter that we must understand is CREATE_DISK structure so it is only appropriate to have it use unions. As you might know, there is no meaningful support for unions in C#. There is a way around it with FieldOffset(0) but it does not look nice.

Rest of code is fairly straightforward. To call it just use DiskIO.InitializeDisk("\\.\PHYSICALDRIVE4") (substitute number for whichever drive you wish to initialize).

Full code follows:

internal static class DiskIO {

    public static void InitializeDisk(string path) {
        var signature = new byte[4];
        RandomNumberGenerator.Create().GetBytes(signature); //lazy way to generate "unique" signature

        using (SafeFileHandle handle = NativeMethods.CreateFile(path, NativeMethods.GENERIC_READ | NativeMethods.GENERIC_WRITE, 0, IntPtr.Zero, NativeMethods.OPEN_EXISTING, 0, IntPtr.Zero)) {
            if (handle.IsInvalid) { throw new Win32Exception(); }

            var cd = new NativeMethods.CREATE_DISK();
            cd.PartitionStyle = NativeMethods.PARTITION_STYLE.PARTITION_STYLE_MBR;
            cd.MbrGpt.Mbr.Signature = BitConverter.ToInt32(signature, 0);
            Int32 bytesOut = 0;
            if (NativeMethods.DeviceIoControl(handle, NativeMethods.IOCTL_DISK_CREATE_DISK, ref cd, Marshal.SizeOf(cd), IntPtr.Zero, 0, ref bytesOut, IntPtr.Zero) == false) { throw new Win32Exception(); }
        }
    }


    private static class NativeMethods {

        public const int GENERIC_READ = -2147483648;
        public const int GENERIC_WRITE = 1073741824;
        public const int OPEN_EXISTING = 3;

        public const int IOCTL_DISK_CREATE_DISK = 0x7C058;


        public enum PARTITION_STYLE {
            PARTITION_STYLE_MBR = 0,
            PARTITION_STYLE_GPT = 1,
            PARTITION_STYLE_RAW = 2,
        }


        [StructLayoutAttribute(LayoutKind.Sequential)]
        public struct CREATE_DISK {
            public PARTITION_STYLE PartitionStyle;
            public CREATE_DISK_UNION_MBR_GPT MbrGpt;
        }

        [StructLayoutAttribute(LayoutKind.Explicit)]
        public struct CREATE_DISK_UNION_MBR_GPT {
            [FieldOffset(0)]
            public CREATE_DISK_MBR Mbr;
            [FieldOffset(0)]
            public CREATE_DISK_GPT Gpt;
        }


        [StructLayoutAttribute(LayoutKind.Sequential)]
        public struct CREATE_DISK_MBR {
            public Int32 Signature;
        }

        [StructLayoutAttribute(LayoutKind.Sequential)]
        public struct CREATE_DISK_GPT {
            public Guid DiskId;
            public Int32 MaxPartitionCount;
        }


        [DllImportAttribute("kernel32.dll", EntryPoint = "CreateFileW", SetLastError = true)]
        public static extern SafeFileHandle CreateFile([MarshalAsAttribute(UnmanagedType.LPWStr)] string lpFileName, Int32 dwDesiredAccess, Int32 dwShareMode, IntPtr lpSecurityAttributes, Int32 dwCreationDisposition, Int32 dwFlagsAndAttributes, IntPtr hTemplateFile);

        [DllImportAttribute("kernel32.dll", EntryPoint = "DeviceIoControl", SetLastError = true)]
        [return: MarshalAsAttribute(UnmanagedType.Bool)]
        public static extern Boolean DeviceIoControl(SafeFileHandle hDevice, Int32 dwIoControlCode, ref CREATE_DISK lpInBuffer, int nInBufferSize, IntPtr lpOutBuffer, Int32 nOutBufferSize, ref Int32 lpBytesReturned, IntPtr lpOverlapped);

    }

}

Update Kills VHD Boot (Temporarily)

Some windows update that got installed on my VHD-based Windows in week from 2011-06-12 to 2011-06-19 killed possibility to boot from them. Instead of normal startup procedure I was greeted with Repair Windows.

Fortunately I had another Windows installation on same machine so I was able to check boot parameters:

bcdedit

 Windows Boot Manager
 --------------------
 identifier              {bootmgr}
 device                  partition=D:
 description             Windows Boot Manager
 locale                  en-US
 inherit                 {globalsettings}
 default                 {current}
 resumeobject            {fa179570-87b4-11e0-b0a7-da74dade416b}
 displayorder            {current}
                         {fa179565-87b4-11e0-b0a7-da74dade416b}
 toolsdisplayorder       {memdiag}
 timeout                 1

 Windows Boot Loader
 -------------------
 identifier              {current}
 device                  partition=C:
 path                    \Windows\system32\winload.exe
 description             Windows 7 (x64)
 locale                  en-US
 inherit                 {bootloadersettings}
 recoverysequence        {fa179566-87b4-11e0-b0a7-da74dade416b}
 recoveryenabled         Yes
 osdevice                partition=C:
 systemroot              \Windows
 resumeobject            {fa179564-87b4-11e0-b0a7-da74dade416b}
 nx                      OptIn

 Windows Boot Loader
 -------------------
 identifier              {aa179565-87b4-11e0-b0a7-da74dade416b}
 device                  partition=E:
 path                    \Windows\system32\winload.exe
 description             My VHD installation
 locale                  en-US
 inherit                 {bootloadersettings}
 recoverysequence        {fa179572-87b4-11e0-b0a7-da74dade416b}
 recoveryenabled         Yes
 osdevice                partition=E:
 systemroot              \Windows
 resumeobject            {fa179570-87b4-11e0-b0a7-da74dade416b}
 nx                      OptIn

There was my problem - somehow update has changed VHD boot device to nonexistent partition E:.

Solution lies in two commands:

bcdedit /set "{aa179565-87b4-11e0-b0a7-da74dade416b}" device "vhd=[C:]\VHDs\Windows7.vhd"
 The operation completed successfully.

bcdedit /set "{aa179565-87b4-11e0-b0a7-da74dade416b}" osdevice "vhd=[C:]\VHDs\Windows7.vhd"
 The operation completed successfully.

P.S. My best is that one of following updates is the killer:

Thanks Microsoft

Illustration

I reinstalled my machine and I had to install some of my tools. To keep things simple, I just went to download them from my own site. I was somewhat surprised at a warning: “vhdattach201.exe is not commonly downloaded and it could harm your computer”. I made this program but now even I wasn’t sure whether something has gone wrong.

So I checked everything. And yes, there is nothing wrong with my programs. It is just that some fool in Microsoft decided that what we need is another warning.

I cannot even start to comprehend what this will solve. If utility with couple of thousand downloads triggers this behavior so will lot of other people’s programs. Users will see this warning couple time through day. And they will ignore it. What IE 9 brought us is just another dialog that we will not read.

Connecting Windows 7 to Old Samba Software

Illustration

I got myself one simple (maybe too simple) NAS: IcyBox’s NAS902. It’s purpose was mostly just handling backups so lack of features didn’t bother me.

What did bother me was accessing this box from Windows 7. When I used NAS’ guest account only, everything was fine. When I added new SMB account with my user name and password I could not access it anymore. To make long story short, issue here was in ancient version of SMB server inside NAS902. It supported only NTLMv1 as authentication protocol. Windows 7 do not use that protocol (and for a good reason) by default. My computer and my NAS just weren’t speaking same language.

Solution was simple enough. First I had to start “Local Security Policy” (in Windows 7 it is as easy as writing exactly that in search box). From there I had to go to “Local Policies” and then “Security Options”. From list of policies I found “Network security: LAN Manager authentication level”. Changing setting to “Send LM & NTLM responses” solved issue.

P.S. Yes, I know, this lowered security in my network considerably. I need to find another NAS as a long-term solution.

Installing Fresh Windows 7 on Mirrored Volume

Illustration

I am fan of software mirroring in Windows 7. Yes, I know, hardware RAID is better, faster, more reliable etc. However, it has one big disadvantage. It is notoriously difficult beast to find. All those RAID controllers integrated on motherboards are usually just software RAID with some hardware support. And their drivers are notoriously bad.

Usually we first install Windows 7 on standard MBR partition. Only after setup is done we can convert disk to dynamic one. After that mirror can be added. Well there is a little bit better way of doing things.

First you need to go into dark dungeons of command line interface. Just boot Windows setup as usually and press Shift+F10 on first screen. This will just open command prompt in which you just write “DISKPART”. That utility will be your host for the day.

Now you need to create some dynamic disks. CLEAN command is there to ensure that you start with blank drives and same procedure needs to be done for both disks. If you are not certain which disks are in computer, you might want to execute “LIST DISK” first - just to get numbers right:

SELECT DISK 0
 Disk 0 is now the selected disk.

CLEAN
 DiskPart succeeded in cleaning the disk.

CONVERT DYNAMIC
 DiskPart successfully converted the selected disk to dynamic format.

SELECT DISK 1
 Disk 1 is now the selected disk.

CLEAN
 DiskPart succeeded in cleaning the disk.

 CONVERT DYNAMIC
DiskPart successfully converted the selected disk to dynamic format.

After this you’ve got two dynamic drives that need to go into some form of RAID. I opted here for RAID 1 (mirroring) but you could also select RAID 0, RAID 5 and a simple volume:

CREATE VOLUME MIRROR DISK=0,1
 DiskPart successfully created the volume.

Volume isn’t worth anything without it being formatted. Next step is just that. Do notice that I call this volume by number 1. On my system volume 0 is CD-ROM and newly created volume got next number. If your system has additional disks (or preexisting volumes), you can check which volume you need with “LIST VOLUME” command:

SELECT VOLUME 1
 Volume 1 is the selected volume.

FORMAT QUICK
   100 percent completed
 DiskPart successfully formatted the volume.

In order to boot from this volume you need to give it a partition:

RETAIN
 The selected volume now has a partition associated with it.

Of course, given partition needs to be activated. Here you will start counting from number 2 since partition 1 is reserved for “system stuff”. If you are not sure, quick check with “LIST PARTITION” is recommended:

SELECT DISK 1
 Disk 0 is now the selected disk.

SELECT PARTITION 2
 Partition 2 is now the selected partition.

ACTIVE
 DiskPart marked the current partition as active.

SELECT DISK 0
 Disk 0 is now the selected disk.

SELECT PARTITION 2
 Partition 2 is now the selected partition.

ACTIVE
 DiskPart marked the current partition as active.

With this done you can type exit twice (once to exit DISKPART and once to exit command prompt) and do installation as you normally would. Only other thing worth mentioning might be slight confusion regarding two separate drives where you can install Windows. Everything will work no matter which disk you select there.

And this was all. As soon as installation is done your mirror will be ready.

P.S. Although I talk about Windows 7 whole post, same procedure will also work on Windows Server 2008 R2. It might even work on earlier Windows versions - I haven’t tried it.

5Nine

Illustration

I was happy like a little puppy when I read that there is graphical manager for Hyper-V Server running on server itself. For me that was single missing link in my Hyper-V adventures.

First step was to download their free version. As it became usual, I had to create yet another another account and leave my password at yet another site. Well, at least I will get download link after installation and that will be that.

And that was that. Sometime I overreact. :)

Well, it turns out that this is not all. All that you get in mail is link to god-knows-what executable file. I guess after running that download manager you will be presented with additional application that would let you download what you want in just three-four simple steps. And let’s hope that this company is legit and that you don’t download some “toolbar helper” application alongside.

Illustration

I don’t know about you but I am pretty allergic to this way of treating your potential customers. While I do understand their “need” to collect e-mail addresses of their potential customers so they can (annoy them) better help them in future, I do not understand why they don’t let you download their FREE application without any additional garbage. Which idiot of a manager thought that this was good idea?

I shall just wait for some normal company to come with same solution.

Running PowerShell

I mostly use PowerShell for my scripting needs. However, I am so used to old command prompt that I type cmd.exe without thinking. So, instead of changing my habits, I have .bat file for each PowerShell script:

powershell script.ps1 %*

First and second parameter determine what to run and third parameter forwards all command line arguments to script.

Are You Sure?

Illustration

Like a true member of “old guard” I occasionally touch hosts file in order to do custom redirects. On Windows 7 it is annoying experience to edit this file. First you need to open it directly in program since it doesn’t have proper extension. After short edit you need to save it and, of course, it is protected file. So you need to open another instance of notepad, this time with administrative privileges…

Few weeks after you change this you might get dialog informing you of virus. True, it doesn’t say virus as such but it does look threatening. Warning message even has virus-like name. Only after careful reading it is obvious that two added lines caused this mess:

127.0.0.1	www.google-analytics.com
127.0.0.1	ssl.google-analytics.com

Security essentials detected this as a thread and, if you use default disinfect command, it will restore order to your hosts file - by deleting one of those items. Redirecting www.google-analytics.com is a big threat but ssl.google-analytics.com is fair game…

Solution is simple, just select allow option and everything is good once more. At least for a month or so. Then, out of a blue, Security Essentials might warn you about something you did before and you already forgot all about it.

Microsoft Mathematics

Illustration

Last few years I hold position of self-proclaimed Microsoft expert. I am so used to people approaching me with various questions regarding Microsoft technology and products and people got used to me having an answer to anything Microsoft. I thought that I knew every Microsoft product there is. However, I had no idea about Microsoft Mathematics. Product has been available from 2006 and I got first whim of it just few hours ago.

Simplest description of it would be graphing calculator (like e.g. HP 49g) but it wouldn’t do justice to it since it only holds until you switch it to “Ink” input mode.

Ink mode is something wet dreams are made of. Not only that it recognizes letters but it also knows how to interpret fractions, exponents, greekish :) symbols and all other “math thingies”. I got so used to write one thing on computer and completely another on paper that I am now freaking at something that should be normal thing - properly formated equations. While Ink mode works with mouse, with tablet computer it is pure math porn.

And it doesn’t stop there. It also offers equation solving, bunch of common formulas with nice interface to enter all data, and very pretty graph controls. Everything is packed in simple and skinnable interface (albeit without Hello Kitty skin ;)). As long as you are not doing math for living, this program probably has everything you need.

I am not in my student days anymore so there is very little chance that I will use this program much. There is very limited need for math in business software. But this program made my eyes shine.

Download is available FOR FREE.