Posts

C# format date times for different locals (localization and globalization), DateTimeFormatInfo

Image
Working on a project recently I found we were presenting date/time data to a variety of users in various countries. Each country uses it's own date/time formatting. Here in the US it's often MM/dd/yyyy, however in Europe it's often dd/MM/yyyy and in Asia they don't even have the slashes they use special characters that designate year, month, and day. At first we were going to come up with localized versions of all the possible date/time combinations you can display (June 6th, 1977, 6/25/77, etc) but Microsoft has an even better solution already in place. static void Main( string[] args ) { DateTime dt = DateTime.Now; // let's create some different date times for different cultures // JAPANESE CultureInfo culture = new CultureInfo("ja-JP"); DateTimeFormatInfo formatInfo = culture.DateTimeFormat; String time = dt.ToString( formatInfo.FullDateTimePattern, culture ); MessageBox.Show( time );...

Using more complicated PInvoke calls

In my last blog post I covered using a very basic PInvoke call to an unmanaged dll that returned an integer. For basic data types int, char, double, float, etc you don't need to do any manual marshaling. However, especially with the Win32 API you will find yourself needing to use more complicated types. Even getting a string back from an unmanaged dll takes more work, and then we have classes, structs, arrays, etc we need to deal with. Let's look at some unmanaged dll signatures extern "C" { struct { char* NAME, char* ADDRESS, int age } PERSON; void FillByteArray( unsigned char* byteArray, int arrayLength ); const char* GetLastErrorMessage(); void FillAStruct( PERSON* pPerson ); } Now here we have three functions; one fills a byte array, one returns a string, and another modifies a struct we've defined. Nothing complicated on the C++ side but we need to be careful when we start using pinvoke to call these functions...

C# using PInvoke to call an unmanaged DLL

Recently I've found myself having to do some pinvoking with .net. Microsoft offers an excellent primer on the subject. http://msdn.microsoft.com/en-us/library/aa288468(v=vs.71).aspx For it's many great benefits the .net framework doesn't do everything. You will find yourself having to invoke a win32 API function call at some point in your career. I'm going to offer some quick and dirty samples on getting data back and forth using the platform invoke. First you cannot invoke any classes using pinvoke. You get 1 function call at a time. If you want classes you will need to write a custom CLI/C++ wrapper. But that goes beyond the scope of this post. First let's look at the unmanaged\win32 side of things. Let's say you have a dll called MyDll.dll. In this dll you have a bunch of functions. // this lets use export functions from the dll #define DllExport __declspec( dllexport ) // first we use extern "C" so we don't get name mang...

C# More on threading, killing a thread, waiting for, or how to do a Thread.Join

Image
In my last post I used a ThreadPool to do some work. ThreadPools are great and I use them a lot. However many times I find myself really only needing 1 thread and I need to have some control over it. I may need to wait for it to finish, or more importantly I need to be able to control when it dies or completes its task. For this case I always use Thread.Join As usual please peruse the MSDN documentation . Thread.Join waits for the thread to complete before proceeding with any other operations. So simply creating a thread then calling Thread.Join can be useful in some UI operations I tend to not call Join until I'm ready to kill the thread entirely. The MSDN link above goes over the great details. Now let's go over some quick code. This example creates a thread then waits for the user to press a key and terminates the thread. Let's look at the main console code using System; using System.Collections.Generic; using System.Text; using System.Threading; namesp...

Threading in C# using the ThreadPool

Image
Threading is one of those topics that creates a lot of discussion in programming. Threading in C# is quite easy. However using it correctly, especially when you start doing data access or sharing information across threads it becomes difficult to keep everything in sync. For this example I'm going to focus on creating some basic threads that run and do some basic output to show we have concurrent threads running. You could create a thread and start it, then join, etc. I prefer to let .net handle the thread creation and use the ThreadPool to do all the thread management for us. You can read more about the ThreadPool here: MSDN Site I normally don't post entire files but this post is a bit different. Let's start with the program that is running the threads. We create 20 threads and pass them an index and a ManualResetEvent. This is so we know which thread is exiting and we need to keep track of when the thread is done processing. If we don't care about when...

C# Lock, Sleep, and Hibernate Windows

This could be a very uncommon occurrence but you might find a need in C# to set the computers sleep or hibernate state. You might even need to lock the entire pc. .NET has two of the needs built in, the third you will need to do some pinvoking. // set the computer to hibernate bool retVal = Application.SetSuspendState( PowerState.Hibernate, false, false ); if( retVal == false ) { MessageBox.Show( "Unable to hibernate the system." ); } // set the computer to suspended bool retVal = Application.SetSuspendState( PowerState.Suspend, false, false ); if( retVal == false ) { MessageBox.Show( "Unable to suspend the system." ); } // lock the workstation // we need to import from user32.dll, the LockWorkStation function [DllImport("user32.dll", SetLastError = true)] static extern bool LockWorkStation(); bool result = LockWorkStation(); if (result == false) { // TODO: an error occured } The Application.SetSuspendState is the big ...

MFC get your external ip address

I recently wrote a program in MFC that would monitor your ip address.  This was great but I soon realized if your behind a NAT of some kind you get your internal ip address.  I soon realized a need to know my external ip address.  There is no built in functionality to do this in windows so you have to ping an outside server or website that will tell you what your ip address is.  There are several ways to do this sockets, an http request, or urlmon.  Many people say sockets is the best since you can use any version of windows and create a socket.  The issue is the socket code is extremely long and complicated.  I only need to support windows 2000 and above so I decided using the urlmon way was much simpler and faster.  Here is some code in MFC to hit an outside website which returns your IP address in file that you then parse for the data. This is in a class with a CString member variable called m_strExternalIp. m_strExte...