Schultz's profileSchultzpacePhotosBlogNetwork Tools Help
    May 02

    Tower of Hanoi in C#

    using System;

    using System.Collections.Generic;

    using System.Text;

     

    namespace Hanoi

    {

        class Program

        {

            static void Main(string[] args)

            {

                int count = 3;

                if (args.Length != 0 && !Int32.TryParse(args[0], out count))

                {

                    count = 3;

                }

     

                for (int i = 0; i < 3; i++)

                {

                    pinsAndDisks[i] = new Stack<int>();

                }

     

                for (int i = 0; i < count; i++)

                {

                    pinsAndDisks[0].Push(count - i);

                }

     

                Hanoi(0, 2, 1, count);

     

                Console.WriteLine("Total number of calls: {0}.", depth);

            }

     

     

            static int depth;

            static Stack<int>[] pinsAndDisks = new Stack<int>[3];

     

            static void Hanoi(int source, int dest, int misc, int count)

            {

                depth++;

     

                if (count == 1)

                {

                    MoveAndPrint(source, dest);

                }

                else

                {

                    Hanoi(source, misc, dest, count - 1);

                    MoveAndPrint(source, dest);

                    Hanoi(misc, dest, source, count - 1);

                }

            }

     

            static void MoveAndPrint(int source, int dest)

            {

                int disk = pinsAndDisks[source].Pop();

                pinsAndDisks[dest].Push(disk);

                for (int pin = 0; pin < 3; pin++)

                {

                    if (pinsAndDisks[pin].Count == 0)

                    {

                        Console.WriteLine("|-----");

                    }

                    else

                    {

                        string pinView = "";

                        Stack<int>.Enumerator e = pinsAndDisks[pin].GetEnumerator();

                        while (e.MoveNext())

                        {

                            pinView = e.Current + "-" + pinView;

                        }

                        Console.WriteLine("|-" + pinView);

                    }

                }

                Console.WriteLine();

            }

        }

    }

     

    September 20

    Iniana state PI redifinition: "Establishing scientific truth by legislative fiat."

    "The Indiana Pi Bill is the popular name for bill #246 of the 1897 sitting of the Indiana General Assembly, which is one of the most famous historical attempts to establish scientific truth by legislative fiat. Despite its popular name, the main result claimed by the bill is a method to square the circle, rather than the establishment of the value of π. Nevertheless, the bill does contain text which appears to dictate varying wrong values of π such as 3.2. Note that the impossibility of squaring the circle (using only compass and straightedge), suspected since ancient times, was first rigorously proved in 1882 by von Lindemann, and better approximations of π have been known since ancient times."
     
    September 11

    Michael Schumacher - the end of an era... Sad.

    After 90 wins, 1354 points and seven world championship titles, Michael Schumacher has announced he will retire at the end of this season. Statistically the greatest driver the sport has ever seen, Schumacher has, over the past 16 years, set a new standard to which younger drivers can only aspire. He may have courted controversy at times, but with his departure, the sport will lose one of its leading lights.
     
    July 17

    Using CoInitializeEx

    Not really obvious but if you included all headers and still are getting a compiler error
    'CoInitializeEx': identifier not found
    then it means you simply need to define _WIN32_DCOM.
    June 27

    MBM5 - Hardware Monitor

    http://mbm.livewiredev.com/ Great stuff... if needed :)

    FREE Antivirus. avast! 4 Home Edition. Stop the crap!

    http://www.avast.com/eng/avast_4_home.html 

     

    "avast! 4 Home Edition is a full-featured antivirus package designed exclusively for home users and non-commercial use. Both of these conditions should be met! Our company offers the Home Edition free of charge, since, in our opinion, it is possible to avoid global virus spreading by efficient prevention; however, many user are not able to or do not want to pay for antivirus software. This page will show you the most important features of this program."

    April 17

    Windows Live Messenger and Live.com

    I guess it better to move my Law somewhere below. It is so difficult to delete it comletely because it is so true :)
     
    I love instant messenging. I dont know why someone should use something else my Windows Live Messenger. It is very very very nice. You should try it and tell your friend how good it is. Seriously. Yes, I admit I dont know much about other IM clients but whatever I saw doesn't seem to be even close.
     
     
    If you dont have access, just give me your Microsoft Passport and I will send you an invite.
     
    In fact all http://www.live.com products deserve attention. Check them here http://ideas.live.com. If you install Windows Search Bar and Favorites Add-on, you may have all your favorite links the same on every computer that has it installed as well. It is very convinient! I use it at work and at home.
    ---
     
    Для малообразованных . Я не знаю, почему люди продолжают пользоваться чем-то кроме Мессенжера для общения в Интернете. Мне он очень нравится, и я настоятельно рекоммендую его всем. Попробуйте и расскажите своим друзьям, насколько он замечателен! Я, конечно, не очень много знаю о других клиентах, но то, что я знаю, позволяет мне думать, что Мессенжер - лучший. Его можно скачать здесь:
     
     
    Если доступа нет, добавте комментарий с Вашим Майкрософт паспортом, и я вышлю Вам приглашение.
     
    Вообще, все, что находится на http://www.live.com заслушивает внимания. Поисковый тулбар для Интернет Эксплорера и Фавориты к нему - просто замечательные вещи. Все любимые ссылки всегда одинаковые на всех компьютерах, где установлены эти две утилиты!
     
    Пишите, если есть вопросы! С радостью отрекламирую
     
    March 20

    The IDCRL and RPS encryption/decryption with a session key.

    The technologies enabling Passport from Microsoft are cool but difficult to use at the moment due to the lack of documentation. Recently I went thru the testing of encryption/decryption mechanism. It is rather streightforward but has a couple not obvious things. Both IDCRL and RPS use safe arrays as an output whereas it seems to be BSTR. This means that in the managed world if you need to convert the output byte array represented as a IntPtr to a string you have to know how to do that (e.g. thru marshaling) and in native world use SafeArray* methods and VARIANTs which is also not trivial for those who is not familiar with COM.
     
    I will be glad to answer questions.
    February 28

    Calling managed DLL from native code (DLL to TLB to TLH)

    The idea is basically to use COM based access.

    1. Create your DLL and add a GUID to each interface and clasess you want to be publicly seen thru COM. You may use any tool to generate valid GUIDs (e.g. uuidgen.exe by Microsoft).
    2. Sign your DLL with a stong name
    3. Register your DLL in the GAC
      gacutil /i <MyManagedDll.dll>
    4. Generate COM type library
      REGASM <MyManagedDll.dll> /tlb:<MyManagedDll>.tlb
    5. Create a CPP file and include just one line
      #import "<MyManagedDll>.tlb" named_guids raw_interfaces_only
      It will generate a <MyManagedDll>.tlh file in your project debug directory.

    Done.

     

    To call your methods, something like below must be used:

    CoInitialize(NULL);

    MyManagedNamespace::IMyManagedInterface myManagedInterface;

    HRESULT hRes = myManagedInterface.CreateInstance(MyManagedNamespace::CLSID_MyManagedClass);

    if (SUCCEEDED(hRes))
    {
        myManagedInterface->SomePublicMethod();
    }

    CoUninitialize ();

     

    Take care

    October 18

    Whidbey: code snippets

    New Visual Studio is very cool. It has bunch of new small but extremely helpful twists. One of them is code snippets. What is it? It is a frequently used piece of code that can be inserted wherever the source code. Below is the one that can be used to create a file header. Save it to the file FileHeader.snippet, drop it in "My Documents\Visual Studio 2005\Code Snippets\Visual C#\My Code Snippets" and then start typing FileHeader at the top of the file. Very neat!
     
    <CodeSnippets
        xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
        <CodeSnippet Format="1.0.0">
            <Header>
                <Title>
                    File Header
                </Title>
                <Shortcut>FileHeader</Shortcut>
            </Header>
            <Snippet>
       <Declarations>
        <Literal>
         <ID>FileName</ID>
         <ToolTip>Replace with name of the file.</ToolTip>
         <Default>FileName</Default>
        </Literal>
        <Literal>
         <ID>email</ID>
         <ToolTip>Replace with your email.</ToolTip>
         <Default>schultz__@hotmail.com</Default>
        </Literal>
        <Literal>
         <ID>Description</ID>
         <ToolTip>Replace with the description of the content of this file.</ToolTip>
         <Default></Default>
        </Literal>
        <Literal>
         <ID>date</ID>
         <ToolTip>Current date.</ToolTip>
         <Default>MM/DD/YYYY</Default>
        </Literal>
       </Declarations>
                <Code Language="CSharp">
                    <![CDATA[
    //---------------------------------------------------------------------
    //
    // File: $FileName$
    //
    // Description:
    // $description$
    //         
    //
    //
    //
    // History:
    // $date$ $email$       Created
    // 
    //  
    //
    // Freeware. 
    //---------------------------------------------------------------------
    ]]>
                </Code>
            </Snippet>
        </CodeSnippet>
    </CodeSnippets>

     
    September 29

    Migrating to .NET Framework 2.0

    We all wll have to migrate to .NET Framework 2.0 eventually. Yesterday  was the day for me. I made several interesting observations:
    1. If you don't go beyond .NET Framework classes, you may have have almost no problems at all. All you have to do is to disable several warning about obsolite classes. However some of them are actually worth taking care of, e.g. if you worked with FxCop before, you might have added parameterless catch to handle non-CLR exceptions; in this case the compiler warns that they have been wrapped to a CLR one.
    2. If you sign your assembly with a strong name using the AssemblyKeyFile attribute in the Assembly.cs, then you will have to remove it and use the project file instead. This creates problems when the projects in build from the command line. However it is an easy solvable issue. You may either follow the warning instructions or... disable the warning again :) I haven't tried the latter option though.