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

Failing with software and how it can be fun. March 24, 2009

Posted by gcorbin in Commentary.
Tags: ,
2 comments

Several months ago I had the experience of pitching the design for an elegant marketing web site to a group of old school farmers. The need for such a tool was advertised in my local town newspaper. The group of local farmers coordinates a local farmers market that runs from spring to fall every year. They were given a small grant from the state government to help improve the farmers market. So, I decided to give it a shot. My first instincts were to determine what the requirements of the web site were to be. I emailed the individual that posted the need for the web site, looking for a meeting to discuss requirements. I was told all the information that I needed was posted in the request for the web site. See the notice below:

 

 

Carver Reporter –

 

Thanks to the Massachusetts Department of Agriculture, the town of Carver was awarded a grant of $4,000 to help promote the Farmers’ Market through an official Web site and accompanying brochures.

 

With the recent economic crisis in the state, further grant monies may not be available for upcoming seasons, and thus the Carver Agricultural Commission (AgCom) is looking to utilize this grant to the fullest extent. The grant monies must be used within a certain timeframe or they will be lost.

 

The grant parameters are specific in that $2,000 is allocated for Web site development and $2,000 for the brochure. The AgCom is looking for help from the community. Residents who have experience and creativity in either or both of these areas are encouraged to apply to the AgCom with design ideas and proposals.

 

“The Farmers’ Market has become a key economic and social component of the town. The brochure will help the town advertise next year’s market and may help with fundraising, getting new venders, etcetera,” Director of Planning and Community Development Jack Hunter said. “The Web page will allow online updates and interactive approaches to the market for next year, as well.”

 

Hunter said customers could access online farmers’ market coupons through the site, as well as notify them of upcoming specials and events such as the pony rides, hay rides or the Fall Harvest Festival. Web access has proven to be a valuable marketing tool for communities that have farmers’ markets.

 

AgCom members felt that keeping the work local for a local community market was important and hope to receive interest in developing the tools from several Carver residents.

 

The deadline for both proposals is Monday, Nov. 10. Interviews will be scheduled for the Nov. 17 AgCom meeting in Meeting Room 4 at the town hall.

  

Wow, not really much to go on. I pulled the following points from the notice:

 

Functional Requirements

 

1. “The Web page will allow online updates and interactive approaches to the market for next year, as well.”

 

2. Customers could access online farmers’ market coupons through the site

 

3. Notify users of upcoming specials and events such as the pony rides, hayrides or the Fall Harvest Festival.

 

Non-Functional Requirements

 

1. The web site should prove to be a valuable marketing tool for communities that have farmers’ markets.

  

My next step was to research other sites that were designed with farmers in mind. After I spent a few days researching this, I felt I was ready to draft a proposal. In my proposal, I outline the details on how the site could be laid out, what functionality it could provide, how people would find the site, how it would be maintained and updated, what technologies would be used and what documentation I would provide. The full proposal can be found here. Any way, I felt that I’d covered everything needed. The last step was just to pitch my proposal and hope for the best. I had no idea what other professionals would be applying for the same project so I did my best to cover everything I could.

 

The day of the proposal came. I was asked to give my pitch in front of about 16 local farmers and others at the town hall. All was going well, until I started with my written proposal. It was then that I discovered that no one in that room had ever seen my proposal. I was thinking how could this be, I emailed it to the head of the market and asked him to forward it to all that would be interested. I later found that he never forwarded it because none of the local farmers in that room had regularly used email accounts. They all had ones that were setup by the town for them, but it was very unlikely that any of them knew how to check it. It was Ok, I had printed out several copies before the meeting and I could just hand them out. So, I continued to give pitch my proposal and I spoke about all the items in it and covered everything I could think of. I was extra careful to make sure I used as many laymen terms as possible, keeping my audience in mind. So after speaking for about 30 minutes, I final started to get some feedback in the form of questions. First question was what is a URL? Ok I said to myself, these are farmers and I missed that one, I should have used the term web site address. As more and more questions came in, It quickly became obvious that most of these farmers had no idea about what it took to build a web site never mind the reason it would take 2 months to do it. After all, its just words on computer screen, what’s the big deal?

 

Any way, once my painful proposal was complete, I was asked to sit in a waiting room while they listen to other proposals, just incase questions about my proposal came up. I learnt that there was only one other proposal they had to review. After that was complete we were both thanked for spending the time and sent on our way. Later I came to learn that the second candidate was an active member within the community and was well known and liked by all the local farmers. I should have guessed based on all the laughter I heard while waiting for the second proposal to complete. In any case, I never heard back from the committee. I did email them as a follow up, but still have yet to hear anything. So, whether I lost the project due to small town politics or failing to convey a technical topic to lay people, I’ll never know. After this experience, I can’t help to remember that old saying “It’s not what you know, it’s who you know!” In any case, I view it as a very positive experience. It helped me grow as a professional and learn some painful lessons of politics at very little cost.

 

In case you were wondering, the web site that was proposed still has not been built. Last I heard, they decided to scrap the project and go with printing flyers instead. I guess we can add this one to that list of 95% of all projects that fail.

 

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.

 

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.

How to deal with “Pointy Hair Managers”…. November 30, 2008

Posted by gcorbin in Commentary.
Tags:
add a comment

It’s the same old question that you hear time after time, why should we buy a control package when we have many capable developers on staff? It’s a question that is often posed by inexperienced management trying to save a few bucks. For such management, it’s often a rhetorical question because what they are really trying to say is “no, it’s a waste of money!” As all us software engineers know, in reality buying control packs will save lots of money in the long run. So, the issue becomes how do you deal with such management? Unfortunately, there is no simple answer. I’ve found in my experience that demonstrating the savings by comparing the time needed for you to build a control vs. the cost of the control is often not enough to convince anyone. Only after you’ve done the coding, support, documentation, and enhancements that these managers see the light. Sometime, no matter how much you debate something, some people will not budge. Whether is sheer stubbornness or just plain stupidity it does not matter. This question really boils down to the age old question of “how do you give someone wisdom without them having to gained it through experience?” So my advice when dealing with “pointy haired managers” is to just run! If you have the patience to help them understand, then that’s great. It may benefit you in the long run, but most likely it will just ware you down.

At the end of the day, just remember that they are the ones signing your paycheck. If that’s no longer enough of a reason to smile and just get along with them, then its time for a new job.

 

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.

The advent of Silverlight 2.0 July 30, 2008

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

The time has finally come. Now a client-side framework that gives .NET developers the same power and flexibility as Flash has finally arrived. Silverlight 1.0 has introduced this technology to us, but it still required the developer to work with javascript and forced us to remain bound to its limitations. Silverlight 2.0 applications can be entirely written in any of the managed languages. Programming with Javascript is not needed. The framework will handle it for you. The client-side output for Silverlight is all based on the <Object> tag. This means that the source for the client application can appear to be as simple as an HTML file that has nothing but a reference to Silverlight and an <Object> tag. The way this works is that Silverlight 2.0 has introduced a new file type. This is called a ZAP (XAP) file. The zap file is nothing but a zip file with a different name. If you rename it zip, it will open with winzip and all the binary files will be presented. The binary files that are packaged in the zap file are a subset of the WPF framework and whatever assembly that you create for you Silverlight app. The feature set that is available to Silverlight 2.0 is amazing. Any type of Flash application can be built with Silverlight just as well. Goto http://silverlight.net and see all the samples, you’ll be amazed.

Tools on top of Tools…. June 30, 2008

Posted by gcorbin in Uncategorized.
Tags:
add a comment

It’s funny how we all invent various tools to simplify life, only to find that learning to manage and use a new tool only complicates things. I’ve recently spent a bit of time creating a new tool. The purpose of this tool is to simplify the task of tracking time and entering it into yet another tool. Throughout the design and coding of this tool, I found that its almost impossible to create a tool that will make everyone happy. I guess the lesson learned is that sometimes its just better to deal with tool(evil) that you know then to deal with the tool(evil) that you dont.

Going into the (Silver)Light. April 29, 2008

Posted by gcorbin in ASP.NET, Silverlight.
Tags: , ,
4 comments

By now everyone has seen Microsoft’s latest web technology, Silverlight. If you haven’t you got to go check it out. Many blogs I’ve seen have compared it to Macromedia Flash. But, I’ve got to tell you that it differences are just as great as its similarities to Flash. I’ve done work in Flash in the past and it is a great technology. But, Silverlight is in position to become new technology to dominate the client-side browser. There are a few reasons for this.

 

First, the learning curve for Silverlight is much lower for developers that already understand how to use the .Net Framework. Even thou Silverlight 1.0 only supports javascript , the XAML syntax is exactly the same as if you were creating a desktop WPF application. Once Silverlight 2.0 is out, the learning curve will be even less as that version will support managed C#.

 

Second, the IDE for creating Silverlight applications is Visual Studio. This is the same development tool that many developers use for building other windows applications.

 

Third, the event model in Silverlight is the same as ASP.NET. Flash uses an event model that is based on a storyboard that repeats on a specified interval. Silverlight has the typical OnLoad, OnClick, etc. In addition, Silverlight does have a storyboard control that you can use if you need the events to all fire as in Flash.

 

After doing a fare amount of research into Silverlight 1.0, I decided it give it a try. I wanted to see how well, if at all, it could integrate with my existing ASP.NET site. I found that it ties in very easily. For ease of use, I created an ASP.NET Server control that embeds all the client-side JS files and XAML files needed for my Silverlight application. Then all that I needed to do was to drop that server control on my ASP.NET page and set a few parameters.

 

My Silverlight app is very simple. I decided to make use of the WPF Ink class to create a Silverlight Signature Control. You can check it a live demo and find the source code for it here. One of the nice things about this control is that is demonstrates several things. With this sample you can see to following:

 

  • Creating an ASP.Net Server control
  • Working with embedded JavaScript resources
  • Embedding XAML for use with Silverlight.
  • Creating a Silverlight application

 

Enjoy.

Totally free asp.net web site in just 3 weeks March 31, 2008

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

For the past 12 years I’ve been working as a software engineer, mostly building software for web applications. I’ve had many people over the years ask me “What is the URL for my personal site?”. Unfortunately, my response was always the same. “I don’t have a personal site”. It did make me think, how can I claim to be a decent software engineer and not have a web site of my own. So, my project over the last month was to build myself a personal web site. I started by thinking about what type of content, layout, and features I’d like to have. After I make that list, I started looking into designing a site map and flows for my features. Not too long after this did I realize that this was going to take me a bit of time. Then I discovered the Microsoft web site starter kits. I spent some time looking through the various templates until I finally found on that kind of fit what I wanted. So, I took the “Personal Site Starter Kit” as my base for my new site. I spent a few weeks modifying it to fit my needs and then added all the content. That’s it. There you have it. A fully functional completed web site in 3 weeks.

The next step was that I needed to host this site somewhere. So, the answer was to take an old desktop that I was no longer using and to install IIS and Visual Studio Express. This would be the system that would host my site. Since I only have Windows XP Professional and SQL Server Express running there, that means that the site will be limited to only 10 concurrent connections, but that’s fine its just a personal site and not a e-commerce system.

Now comes the issue of how to get it available on the Internet. The first this that I needed to do was to expose my web server outside of my firewall. There are a few ways to do this. You can move the entire server out site by placing it in the DMZ or open a port to the application that needs access through the firewall or you can do some port forwarding and filters on the firewall. I decided to just open port 80 through the firewall so that IIS can communicate with the world. This exposes the bare minimum needed, but it does have some limitations, but for my needs its fine. Another issue that we need to fix is with the DHCP server. We should only be opening port 80 to the web server. To do this, our web server is going to need to have a static IP address within the LAN. Changing this on my internal LAN is simple, the real problem here is with the external ISP. We could call them and ask to have a static IP on the WAN, but that would cost a lot extra. Fortunately, we can install a piece of freeware called No-IP that will solve this problem for us. This freeware runs as a service on the web server and keeps an eye on the servers IP address. When the ISP DNS server changes it, this software will update the domain name for our site with the new IP that our ISP assigned. Now were ready for Internet traffic.

Now comes the last piece. What name do I give this site? If I want to choose my own domain name, that will cost a bit to register it. However, there is a free solution to that also. There is a free site that allows you to create an account that will redirect all Internet traffic to your site. You get to choose the host name and you can choose from a list of domain names that they own. This site also integrates with the freeware that update the domain name for us when the ISP changes our IP.  So, for this last step, just create an account with no-ip.com and pick a host and domain name. That it!

So, you too can build a site free fully featured asp.net site in just 3 weeks.  Enjoy.

Links for this entry:

http://corbin.bounceme.net    (My personal site)

http://www.no-ip.com  (Freeware and domain account site)