Thursday, October 15, 2009 #

Writing to a file asynchronously

Here is a code snippet for writing to a file asynchronously:

private
void writeFileAsync(string text)
{
      System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
      byte[] buffer = encoding.GetBytes(text);
      using (FileStream fs = new FileStream("temp.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite, buffer.Length, FileOptions.Asynchronous))
      {
           IAsyncResult asyncResult = fs.BeginWrite(buffer, 0, buffer.Length, new AsyncCallback(EndWriteCallback), new State());
      }
}

private void EndWriteCallback(IAsyncResult result)
{
 
}

posted @ Thursday, October 15, 2009 1:48 PM | Feedback (0)

Tuesday, September 15, 2009 #

DataGridView upper case textbox column

It's a shame that the DataGridViewTextBoxColumn class doesn't allow you to set the casing so that you can restrict user input to all upper or lower case letters.

Fortunately, it's actually pretty easy to create a custom column class to do just that.
public class DataGridViewUpperCaseTextBoxColumn : DataGridViewTextBoxColumn
{
    public DataGridViewUpperCaseTextBoxColumn()
        : base()
    {
        CellTemplate = new DataGridViewUpperCaseTextBoxCell();
    }
}
 
public class DataGridViewUpperCaseTextBoxCell : DataGridViewTextBoxCell
{
    public DataGridViewUpperCaseTextBoxCell()
        : base()
    {
    }
 
    public override Type EditType
    {
        get
        {
            return typeof(DataGridViewUpperCaseTextBoxEditingControl);
        }
    }
}
 
public class DataGridViewUpperCaseTextBoxEditingControl : DataGridViewTextBoxEditingControl
{
    public DataGridViewUpperCaseTextBoxEditingControl()
        : base()
    {
        this.CharacterCasing = CharacterCasing.Upper;
    }
}

Sweet fancy moses:)

posted @ Tuesday, September 15, 2009 12:30 AM | Feedback (0)

Sunday, June 21, 2009 #

Scrollable PictureBox control

The PictureBox control in .NET does not have scroll bars, however, it is actually really easy to create a PictureBox control with scroll bars enabled. All you have to do is to drop a panel control onto a form, and set the AutoScroll property to true.

this.panel1.AutoScroll = true;

And drop a PictureBox control inside the panel and set the SizeMode to AutoSize.

this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;

That's it.

posted @ Sunday, June 21, 2009 10:14 PM | Feedback (0)

Saturday, May 09, 2009 #

Starting a background thread using the Threadpool

Here is a quick and easy way of starting a background process using the Threadpool by way of an inline delegate.

ThreadPool.QueueUserWorkItem(new WaitCallback(
delegate(object stateInfo)
{
    saveToDB();
}));         

posted @ Saturday, May 09, 2009 1:42 PM | Feedback (0)

Wednesday, April 29, 2009 #

Time enjoyed wasting is not wasted time

posted @ Wednesday, April 29, 2009 9:18 PM | Feedback (0)

Tuesday, April 28, 2009 #

Expect: 100-continue Header Problem

Here is a way for you to disable the Expect: 100-continue Header:

string url = "http://www.myurl.com";
 
ServicePoint sp = ServicePointManager.FindServicePoint(new Uri(url));
sp.Expect100Continue = false;

I was getting a 500 http error when I tried to send a post to a Java web service through .Net using HttpWebRequest. Turning off this header did the trick. This will work even if you are using the WebClient class, which goes through HttpWebRequest under the covers. Hope this helps someone, this is a doozy of a problem to debug.

posted @ Tuesday, April 28, 2009 11:13 PM | Feedback (0)

Saturday, April 18, 2009 #

Sending key presses to applications

I was working on an UI automation project recently and I had to submit key press messages to a windows forms application. I was looking at ways of writing code to make that possible, but then I found that you can actually just call SendKeys.Send() to send any key press message to the active form. Who knew it could be so easy.

http://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.aspx

posted @ Saturday, April 18, 2009 2:38 PM | Feedback (0)

Sunday, April 05, 2009 #

Microsoft test vouchers

I just found out that I can't use the 15% off voucher and the second shot offer voucher on the same MCTS certification test. That's really lame Microsoft.

posted @ Sunday, April 05, 2009 10:58 PM | Feedback (0)

Saturday, March 21, 2009 #

Searching for an item in a list

It's cool to see how the .Net framework has evolved from 1.1 to 2.0 and to 3.5. Searching for items in a list is a pretty common programming task. This is a comparison of how list searching has changed throughout the different .Net framework versions.

 
//.Net 1.1 search using a foreach statement
foreach (Customer cust in customerList)
{
    if (cust.FirstName == "Bill")
    {
        customer = cust;
        break;
    }
}
 
//.Net 2.0 search using a inline delegate            
Customer cust = customers.Find(
    delegate(Customer c)
    {
        return c.FirstName == "Bill";
    });
 
//.Net 3.5 search using a lambda expression
Customer cust = customers.Find(C => C.FirstName == "Bill");
 

posted @ Saturday, March 21, 2009 6:30 PM | Feedback (0)

Saturday, March 07, 2009 #

Refresh AppSettings keys

The .Net runtime caches the app.config file, therefore, when the app.config file is updated, you often need to restart the application in order for the changes to show up. Sure, you can get the keys by calling ConfigurationManager.OpenExeConfiguration() and you would be getting the latest version of the config file every time, but it's probably not the most efficient way to do it.

Here is how I like to do it. I call ConfigurationManager.AppSettings["MyAppSetting"] to get my key, which gets the cached version of the key so it's very fast. And I use a file system watcher to watch for changes in the config file. Whenever the config file is updated, I call ConfigurationManager.RefreshSection("AppSettings") to refresh the app settings keys. This way, the application would not have to be restarted whenever the config file changes.

Here is what the class might look like.

using System;
using System.Configuration;
using System.IO;
 
namespace myApp
{
    /// <summary>
    /// This class will refresh the cached version of the config file when it is changed.
    /// </summary>
    public static class ConfigurationWatcher
    {  
        private static FileSystemWatcher _fileWatcher;   
 
        internal static void Start()
        {
            if (_fileWatcher == null)
            { 
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                string path = Path.GetDirectoryName(config.FilePath);
                string filename = Path.GetFileName(config.FilePath);                   
 
                _fileWatcher = new FileSystemWatcher();
                _fileWatcher.Path = path;
                _fileWatcher.Filter = filename;
                _fileWatcher.NotifyFilter = (NotifyFilters.CreationTime | NotifyFilters.LastWrite |
                                NotifyFilters.FileName);
                _fileWatcher.Changed += OnChange;
                _fileWatcher.EnableRaisingEvents = true;
            }           
        }
 
        private static void OnChange(object source, FileSystemEventArgs e)
        {
            ConfigurationManager.RefreshSection("AppSettings");
        }
    }
}

posted @ Saturday, March 07, 2009 5:11 PM | Feedback (1)

Copyright © HanSolo

Design by Bartosz Brzezinski

Design by Phil Haack Based On A Design By Bartosz Brzezinski