jump to navigation

Having fun with Pinvoke April 30, 2009

Posted by gcorbin in .NET, C#.
Tags: ,
add a comment

The .Net libraries have many built-in objects that can be used to create most types of programs for windows. In most cases, the typical developer would not need anything more. However, there are a few cases in which a direct call to a COM object is needed. The ability to call objects that are not .Net from within .Net is called Interoperability. InterOp calls are often used in cases where a .Net program needs to communicate with older software that is based on COM. It can also be used to make direct calls to the windows Kernel. In these cases, a common term among .Net developers is the Pinvoke. Using a Pinvoke is very similar to calling a Windows API from VB6. You need to copy the declaration and import the library and then you can use it. The compiler sees code that uses Pinvoke as being unsafe code. This means that you will need to set the project properties for your code to allow compile unsafe code. The declarations and constants used for these calls can all be found at http://www.pinvoke.net/. Some sample .Net code that uses a Pinvoke can be seen below. This code is using the Windows Kernel to create a file.

 

using System;

using System.Collections.Generic;

using System.Text;

 

namespace CreateFilewithPinInvoke

{

    class FileReader

    {

        const uint GENERIC_READ = 0x80000000;

        const uint FILE_ALL_ACCESS = 0x80000000;

        const uint OPEN_EXISTING = 3;

        const uint OPEN_ALWAYS = 3;

        System.IntPtr handle;

 

        [System.Runtime.InteropServices.DllImport(“kernel32”, SetLastError = true)]

        static extern unsafe System.IntPtr CreateFile

        (

            string FileName,          // file name

            uint DesiredAccess,       // access mode

            uint ShareMode,           // share mode

            uint SecurityAttributes,  // Security Attributes

            uint CreationDisposition, // how to create

            uint FlagsAndAttributes,  // file attributes

            int hTemplateFile         // handle to template file

        );

 

        [System.Runtime.InteropServices.DllImport(“kernel32”, SetLastError = true)]

        static extern unsafe bool CloseHandle

        (

            System.IntPtr hObject // handle to object

        );

 

        public bool Open(string FileName)

        {

            // open the existing file for reading      

            handle = CreateFile(FileName,FILE_ALL_ACCESS,0,0, OPEN_ALWAYS,0,0);

 

            if (handle != System.IntPtr.Zero)

                return true;

            else

                return false;

        }

 

        public bool Close()

        {

            return CloseHandle(handle);

        }

    }

 

    class Program

    {

        static int Main(string[] args)

        {

            if (args.Length != 1)

            {

                System.Console.WriteLine(“Usage : CreateFile.exe <FileName>”);

                return 1;

            }

  

            FileReader fr = new FileReader();

 

            if (fr.Open(args[0]))

            {

                System.Console.WriteLine(“Created requested file”);

                return 0;

            }

            else

            {

                System.Console.WriteLine(“Failed to create file!”);

                return 1;

            }

        }

    }

}

-Enjoy.

Advertisements

Data binding with generic dictionary objects January 30, 2009

Posted by gcorbin in .NET, ASP.NET, C#.
Tags: , ,
2 comments

This issue caused me some pain recently. So, after I spent some time to figure out how to do this, I figured it would be good to share it with the community. The problem is that I had to created my own class called Item. This class was meant to contain all properties and methods on an Item object. I then wanted to have a collection of Item objects, so I created a generic dictionary that contained the Item object as the Kvalue for the generic dictionary. The problem comes when you try to databind this collection to a control.

 

Many of the WinForm controls only support databinding to an IList. To make the generic dictionary work here, we need to use the BindingSource Object (BindingSource implements IList). The next trick is that the DisplayMember needs to be set to a string “Value” and the ValueMember set to a string “Key”. However, “Value” will attempt to display the Item object as a string, so to get around this, we need to override the ToString method of the Item object to display the property of that class. It’s easiest to understand this by seeing a sample.

 

 

private void Form1_Load(object sender, EventArgs e)

{

  //Create a Generic Dictionary.

  Dictionary<int,Item> Items = new Dictionary<int,Item>();

 

  //Load the dictionary

  Items.Add(1, new Item(“FirstItem”, 1));

  Items.Add(2, new Item(“SecondItem”, 2));

  Items.Add(3, new Item(“ThirdItem”, 3));

  Items.Add(4, new Item(“FourthItem”, 4));

 

  //Bind the generic dictionary

  comboBox1.DataSource = new BindingSource(Items, null);

 

  //For this to work, the Item.cs class needs to

  //override the ToString() method.

  comboBox1.DisplayMember = “Value”;

  comboBox1.ValueMember = “Key”;

} 

 

 

class Item

    {

        private string _itemName;

        private int _itemId;

 

        //constructor

        public Item(string strItemName, int itemId)

        {

            this._itemName = strItemName;

            this._itemId = itemId;

        }

 

        public string ItemName

        {

            get{ return _itemName; }

        }

 

 

        public int ItemId

        {

            get{ return _itemId; }

        }

 

        //Override ToString to the itemName property.

        public override string ToString()

        {

            return _itemName;

        }

    }

 

 

 

The compelte source code for this demo can be downloaded here.

 

Enjoy.

 

The Monty Hall Paradox December 19, 2008

Posted by gcorbin in C#, Commentary.
Tags:
add a comment

Every now and then, I find myself missing the simplistic days of higher education. I miss the enjoyment of studying computational theory and all those fun brainteaser puzzles that such topics often bring to light. Recently, while reading one of my favorite blogs (blog.stackoverflow.com), I can across a posting / podcast that had references to a few such puzzles.  Some of these puzzles I’ve already heard of, but there was one that I’ve never come across. It s called “The Monty Hall Paradox”.

 

The puzzle is about an old game show where the host (Monty Hall), would give contestants a choice of 3 doors. One of the doors would have a new car and the other 2 would have a goat. The contestant would choose 1 door, then Monty would open 1 of the other 2 remaining door revealing a 1 of the goats. He would then give the contestant the option to keep their selected door or switch doors. So the question is would it be best to keep your original door or switch doors?

 

So, my first answer to this is that it doesn’t matter. 2 doors remaining should be a 50/50 chance. This is what most people give for an answer to this puzzle also. However, after studying it further it became apparent that the answer was not this simple. Several other people are posting the true answer is that its better to switch doors. The odds of getting the car by switch doors are 66%. So, instead of just reading more and more on the topic, I decide to write a simple program that I could use to test this out.

 

I wrote the code in .NET (of course). It’s a small program 30 lines or less. I ran the code over 1 million iterations and to my surprise, the odds were 66.34% of getting car if the program swaps doors at the end.

 

Check out the code. Check out addition puzzles and feel free to share.

 

Find more on the monty hall puzzle here.

Enjoy.

The joys of video editing (WPF Intro) February 29, 2008

Posted by gcorbin in C#.
Tags: ,
3 comments

One of my favorite past times that I enjoy the most is video editing. It’s been a long time hobby of mine. There are many different software packages out there that have tons of functionality that can make even an amateur appear like a pro. Recently, I’ve discovered windows media encoder. It’s a nice package that Microsoft gives away for free. For free, it does a decent job of editing, although many of the paid for packages are by far much better. One task that I found it can do that the other packages don’t is that is can do real-time screen video and audio captures. I’ve never played around with this stuff too much before, so I figured I’d research it a bit. I found that there is again other packages out there that do real-time screen capture, but the free ones had poor quality and generated large files. The paid for packages have great quality and decent file sizes, but they are also quite costly.

Any way, I figured I’d give the Microsoft media encoder a try. I’ve always wanted to try to create an online tutorial for some of the new and cool technologies out there, so I spent a bit of time creating a “Beginning WPF” tutorial. It’s only about 8 minutes long, but I think it gives a nice simple introduction to WPF and shows some of its power. So, if you’re up to learning a bit about WPF you can start the video by clicking the link below.

Beginning WPF” – by Greg Corbin (best viewed at 1024×768)

Enjoy. J

MMC 3.0 – Build Snap-ins with C# and.Net September 23, 2007

Posted by gcorbin in C#.
Tags: , , ,
2 comments

Microsoft Management Console no longer belongs in the realm of C++ developers only. Microsoft has released a new version of the popular MMC framework. This version fully supports managed and unmanaged code. The new MMC 3.0 SDK finally gives .NET developers the ability to create snap-ins. In prior versions of MMC, we were able to use some of the .NET framework, but all that code needed to be embedded into a C++ framework that provided a sort of communication bridge between MMC and .NET. With that architecture there was plenty of cases where .NET coding was limited in what could be done. The way it worked was the C++ snap-in hosted the .NET program in an ActiveX container. This is would cause all the .NET code to be in a sort of island that could not easily communicate with the outside MMC framework. All that is now behind us. Now that we have an MMC framework that is fully .NET compliant, we can ditch all the old C++ hacks in favor for the simplicity and power of C#.

To get started with writing snap-ins using C#, you will need 2 items. First you will need the MMC 3.0 console. Next you will need the .NET 3.0 framework. If you are working on windows Vista, you will already have these. The operating systems supported by this are Windows XP, Windows 2003, and Windows Vista. If you want your snap-in to work on anything older than that, then you’re out of luck. Once you get these pieces installed, I would recommend visiting the MSDN. There are several good samples that show how to write snap-ins using C#. There are samples that are as simple as a “Hello World” and there are some that are as complex as some of the Microsoft snap-ins.

Regardless to how you choose to use this, it is a great new technology that I would recommend you add to you portfolio. One last side note that I discovered is that this framework is even flexible enough to allow us to scrap winforms and use all the cool animation that WPF gives us. This is a great framework for creating any desktop administrative tool.

Let’s Start Simple January 11, 2007

Posted by gcorbin in C#.
add a comment

Before we talk about asp.net and all its cool features, we need to understand a little bit about the programming languages that can be used. The two languages that Microsoft provides are C# and VB.net. Either language will work just fine, but my preference is C#. So, all the sample code that I provide will be written with C#.

Ok, let’s get started. In this posting I wanted to start simple by just discussing the C# language and some of its uses. The best way to do this is with an example. The example below shows deals with creating some objects and defining them. I decided to use racecars as my example objects. Take a look at the code below for further details.

 This sample was created using VS2003, but will work in VS2005. For the purpose of creating a simple sample I choose to make it a console application, but the code will work very much the same if it were called from an asp.net page.

Listing 1

blog2a.JPG

The source code for this can be downloaded here. This sample shows a simple Class called FordRaceCar. This Class has many properties and methods that can be called and set. A FordRaceCar Object is created and set in Main( ) method of the RaceTrack Class.

This Main( ) method is the entry point for the application. Its equivlant to PageLoad( ) in asp.net

The main problem with this code is what if we wanted to create a ChevyRaceCar? We could take all the code for the FordRaceCar Class copy it, and call it ChevyRaceCar Class. The problem here is we would now have a lot of duplicated code. This would lead to poorly maintainable code.

A better solution is to use Inheritance. We would create one base class that has all the methods and properties that would apply to RaceCars in general, and then we could inherit this base class into our specific FordRaceCar and ChevyRaceCar Class. This would avoid the duplicate code. We are also going to have an interface to define our base RaceCar class. The Interface is nothing more than a contract that says what a base RaceCar must have. In this case, the only property being enforced here is “Tires”. This means that a base RaceCar must have code to define the car tires. The interface does not contain any implemented code, only the contract. All the source code below can be downloaded here.

 blog1b.JPG

 blog1c.JPG

Listing 6

 Listing 5