Posts

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

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

Image
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

Image
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; }