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 = 0×80000000;

        const uint FILE_ALL_ACCESS = 0×80000000;

        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.

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.

 

Windows Workflow Foundation (WF) and you… October 28, 2008

Posted by gcorbin in .NET.
Tags: , ,
2 comments

I’ve recently spent some time playing around with Windows Workflow Foundation (WF). I wanted to see why all these magazines are praising it as a great new technology, after all workflow based technologies have been around for many decades now. It didn’t take to long for me to realize how cool WF really is. For beginners it has two workflow models that can be used. The first is the “Sequential Workflow” and the second is called the “State machine workflow”. Both of these models allow you to use the same set of tools to create them. The big difference when trying to determine which to use needs to be based on your line of business. One of the big deciding factors that I’ve found is based on the amount of time needed for the workflow to process. If the process is going to be a quick inline sequential thought, then “Sequential Workflow” is what you want. If the time to process the workflow is going to involve state changes and possibly long running decision points, then “state machine workflow” is for you.

 

In any case, when digging into workflow it exciting to notice the many tasks and controls that is available to developers. The greatest assets that I’ve found with this are the tools that Microsoft gives developers for creating and maintaining workflows. These tools are far better than anything else I’ve seen.

 

If you haven’t check into WF yet, I strongly recommend it. The best place I’ve found for a good intro to it is the DNR TV series on WF. It’s very helpful and informative.

 

You can find that at http://www.dnrtv.com

Look in the archives section.

 

Enjoy.

Follow

Get every new post delivered to your Inbox.