FINAL UPDATE: I have tried this today, 7th of May 2008, and the bug is gone from all versions of IE and FF. I think it is the result of some Windows XP patch.

I found out that in Javascript, the Date object can give weird results.
Imagine that new Date(2005,2,27) [Javascript months are 0=11] returns 26 March 2005. If you look closely, you will see that it returns 26.03.2005 23:00:00.
Why? Because then our computers are configured to change the time with one hour. In a sense, this is not an error, as 27.03.2005 00:00:00 does not exist. You either have 1:00 of the 27th or 23:00 of the 26th. It is weird that Javascript both on IE and Netscape (and probably all other browsers) chooses the second option.

[Update thanks to a comment]I live in Romania. 27 of March 2005 is a daylight saving date (a bit non standard). Maybe the same bug can be reproduced for other countries on their respective daylight saving dates.[/Update]

This can yield weird results, as validators sometimes fail to recognize 27.03.2005 as a valid date. The solution for Javascript code: always use new Date(year, month, day, 12, 0, 0). The solution for validators... well, except calling Microsoft and bitching about it or changing the validator JS
file on ALL deployment servers, is either use a home made validator or replace the faulty validator js function in the pages that need date validation.

That means adding in the common site js this function:

function ValidatorConvert(op, dataType, val) {
function GetFullYear(year) {
return (year + parseInt(val.century)) - ((year < val.cutoffyear) ? 0 : 100);
}
var num, cleanInput, m, exp;
if (dataType == "Integer") {
exp = /^\s*[-\+]?\d+\s*$/;
if (op.match(exp) == null)
return null;
num = parseInt(op, 10);
return (isNaN(num) ? null : num);
}
else if(dataType == "Double") {
exp = new RegExp("^\\s*([-\\+])?(\\d+)?(\\" + val.decimalchar + "(\\d+))?\\s*$");
m = op.match(exp);
if (m == null)
return null;
cleanInput = m[1] + (m[2].length>0 ? m[2] : "0") + "." + m[4];
num = parseFloat(cleanInput);
return (isNaN(num) ? null : num);
}
else if (dataType == "Currency") {
exp = new RegExp("^\\s*([-\\+])?(((\\d+)\\" + val.groupchar + ")*)(\\d+)"
+ ((val.digits > 0) ? "(\\" + val.decimalchar + "(\\d{1," + val.digits + "}))?" : "")
+ "\\s*$");
m = op.match(exp);
if (m == null)
return null;
var intermed = m[2] + m[5] ;
cleanInput = m[1] + intermed.replace(new RegExp("(\\" + val.groupchar + ")", "g"), "") + ((val.digits > 0) ? "." + m[7] : 0);
num = parseFloat(cleanInput);
return (isNaN(num) ? null : num);
}
else if (dataType == "Date") {
var yearFirstExp = new RegExp("^\\s*((\\d{4})|(\\d{2}))([-/]|\\. ?)(\\d{1,2})\\4(\\d{1,2})\\s*$");
m = op.match(yearFirstExp);
var day, month, year;
if (m != null && (m[2].length == 4 || val.dateorder == "ymd")) {
day = m[6];
month = m[5];
year = (m[2].length == 4) ? m[2] : GetFullYear(parseInt(m[3],10))
}
else {
if (val.dateorder == "ymd"){
return null;
}
var yearLastExp = new RegExp("^\\s*(\\d{1,2})([-/]|\\. ?)(\\d{1,2})\\2((\\d{4})|(\\d{2}))\\s*$");
m = op.match(yearLastExp);
if (m == null) {
return null;
}
if (val.dateorder == "mdy") {
day = m[3];
month = m[1];
}
else {
day = m[1];
month = m[3];
}
year = (m[5].length == 4) ? m[5] : GetFullYear(parseInt(m[6], 10))
}
month -= 1;
var date = new Date(year, month, day,12,0,0); //BUG FIX
return (typeof(date) == "object" && year == date.getFullYear() && month == date.getMonth() && day == date.getDate()) ? date.valueOf() : null;
}
else {
return op.toString();
}
}

I've just installed Resharper 2.0. It still has little bugs, but it has that system where you can remember and ignore a set of errors.

What can I say? It's a the greatest software tool EVER. It can generate code, complete code, suggest changes, basically what Resharper 1.5 did, but
now it's WAY better.

The best thing in 2.0 I think it's Live Templates. They work like macros, but from just a few key presses and are way easy to configure. Imagine you
want to do something like :

throw new Exception("Any message");

all you have to do is type thr[Tab] and you get

throw new Exception(""); and the cursor between the quotes.

Of course that means also: itterating through a dictionary, creating for loops, transforming types into other types, automatic creation of aspx code
like datagrid columns, etc.

You want to put a piece of code in an if block, a region or a try catch, just select the code , press ctrl-alt-J and choose the type of block.
You want to add the properties and methods of an object inside your class to your class, just press Alt-Insert and choose the object and the members and you have them all in your class, referenced to the internal object and commented!

The Live Template system includes a scope of the template. That means that the template for creating a new method will not work inside a method, or
aspx code will not be generated into a cs file, etc.

Other two nice tools that I've found are :

- CommentReFlower - which takes care of the comments in your code. Not terribly useful, but time saving when you need to comment code
- RegionsAddIn - it allows you to take pieces of code and move them into regions, or create new ones.

Both are addins for visual studio 2003.

I can't explain it better than the four guys from Rolla, so there you have them:

Improving Developer Productivity with Visual Studio .NET Macros

and has 0 comments
You go to the MSDN site and you get this as a proper implementation of the IDisposable interface:

#region IDisposable Members
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}

protected virtual void Dispose(bool isDisposing)
{
// Check to see if Dispose has already been called.
if (!_isDisposed)
{
_isDisposed=true; //this is what I added, I think it makes this thread safe
if (isDisposing)
{
//Clean up resources
}
}
_isDisposed = true;
}
#endregion

In other words, implement IDisposable to clean up unmanaged resources. Well, unmanaged could be considered managed code from another thread. If your object starts a thread that calls an event, then when you exit the code block where you declared the object, then the event will never get fired. A pending action is unmanaged, therefore you can do something like:

while (!actionFinished) Thread.Sleep(1000);

the action should, of course, set actionFinished to true;

and has 0 comments
If you have ever used code like:
try {
obj1=(TypeObj1)obj2;
} catch {
obj1=null;
}

you need to read this.

The same thing can be written as:
obj1=obj2 as TypeObj1;

In case the conversion doesn't work, the value of obj1 will be null.
Be careful when you do this with value types that don't allow null.

Update:
Also, implicit casting will not work. A code like:
int i=5;
string s=i as string;

will have s being null, not "5".

You also have to be careful about using the "is" word. Code like
if (ctrl is Table) {
Table tbl=(Table)ctrl;
tbl...

actually casts ctrl twice!
a is b translates to (a as b)!=null.

So a nice piece of code would look like this:
Table tbl=ctrl as Table;
if (tbl!=null) {
tbl...

and has 0 comments
Did you know that in a class you can do something like:
public static implicit operator type2(type1 value) {
return value.ToType2();
}


Now class type1 will be automatically converted into type2 when used as such.

Example:

public class NullBoolean {
private bool internalBool;

public static NullBoolean False {
return new NullBoolean(false);
}

public static NullBoolean True {
return new NullBoolean(true);
}
public NullBoolean(bool value) {
internalBool=value;
}

public static implicit operator bool(NullBoolean) {
return internalBool;
}
}


with this class all these statements are correct:
NullBoolean nb=null;
nb=NullBoolean.True;
if (nb==true) MessageBox.Show("nb is true"); // no cast

if the word implicit would have been explicit, then the compiler would have required you to cast nb to bool first:

if ((bool)nb==true)...


Add to this Equals, ToString and == overide and you have a nice boolean type that allows for null values.

Update:
First of all implicit operators are a kind of a shortcut for casting. Sometimes this doesn't work, like in foreach loops. Sometimes a code like this will not work:
foreach (RowAdapter ra in dt.Rows) ...

while this would work:
foreach (DataRow dr in dt.Rows) {
RowAdapter ra=dt;...

Second of all, an object like the one above can in NET 2.0 be easily formed with nullable types:
bool? nb;

and has 0 comments
Windows Management Instrumentation (WMI) provides access to information about objects in a managed environment. Through WMI and the WMI application programming interface (API), applications can query for and make changes to static information in the Common Information Model (CIM) repository and dynamic information maintained by the various types of providers.

What that actually means it that one can get information about the computer and operating system or subscribe to global events. I've already added a
SystemManagement object to the Siderite library, but it is only a wrapper for a few lines of code that are easy to do anyway.

Cool things that WMI can help you with:
- Enumerate harddrives, networkcards, PCI slots, operating system information, processors, processes, registry keys, security policies, windows start menu items, etc. and their properties (physical memory size, processor ID, etc)
- Subscribe to events like "a specific registry key has been changed" or "a new process started/ended" or "windows is shutting down".

It is also interesting that this can be done to a remote system as well, just like the Windows Task Manager which uses WMI to get and display all information and can connect to another computer.

It seems that the NET framework comes with some nice command line utilities. One of them is MgmtClassGen.exe.

Basically what you do is:
MgmtClassGen.exe /P
And it creates a strong typed wrapper for the WMI class.

Example:
MgmtClassGen Win32_Processor /P processor.cs
creates a Processor class that controls everything about the processor.

For a complete list of WMI classes check out:
Computer System Hardware Classes

I had to do this Export functionality that saves data in a file from the database after filtering by date. My first idea was "let's just export everything and only use an OpenFileDialog", but then the date filtering request came. I thought that changing the OpenFileDialog to add two date
time pickers would be an easy job, but, alas, it is close to impossible.

Good research came out of this, though:
FileDialogExtender - Customize a dialog by issuing API Messages to already open windows
Customize Your Open File Dialog - Customize a dialog by changing the registry
Advanced MessageBoxing with the C# MessageBoxIndirect Wrapper - a friendly C# wrapper class for the MessageBoxIndirect API that allows you to add a help button, custom icon, locale-aware buttons, and different modalities to a message box.
Control.WndProc Method - MSDN WndProc method

and has 0 comments
You use the InvokeMember function.

Quick example:
typeof(DataGrid).InvokeMember("RowAutoResize",BindingFlags.InvokeMethod|BindingFlags.NonPublic|BindingFlags.Instance,null,wDataGrid1,new object[] {1});

This is equivalent to wDataGrid1.RowAutoResize(1), which would not normally work because the method is private.

The syntax for InvokeMember is:
public object InvokeMember(
string name, // name of the method
BindingFlags invokeAttr, // Binding flags, see below
Binder binder, // Use null for the default binder. A Binder object that defines a set of properties and enables binding, which can involve selection of an overloaded method, coercion of argument types, and invocation of a member through reflection
object target, // object that owns the method you want to run
object[] args // argument array
);

Why does it work? Because access-modifier based security has no impact on Reflection
Ok, some of you might ask themselves How do I protect my code in libraries and other things I publish? Add this in front of the namespace declaration:

[assembly:ReflectionPermissionAttribute(SecurityAction.RequestRefuse,
Unrestricted=true)]

By setting the ReflectionPermission to RequestRefuse at assembly level, you could prevent all the accesses to private members and if someone tries to access it, it throws 'System.NullReferenceException'. In the above example, at fInfo.SetValue it throws NullReferenceException, because it is able to create fInfo object.


I think this is a greatly useful feature, especially when working with
Microsoft objects that have a lot of nifty procedures all marked with
private or internal or both :)

and has 1 comment
Trying to build a reusable object that is independent of the Windows or Web interface I've stumbled upon the issue of multiple threads trying to access and modify the same form. The ugly "Controls created on one thread cannot be parented to a control on a different thread." error occured and, no matter what I tried, it seemed it will never work. But finally I found out the solution.

First the issue:
doing something on the interface was starting a separate process that ran an external program. The interface has a progress bar that was updated during this. At the end of the process, an event was fired, and to that event I added a method that was supposed to clear the progress bar and put another UserControl on the form. The the error occured.

The problem was that the event was fired by the separate process that ran the external program. Trying to change something in the form that was created on another thread resulted in error.
The solution is that inside the method called by the event any references to methods that change the interface must be done through BeginInvoke:

private delegate void MethodDelegate(int i)

private void TestMethod(int i) {
// change interface here
}

private void OnEvent(object sender, EventArgs e) {
<interface_form_object>.BeginInvoke(new MethodDelegate(TestMethod),new
object[] {i});
// this replaces using TestMethod(i) which generates an error
}

Update on this:
Use the BackgroundWorker class in NET 2.0.

One of the major marketing statements regarding ASP.NET was its capability to display content differently depending on browser. What actually happends, though, is that Internet Explorer is considered a HTML 4.0 compatible browser, while others are not. If you ever looked at a normal page with a few textboxes and a button on Firefox or Netscape, then you know what I mean.

Example:rendering for FireFox:

<table width="30%" border="2">
<tr>
<td align="Right">
<span >
Hi there...
</span>
</td>
</tr>
</table>


rendering for IE:

<table width="30%" border="2">
<tbody><tr>
<td style="FONT-SIZE: large; COLOR: red" align="right">
Hi there...
</td>
</tr>
</tbody></table>


In this case, if you want to , let's say, replace the innerHTML property of the td, then you lose the color red.Other such changes put the width/height parameters inside the style property or outside it.

Apparently, the difference in rendering comes from the HtmlTextWriter class. For "not compatible browsers" an overridden class is used for rendering: Html32TextWriter.

How to fix it.
The recomended fix for this is change the tag in machine.config. That would make your server compatible to each browser as you see fit. The downside of this, of course, is that your ASP.NET application will render differently for each hosting server making it undeployable.

My fix.
Just inherit the Page class and add this:
protected override void Render(HtmlTextWriter writer)
{
writer=new HtmlTextWriter(writer.InnerWriter);
base.Render (writer); // or your own rendering logic
}
and use this page class for all forms.

This will make all controls on the page render for HTML4.0 compatible browsers. In my personal opinion, we will never make sites that are designed to be seen with Internet Explorer 3.2 or Nescape 4 so this will work. Of course, that doesn't make the pages look the same on all browsers. One needs to check out all the details regarding browser compatibilty such as the way the Visual Studio IDE adds or removes DOM incompatible attributes, but it's a major step forwards.

and has 0 comments
Today I've learned that there is a way to add extra functionality to already defined classes through ExtenderProviders. While in Windows Forms things are relativeley easy, in Asp.NET visual studio 2003 is broken and needs special hacks in order to work.

This is the link for how to use ExtenderProviders in ASP.NET:
Extender provider components in ASP.NET: an IExtenderProvider implementation

Example:
in my latest WebControls library I have a component called NiftyExtender. You drag and drop it on an ASP.NET page and in Visual Studio all Controls have extra filter functions like Glow, Emboss, Engrave, Flip, etc. There is no need for cumbersome inheritance, just add the component to an already made site and it works just fine.

The same applies to Windows Forms, but there it works by default, without the need for a special class and weird hacks. A Windows Forms example is the ToolTip object that I always wondered what it does. Well, you drag and drop it on a form, then all windows form components have a tooltip in the Misc section.

I am thinking of a validator ExtenderProvider that would add the necessary validation functions to all controls in a page or form.