Reflection IT Blog

Benieuwd naar de laatste ontwikkelingen rondom software ontwikkeling en Reflection IT? Onze slimme koppen delen regelmatig hun kennis en ervaring. Zo weet jij wat er speelt!

csharp tagged Blog posts

EventsHelper using Fire and Forget

07-Mar-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}
}

DateDiff() function in C#

11-Feb-2004 4 Comments

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


Integrate NDoc HTML Help in VS.NET

30-Dec-2003

NDoc 1.2 generates class libraries documentation from .NET assemblies and the XML documentation files generated by the C# compiler. NDoc uses add-on documenters to generate documentation in several different formats, including the MSDN-style HTML Help format (.chm), the Visual Studio .NET Help format (HTML Help 2), and MSDN-online style web pages.

This article explains the four steps to take in order to integrate the HTML Help 2 file you generated into Visual Studio.NET.

  1. Comment the Library using XML documentation tags
  2. Create HTML Help 2 using NDoc
  3. Registering the Help File using H2Reg
  4. Include Help Collection to VSCC

 

.NET Quick Reference Card

07-Nov-2003

Download DotNetRefCard.pdf

I have created a small quick reference card for Microsoft .NET with some hard to remember details. My printer supports two pages per side and double sided printing. This makes it possible to print the 4 pages on a single sheet which makes it easier to use.

Contents:

  • C# String escape sequence
  • C# Numeric & Char Literals
  • String Formatting
  • Standard Numeric Format Strings
  • Custom Numeric Format Strings
  • Standard DateTime Format Strings
  • Custom DateTime Format Strings
  • Regular Expressions

I hope you will find it useful.

Any suggestions and feedback for improving this reference card is most welcome. Send your suggestions and feedback to Fons.Sonnemans@reflectionit.nl

LocalizedTextProvider Component

10-Aug-2003 1 Comments

I have read that the .NET framework has great features to localize your application. I had to use them recently to create an English, Dutch, French and German "version" of one of my applications. I found out they worked well but it was very time consuming to set all the text properties of all controls for each language. Even worse you have to translate common terms like: OK, Cancel, New, Open, Close, etc. on every form if you want to use the designer. You can, of course, write code to fetch them all from one resource file. But I don't like to write code, especially if you don't have to.

I came up with a solution for this problem, called the LocalizedTextProvider component. This component is actually an extender which, adds a LocalizedText property to a Control or MenuItem. When you add this component to a WinForm it will allow you to set the LocalizedText property ('Misc' category) of all controls on your form. You can select a Key from a predefined list. This list contains all keys from the string resources in the component. I have filled the list using the International Word List from the 'Microsoft Official Guidelines for User Interface Developers and Designers' website.

 


Example: the LocalizedText property for the Cancel button is set to Microsoft.Cancel

The Text for the Cancel button will automatically be translated to 'Annuleren' for Dutch users, 'Abbrechen' for German users and 'Annuler' for French users. You can test this by setting the CurrentUICulture property of the CurrentThread to a Dutch, German or French CultureInfo.

C# Minesweeper Game

29-Jun-2003 6 Comments

I have always wondered how hard it would be to write a game in C#. I picked Minesweeper for my first try. Made an OO design and then went programming.

See the result in the downloadable zip file. The whole program is less then 400 lines of code!


Screenshot

I have reduced the complexity a bit by eliminating the flag-icon and all menu options.

 

C# InputBox

30-Apr-2003 2 Comments

Visual Basic 6.0 has an InputBox() function, Visual Basic.NET has one but in C# you don't. You can solve this easily by adding a reference to 'Microsoft.VisualBasic.dll' and use the static method Microsoft.VisualBasic.Interaction.InputBox().

The VB implementation has some shortcomings which I solved in my improved InputBox class. You never know whether the user entered a empty text or clicked the Cancel button. It is also impossible to have validation on the text.


Example: InputBox

SQL-strings considered harmful

10-Mar-2003

Did you know that any malicious user can corrupt your database by injecting harmful SQL strings? To prevent SQL injection, you can use the parameters collections when building SQL strings. However, I developed a more sophisticated method to construct SQL statements from user's input and execute them safely. In this article I describe how to write and execute SQL statements by using objects instead of SQL strings. These objects also address specific SQL statement syntax issues on different RDBMS: they enable you to write generic and RDBMS independent code.

Save your UserSettings in an Isolated Store

01-Feb-2003

I like applications who remember my settings the next time I use it. This is an easy feature which is often forgotten. Most of the time because it is quite some work. With this article I want to help you with this and saving you a lot off work.

Then there is always the question 'where do we store the settings?'. I see a lot of applications using the Registry, ini-files or xml-files. All these solutions are causing a security risk. Especially when you want your application to be downloaded from the web using the 'no touch' deployment features of .NET.

Microsoft has solved this problem for me by introducing an isolated stores. With these stores, you can read and write data that less trusted code cannot access and prevent the exposure of sensitive information that can be saved elsewhere on the file system. Data is stored in compartments that are isolated by the current user and by the assembly in which the code exists.

The downloadable zipfile contains a UserSettingLibrary which can be used to store user settings into an isolated store.

Get in touch

Met dit formulier kunt u informatie over een In-Company of Small-Group training aanvragen. U kunt in het bericht aangeven welke training u wilt, voor hoeveel personen, wanneer deze verzorgd moet worden en op welke locatie. Wij nemen vervolgens contact met u op.

U kunt ons ook bereiken via telefoonnummer +31 (0)493-688810 of per mail training@reflectionit.nl.