Showing posts from 2011

C# convert string array to integer (or something other kind of data type) array

Many times in coding you are dealing with transforming data from one type to another.  I often find myself creating integers, longs, etc from strings.  Especially in .net for some reason.  I got tired of writing tons of code to handle this.  .Net gives you a great way to convert an array from one type to another. Currently I would always end up writing a for loop iterating through the array and doing a manual copy.  It would look something like this: string[] someStringValues; int[] someIntValues = new int[someStringValues.Length]; for( int i = 0; i < someStringValues.Length; i++ ) {    someIntValues[i] = int.Parse( someIntValues[i] ); } Not horrible code, but there is a more succinct way of doing it! string[] someStringValues; int[] someIntValues = Array.ConvertAll<string, int>( someStringValues, int.Parse ); We have now moved all that code into 1 line.  With some more magic we can also move this into a generic templated solution and you could theoretically change

C# Simple Binary Tree

Today I'm getting a bit into data structures. Recently I've found a need to store a large amount of records (16 million) in memory as a sort of cache. I tried using databases, etc, but it was all too slow. I needed super fast access times, well under a millisecond to speed up a large application with many data look ups. I tried a linked list but while the insert times were great the look ups again were too slow. I finally settled on a binary tree. Building the tree is slow, several minutes, but this data doesn't change and gives me super fast look up times, around .005 ms. To achieve this I wrote a very simple binary tree class. It uses a node that is fit for my purposes. To make this class even better I would implement in generics with a node class that has to implement IComparable. This way you can make a binary tree for any type of class that can be compared. For now I'm hard coding the key/values for my specific needs. See the rather large code block bel

C# create a new process

Once in a while I find myself needing to spawn a process in C#.  The .net framework has some built in functionality to do this.  It's fairly trivial to just spawn a process and let it run.  .NET however allows us many options to customize the look and feel as well as the error output of the spawned process.  The example below simply fires up notepad with a default document.  You can customize this heavily as mentioned and not show windows, etc. You can read all about is on MSDN . // create and setup the process object chartProcess = new Process(); chartProcess.StartInfo.FileName = "notepad.exe"; // this is all optional setup // pass in any command line arguments if desired chartProcess.StartInfo.Arguments = "test.txt"; // chartProcess.StartInfo.UseShellExecute = false; // this determines if we show the actual command or form window chartProcess.StartInfo.CreateNoWindow = false; // this lets us handle an event when the process we start stops chartProcess

C# Parallel.For

With the advent of C# 4.0 you can now write code to more efficiently use multiple core machines. I will show a trivial example on how to do this. This code reads through a directory and lists all the files. Now while the example itself isn't that complicated I will show some timings and benefits on my Intel duo core 2 machine. Running on even more cores would show an even bigger result. This kind of computing really shines when you're dealing with large amounts of data or very intensive computations. This test sums up 10 million random integers. using System.Threading.Tasks; static void Main( string[] args ) { int[] values = new int[10000000]; Random r = new Random( DateTime.Now.Millisecond ); double sum = 0; for( int i = 0; i < values.Length; i++ ) { values[i] = r.Next( 0, 10 ); } DateTime start = DateTime.Now; DateTime end; // run the test in parallel Parallel.For( 0,

C# create MD5 hash from a string

A common task when dealing with sensitive data is to create a hash of it. MD5 is used quite often especially when dealing with password, etc. I will leave the discussion of collisions, etc to others and just show a function that will return an array of bytes that is the result of hashing the input string. This function calls for an Encoding object to be passed in since you never know what encoding you will be using. But you could easily hard code the encoding if you know that will never change. using System.Security.Cryptography; /// <summary> /// Hashes the string. /// </summary> /// <param name="valueToHash">The value to hash.</param> /// <param name="textEncoding">The text encoding.</param> /// <returns></returns> private byte[] HashString( String valueToHash, Encoding textEncoding ) { byte[] result; using( MD5 md5 = MD5.Create() ) { byte[] inputBytes = textEncoding.GetBytes( val

C# get the number of days in a month

Ok this isn't the longest blog post, but it contains a handy little code snippet. Sometimes you find yourself needing to know the number of days in any given month. The code below will get you the last day of the month. I'm using the current month but you could use any month. You just need to know the month and year you're looking for. The magic lies in the DateTime.DaysInMonth method. You pass in the year and month and it returns the number of days in that month. The code below is pretty self explanatory. static void Main( string[] args ) { DateTime now = DateTime.Now; int daysInMonth = DateTime.DaysInMonth( now.Year, now.Month ); String dateFormat = String.Format( "Last day of the month is - {0}/{1}/{2}", now.Month, daysInMonth, now.Year); Console.WriteLine( dateFormat); Console.ReadKey(); } And a brief picture showing the output, obviously I ran this is October 2011.

C# Get the ip address of a host name

Often times you want to find the ip address of a host name. This function will do this for you. It returns the first address. using System.Net; public string GetIPAddress(string sHostName) { IPHostEntry ipEntry = Dns.GetHostByName(sHostName); IPAddress [] addr = ipEntry.AddressList; string sIPAddress = addr[0].ToString(); return sIPAddress; }

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

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. 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

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

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_strExternalIp = _T( "Unavailable" ); try {

Using google maps API for driving directions

This is a bit different than my usual blog postings but I think it will help a lot of people.  I recently have found a need to generate a Google Map with driving directions based on some customer input.  After a few hours looking over some javascript API's I found a very simple solution on itself.  There are a few different versions of the API and this solution uses version 2.0.  I believe the current version is 3.0.  I have no clue when if ever they will deprecate the API but it could happen.  They also state if you call this service more than 2,500 times a day you will get banned so don't abuse the service.  My use is light at best maybe once or twice a day.  I have found it to be fairly fast and light weight. UPDATE!! Looks like Google wants you to have a key to use the maps. You will need to signup for a key here: It takes a few seconds and you will need to add the key to the query string used. Now onto the

C# using a transaction with ODBC

Let's say your writing some data to the database and you need to make it transactional.  You know where you need to rollback multiple statements or use multiple statements in one go.  Normally you would do this in the database itself.  But I have found a few times where you have to do this in .net.  My latest was using mySQL to get the new index after I did an insert.  I found the SQL to do so would work fine in a mySQL command prompt or in the phpMyAdmin SQL pane but their .net ODBC driver simply wouldn't allow it.  Epic .net fail mySQL I guess your love for PHP has clouded your vision.  So you end up needing to wrap up multiple SQL calls in a transaction to accomplish this.  I have also had to do this it SQLSERVER but not on a scale like this.  But regardless this is how you can use a .net transaction with multiple SQL statements. You need to create an OdbcConnection.  Then an OdbcCommand and OdbcTransaction.  Set the command and transactions connection to the connection op

C# Anti Aliasing when drawing

In a previous post I talked about how to set anti-aliasing on text in C#. Now you may find yourself needing to set anti aliasing when drawing shapes. This is very easy to do using the GDI+ graphics object. The trick is to use the SmoothingMode and PixelOffsetMode . Now some quick code protected override void OnPaint( PaintEventArgs e ) { e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; e.Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; e.Graphics.DrawEllipse( new Pen( new SolidBrush( Color.Red ), 1.0f ), new Rectangle( 5, 5, 200, 200 ) ); e.Graphics.SmoothingMode = SmoothingMode.HighQuality; e.Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; e.Graphics.DrawEllipse( new Pen( new SolidBrush( Color.Red ), 1.0f ), new Rectangle( 210, 5, 200, 200 ) ); e.Graphics.SmoothingMode = SmoothingMode.HighSpeed; e.Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; e.Graphics.DrawEllipse( new Pen( new SolidBrush( Color.Red ),

Antialiasing Text with C#

Lately I have found myself having to use anti-aliasing in a lot of our rendering code to improve the output look our images.  To help others here is a snippet of code to anti alias text. protected override void OnPaint( PaintEventArgs e ) {     base.OnPaint( e );     Font font = new Font( "Tahoma", 12.0f, FontStyle.Regular );     e.Graphics.TextRenderingHint = TextRenderingHint.SystemDefault;     TextRenderer.DrawText( e.Graphics, "Antialiased Text", font, new Point( 0, 20 ), Color.Black );      e.Graphics.TextRenderingHint = TextRenderingHint.AntiAlias;      TextRenderer.DrawText( e.Graphics, "Antialiased Text", font, new Point( 0, 40 ), Color.Black );     e.Graphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;     TextRenderer.DrawText( e.Graphics, "Antialiased Text", font, new Point( 0, 60 ), Color.Black );     e.Graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;     TextRenderer.DrawText( e.Graphics, "Anti