Blog

posts tagged with csharp

Microsoft has put my 'Dual List' .NET Magazine article online!

0 Comments
By Fons Sonnemans, 09-apr-2005

Microsoft has put my Visueel programmeren met .NET: Dual List Control article online. It is published in the .NET Magazine #8 and it is free for Dutch developers.
They didn't publish the sourcecode (yet) but you can download it from my own site. The aricle is in Dutch. You can find an (old) English version of this article here. An even more advanced implementation that also supports Drag & Drop can be found here.

READ MORE

WaitCursor

0 Comments
By Fons Sonnemans, 10-feb-2005

For a long time I thought that I only had to set the Cursor.Current to a WaitCursor before a long running operation, the .NET runtime would reset it back to the Default cursor. Turns out that this is only true when the mouse is moved. Bummer.

// Cursor.Current are automatically reset to Default when the
// mouse is moved and the application is idle!
Cursor.Current = Cursors.WaitCursor;

The solution for this problem is very easy. I created a helper class called WaitCursor which set the Cursor.Current and restores it to the original value when it it disposed.

public sealed class WaitCursor : IDisposable {   &nbsp   &nbsp   &nbsp   &nbsp
   &nbspprivate Cursor _prev;

   &nbsppublic WaitCursor(){
   &nbsp   &nbsp_prev= Cursor.Current;
   &nbsp   &nbspCursor.Current = Cursors.WaitCursor;
   &nbsp}

   &nbsppublicvoid Dispose(){
   &nbsp   &nbspCursor.Current =_prev;
   &nbsp}
}

I create the instance of the WairCursor class inside a using statement. This will automatically call the Dispose() method when it goes out of scope.

READ MORE

Dispose Modal WinForm Dialogs

0 Comments
By Fons Sonnemans, 12-dec-2004

There is a difference in disposing Modal and Non-Modal forms. In a training I gave last week I noticed that even experienced developers didn't know that Modal Dialogs don't dispose automatically, Non-Modal do.

private void buttonShowNonModalForm ( object sender , System.EventArgs e){
   &nbspnew TestForm().Show();
}

privatevoidbuttonShowModalDialog(objectsender, System.EventArgs e){
   &nbspnew Form2().ShowDialog();
}

The solution to this problem is very simple by creating the Form instance within a using block. This will dispose the Form when it is closed.

private void buttonShowModalDialog ( object sender , System.EventArgs e){
   &nbspusing(TestForm f =new TestForm()){
   &nbsp   &nbspf.ShowDialog();
   &nbsp}
}

An alternative solution uses a try/finnaly. Personally I prefer the previous, it is easier to read and write.

READ MORE

C# HandleWhiteSpace Add-In

0 Comments
By Fons Sonnemans, 23-sep-2004

Download WhiteSpace.zip

Introduction

The C# code editor in Visual Studio.NET 2003 does not handle whitespaces automatically like the VB.NET code editor does. This Add-In solves this problem by adding the 'Handle WhiteSpace' menu option to the Visual Studio.NET 2003 Tools menu. This option formats the C# code of the active code editor. This includes:

  • Space before:  method declaration parentheses, method call parentheses, statement parentheses, braces and brackets
  • Space after: comma and semicolon
  • Space around: operators
  • Double space

Example


Screen shot: Handle WhiteSpace menu option

After you have selected the menu option the C# source code is formatted with correct whitespaces.


Screen shot: Reformatted code

Conclusion

Writing clean C# code has become easier with this Add-In. I hope you enjoy using it.

I thank Heindirk de Laat for providing me the code for the most difficult part of the program. I only added some extra regular expressions and transformed it into an Add-In.

Any suggestions and feedback for improving this Add-In is most welcome. Send your suggestions and feedback to Fons.Sonnemans@reflectionit.nl


READ MORE

ToolboxBitmap workaround

0 Comments
By Fons Sonnemans, 03-sep-2004

I have found a solution for a problem which I had for a long time. I was unable to set the ToolboxBitmap attribute for a component using the (type, string) constructor. I found the solution for this problem (using an internal ResFinder class) on www.bobpowell.net. This site has also some other Windows Forms Tips and Tricks. Great!

READ MORE

Visual C# 2005 Express Edition Beta is great

0 Comments
By Fons Sonnemans, 14-jul-2004

I'm testing Visual C# 2005 Express Edition Beta and I really like it. It has all of the features which I need to build Windows Forms applications. The Editor has also all new IntelliSense, Refactoring and Code Snippets features. They work great and really can boost productivity.

I have tested it on a PC with only 256Mb of ram. This is for the beta not enough. You need at least 512Mb.

I'm using the Online MSDN Help, it works OK. The looks are good but I find it difficult to get to the 'overview' of a class.

For professional development I would advise to use Visual Studio. For hobby work use the Express versions.

READ MORE

String Array Sorting

0 Comments
By Fons Sonnemans, 27-apr-2004

It took me today some time to figure out how to sort an array of strings case-sensitively. The default behavior of the Array.Sort() uses an default Comparer object which should be case-sensitive. When I tested this I found out that I had misinterpreted the definition of 'case-sensitive'. What I wanted was 'Oridinal' sorting. So I created an OrdinalStringComparer class which implements IComparer and I got what I wanted.

using System;
using System.Collections;

namespace ReflectionIT.Test {

   &nbspclass Class1{

   &nbsp   &nbsp[STAThread]
   &nbsp   &nbspstaticvoid Main(string[]args){

   &nbsp   &nbsp   &nbspTest(new CaseInsensitiveComparer());
   &nbsp   &nbsp   &nbspTest(Comparer.Default);   &nbsp   &nbsp
   &nbsp   &nbsp   &nbspTest(new OridinalStringComparer());
   &nbsp   &nbsp
   &nbsp   &nbsp   &nbspConsole.ReadLine();
   &nbsp   &nbsp}

   &nbsp   &nbspprivatestaticvoid Test(IComparer comparer){

   &nbsp   &nbsp   &nbspstring[]words=newstring[]{"c","a","A","aB","ab","Ab"};

   &nbsp   &nbsp   &nbspArray.Sort(words,comparer);
   &nbsp   &nbsp
   &nbsp   &nbsp   &nbspConsole.WriteLine(comparer.GetType().Name +":");
   &nbsp   &nbsp   &nbspforeach(stringwordinwords){
   &nbsp   &nbsp   &nbsp   &nbspConsole.WriteLine(word);
   &nbsp   &nbsp   &nbsp}
   &nbsp   &nbsp   &nbspConsole.WriteLine();
   &nbsp   &nbsp}
   &nbsp   &nbsp
   &nbsp}
   &nbsp   &nbsp
   &nbsppublicclass OridinalStringComparer : IComparer {
   &nbsp   &nbsp
   &nbsp   &nbspint IComparer.Compare(object x,object y ){
   &nbsp   &nbsp   &nbspreturnstring.CompareOrdinal((string)x,(string)y);
   &nbsp   &nbsp}
   &nbsp   &nbsp
   &nbsp}
   &nbsp   &nbsp
}

And when you run this program you get the following output:

CaseInsensitiveComparer:
A
a
Ab
ab
aB
c

Comparer:
a
A
ab
aB
Ab
c

OridinalStringComparer:
A
Ab
a
aB
ab
c

READ MORE

System.Collections and System.Collections.Specialized

0 Comments
By Fons Sonnemans, 08-mrt-2004

This table gives you an overview of all collections in the System.Collections and System.Collections.Specialized namespaces.

Class Key Value Remarks
System.Array   ? Predefined size, used for passing data around.
ArrayList   Object Easy to work with, provides basic collection functionality and can easily be converted to an Array.
BitArray   Boolean
Manages a compact array of bit values, which are represented as Booleans
CollectionBase   ? Abstract base for building your own collection classes.
DictionaryBase Object ? Abstract base for building your own collection classes using a key-value pair.
HashTable Object Object Provides high performance access to items in the key-value pair collection, by a specific key.
Queue   Object Implements the FIFO mechanism.
ReadOnlyCollectionBase   Object Abstract base for building your own read-only collection classes.
SortedList Object (sorted) Object Provides access to items in the collection by a specific key or an index (GetByIndex(int)).
Stack   Object Implements the LIFO mechanism.
Specialized.HybridDictionary
Object Object Uses internally a ListDictionary class when the collection is small, and switches automatically to a Hashtable class when the collection gets large.
Specialized.ListDictionary Object Object Is designed to be used for collections with 10 or less items, while the Hashtable is designed to contain more items.
Specialized.NameObjectCollectionBase String ? Abstract base for building your own collection classes using a key-value pair.
Specialized.NameValueCollection String (sorted) String NameValueCollection class is the strong type equivalent of the SortedList class, for the String class.
Specialized.StringCollection   Object Strongly typed ArrayList for the String class.
Specialized.StringDictionary String String Strongly typed Hashtable for the String class, not sorted.

Read also Jan Tielens article on the MSDN Belux website.

READ MORE

EventsHelper using Fire and Forget

0 Comments
By Fons Sonnemans, 07-mrt-2004

I have used the EventsHelper class to fire events asynchronical. I came across this class in the TechEd 2003 presentation C# Best Practices from Eric Gunnerson and Juval Löwy. Today I noticed a bug. The FireAsync() method uses the 'Fire and Forget' pattern incorrectly.

The 'Fire and Forget' pattern is used when the return value and returned parameters of the call are not required, and when there is no need to synchronize with the asynchronously executing method. In this case, the caller simply needs to call BeginInvoke, passing any normal and ref parameters, and null for the callback and asyncState.

This has been a commonly used pattern. However, there has been a documentation change in version 1.1 of the .NET Framework that has big ramifications for this technique of making async calls. The documentation now states that EndInvoke must be called for a corresponding BeginInvoke--otherwise Microsoft say they may now, or in the future, leak resources. It appears that no resources are leaked under version 1.0 of the framework; however, with this type of warning in place, it is recommended that a call to EndInvoke be made even if the return values of an async call are not required.

It is relatively straightforward to create a helper class that handles this for you--one example I found here.

public class AsyncHelper {

   &nbspdelegatevoid DynamicInvokeShimProc(Delegate d,object[]args);

   &nbspstatic DynamicInvokeShimProc dynamicInvokeShim=new
   &nbsp   &nbspDynamicInvokeShimProc(DynamicInvokeShim);

   &nbspstatic AsyncCallback dynamicInvokeDone=new
   &nbsp   &nbspAsyncCallback(DynamicInvokeDone);

   &nbsppublicstaticvoid FireAndForget(Delegate d,paramsobject[]args){
   &nbsp   &nbspdynamicInvokeShim.BeginInvoke(d,args,dynamicInvokeDone,null);
   &nbsp}

   &nbspstaticvoid DynamicInvokeShim(Delegate d,object[]args){
   &nbsp   &nbspd.DynamicInvoke(args);
   &nbsp}

   &nbspstaticvoid DynamicInvokeDone(IAsyncResult ar){
   &nbsp   &nbspdynamicInvokeShim.EndInvoke(ar);
   &nbsp}
}

READ MORE

DateDiff() function in C#

4 Comments
By Fons Sonnemans, 11-feb-2004

I have written the following DateDiff() function in C#. VB.NET users already had it using the Micrsoft.VisualBasic.dll assembly. Now you can use it without referencing this 'ugly' extra assembly.

using System;


namespace ReflectionIT.System {

   &nbsppublicenum DateInterval {
   &nbsp   &nbspYear,
   &nbsp   &nbspMonth,
   &nbsp   &nbspWeekday,
   &nbsp   &nbspDay,
   &nbsp   &nbspHour,
   &nbsp   &nbspMinute,
   &nbsp   &nbspSecond
   &nbsp}

   &nbsppublicclass DateTimeUtil {

   &nbsp   &nbsppublicstaticlong DateDiff(DateInterval interval, DateTime date1, DateTime date2){

   &nbsp   &nbsp   &nbspTimeSpan ts=date2-date1;

   &nbsp   &nbsp   &nbspswitch(interval){
   &nbsp   &nbsp   &nbsp   &nbspcase DateInterval.Year:
   &nbsp   &nbsp   &nbsp   &nbsp   &nbspreturndate2.Year -date1.Year;
   &nbsp   &nbsp   &nbsp   &nbspcase DateInterval.Month:
   &nbsp   &nbsp   &nbsp   &nbsp   &nbspreturn(date2.Month -date1.Month)+(12*(date2.Year -date1.Year));
   &nbsp   &nbsp   &nbsp   &nbspcase DateInterval.Weekday:
   &nbsp   &nbsp   &nbsp   &nbsp   &nbspreturn Fix(ts.TotalDays)/7;
   &nbsp   &nbsp   &nbsp   &nbspcase DateInterval.Day:
   &nbsp   &nbsp   &nbsp   &nbsp   &nbspreturn Fix(ts.TotalDays);
   &nbsp   &nbsp   &nbsp   &nbspcase DateInterval.Hour:
   &nbsp   &nbsp   &nbsp   &nbsp   &nbspreturn Fix(ts.TotalHours);
   &nbsp   &nbsp   &nbsp   &nbspcase DateInterval.Minute:
   &nbsp   &nbsp   &nbsp   &nbsp   &nbspreturn Fix(ts.TotalMinutes);
   &nbsp   &nbsp   &nbsp   &nbspdefault:
   &nbsp   &nbsp   &nbsp   &nbsp   &nbspreturn Fix(ts.TotalSeconds);
   &nbsp   &nbsp   &nbsp}
   &nbsp   &nbsp}

   &nbsp   &nbspprivatestaticlong Fix(double Number){
   &nbsp   &nbsp   &nbspif(Number >=0){
   &nbsp   &nbsp   &nbsp   &nbspreturn(long)Math.Floor(Number);
   &nbsp   &nbsp   &nbsp}
   &nbsp   &nbsp   &nbspreturn(long)Math.Ceiling(Number);
   &nbsp   &nbsp}
   &nbsp}
}


READ MORE

All postings/content on this blog are provided "AS IS" with no warranties, and confer no rights. All entries in this blog are my opinion and don't necessarily reflect the opinion of my employer or sponsors. The content on this site is licensed under a Creative Commons Attribution By license.