Tuesday, March 30, 2010

OpenFileDialog changes the current directory

I opened a file from my application and later on when I went to run a shell script that was in the application directory, it wasn't able to find the file.  It turns out that the OpenfileDialog changed the current directory and therefore it was looking for my shell script in the new location.  The fixes were:

1.  Change OpenFileDialog to use the RestoreDirectory option and set it to true.  Like this:
            OpenFileDialog fileDlg = new System.Windows.Forms.OpenFileDialog
                Multiselect = MulitFileSelect,
                Filter = "Data Sources (*.txt, *.csv|*.txt*;*.csv|All Files|*.*",
                RestoreDirectory = true
2.   The next thing I did was when I looked for the Shell Script, if it didn't find the file, I inserted code to go to the Application.ExecutablePath and try there.  Keep in mind that ExecutablePath returns the .exe name so you need to call Path.GetDirectoryname on it if you want to get the directory location.

Summary on how to use List in C#

A good summary on how to use the List<> in C#

Return a List of string and append/concat a List in C#

Got this from stackoverflow - http://stackoverflow.com/questions/1036829/how-to-return-list-of-strings-in-c

public static List<string> GetCities()
  List<string> cities = new List<string>();
  return cities;

To append to a List just do something like this
List<string> thumbnails = new List<string>();
thumbnails.AddRange(--------have a string array here--------------);

Wednesday, March 24, 2010

Moving a WPF Window with a WindowStyle of None

From: http://cloudstore.blogspot.com/2008/06/moving-wpf-window-with-windowstyle-of.html

To enable a user to move your window from any area on that window (not necessarily just the title if you want to do something really different), you simply handle the MouseLeftButtonDown event for a UIElement on your window and call the DragMove method, as shown in the following code example.

private void title_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)

How to do a redim preserver in C#

This block of code dos the same thing:

string[] nums = {"5", "10", "20"};
string[] temp = new string[10];
System.Array.Copy(nums, 0, temp, 0, nums.Length);
nums = temp;

Monday, March 22, 2010

Three approaches to convert a string to a date in C#

string fileDate = "5/9/2010";
DateTime dt = Convert.ToDateTime(fileDate); //Can be used the same way as ParseExtract below.  It will throw a FormatException exception if it fails.

DateTime dt = DateTime.Parse(fileDate); //will try very hard to generate a DateTime object.  If the string has missing date elements, it will default to the current date and missing time elements default to 12:00:00 am.  After all efforts, if Parse cannot create a DateTime object, it will throw a System.FormatException exception.

DateTime.ParseExact(fileDate, "MMMM dd", null); //You pass a string, a format string the specifies the structure the time and date string must have, and an IFormatProvider reference that provides culture-specific information to the method.  If the IFormatProvider value is null, the current thread's culture information is used.  if it doesn't work, it will throw a System.FormatException exception.

Tuesday, March 16, 2010

IsNumeric in C#

If you need the functionality of IsNumeric in C# and don't want to use the Microsoft.VisualBasic dll then you could use these functions.  I haven't tried them out so can't say how effective they are, just here in case I need something like it in the future.

I found these online.  I can't find the link where I found the one below (my browser just crashed)
using System;
using System.Text;
using System.Text.RegularExpressions;

private bool IsTextValidated(string strTextEntry)
      Regex objNotWholePattern = new Regex("[^0-9]");
      return !objNotWholePattern.IsMatch(strTextEntry)
           && (strTextEntry != "");     

public static bool IsNumeric(object numberString)
char[] ca = numberString.ToString().ToCharArray();
for (int i = 0; i < ca.Length; i++)
if (!char.IsNumber(ca[i]))
if (ca[i] != '.')
return false;
if (numberString.ToString().Trim() == "")
return false;
return true;

Read In Tab Delimited file into Hashtable in C#

    private Hashtable GetHashtableFromFile(string file)
      Hashtable ht = new Hashtable();
      string line = string.Empty;
      using (StreamReader reader = new StreamReader(file))
        int i = 0;
        while ((line = reader.ReadLine()) != null)
          string[] args = line.Split(new char[] { ' ' });
          if (args.Length != 2)
            Console.WriteLine("Invalid input string: " + i.ToString());
          ht.Add(args[0], args[1]);
          Console.WriteLine("IP:{0}, Site:{1}", args[0], args[1]);

      return ht;


Thursday, March 4, 2010


There are many similarities between TWAIN and WIA, but there are also some distinct differences that you should base your choice on when developing an application.


1. As long as a driver exists, both are able to acquire images from devices such as a scanner or camera.  For devices like cameras, sometimes the driver is actually WIA but you can access it via the "TWAIN compatibility layer".
2. Acquire images with a dialog.
3. Programmatically set properties of the device and acquire the images programmatically without showing a dialog
4. Not all capabilities are supported by each device, so you can query the device for the ones that it does support.


1. WIA uses a common dialog for all devices while Twain uses a dialog created by the device manufacturer.  Practically speaking, this almost always means that the TWAIN dialog will provide more options and advanced control over the device.
2. TWAIN allows you to use custom capabilities that the device manufacturer has created even though they don't exist in the TWAIN specifications.
3. In general, when a device supports both Twain and WIA, TWAIN is better for scanners and WIA is better for acquiring images from cameras and video devices.
4. TWAIN has three transfer modes (Native, Memory, File) and WIA only has two (Memory, File).
5. Most TWAIN sources save the settings of the previous scan while WIA does not.
6. TWAIN supports options for each page when scanning in duplex mode but WIA uses the same settings for both sides.

For more details on WIA, please visit http://www.microsoft.com/whdc/device/stillimage/WIA-arch.mspx
For more details on TWAIN, please visit http://www.twain.org/

Wednesday, March 3, 2010

Convert.ToBoolean to convert string to boolean

Convert.ToBoolean function can be used to convert strings to boolean

How to access Default Public Property Item in a VB.NET dll from C# code

I have a function in VB.NET that is a Default Public Property Item (...).  So in VB.NET I would access it Something.Item(1) = somevalue, where 1 is the index of the array.  In C# you would access this property via the bracket [].  For example, the above example in C# would be Something[1] = somevalue

Left Pad and Integer in C#

From - http://www.victorchen.info/left-pad-an-integer-with-zeros-in-c/

int myNumber = 234;
string myStringNumber = myNumber.ToString().PadLeft(16, '0');

Tuesday, March 2, 2010

App.config vs registry

1) The built-in code to access an app.config from .NET is very full-featured and easy to use.

2) You can install the application without having to create registry entries.

3) You can remove the install without having to worry about removing registry entries.

4) You don't have to worry about access permissions to the registry (like from Vista).  However, Unprivileged user normally do not have access to the "Program Files" folder or any subfolders, and usually the app.config file will go there.

5) Content in App.config can be protected using RSA Protected configuration providers available in .Net framework

6) App.config is a XML based hirerarical tree structure database which follows standards understod by .Net and which can be accessed like objects by .Net Code unlike registry data.

Monday, March 1, 2010

How to use the app.config file in VS.NET 2008

I know this is straight forward, but for some reason I wasn't able to figure it out at first.  Can't remember what I did wrong, but here is how you can use it:

- Right click on the project and go to Properties.  Click on the settings tab.  In this area start typing in values.  At first there might be a little lag, as the IDE will create a file called app.config, and another one called Settings.settings and Settings.Designer.cs (under the properties folder).  Once you are done you can specify the type of setting, the scope (application, user) and a default value.

The way you access them is such:
Properties.Settings.Default.<Name of Property>.  For example, "Properties.Settings.Default.Username"

The way you set values to this property is such:
Properties.Settings.Default.<Name of Setting> = Value;

That's it. 

I was working in WPF and I wanted to access a setting in the App.xaml.cs file.  However for some reason Properties.Settings wasn't showing up on IntelliSense.  It turns out to be some namespace issue.  In the file app.config my settings are under the following block:
<MainNameSpace.ApplicationName.Properties.Settings> (I changed MainNameSpace and ApplicationName, but your file will have something similar).
The way I was able to access those settings was via:
Noblis.EBTSFileManager.Properties.Settings.Default.<Name of Setting>

Another thing I thought I needed to do was to include the app.config file in the bin directory.  This is not necessary.  The file is copied to the output directory via the application name.  so it will be something like: MainNameSpace.ApplicationName.exe.config.  Ther is also another file there called MainNameSpace.ApplicationName.vshost.exe.config.

More information can be found here:

One thing I need to figure out is where is the file with the settings.  For example, I keep a default username in my settings file.  When I run the application, it seems to be loading the values from the file, but the MainNameSpace.ApplicationName.exe.config doesn't have the default username, it looks just like the app.config file.  Where does it go?