and has 1 comment
Making a Web Control is not complicated. but things get weird when they need to postback values. Well, how does a Web Control postback? It implements the Interface IPostBackDataHandler which exposes two methods:

public bool LoadPostData(string postDataKey, NameValueCollection postCollection)
public void RaisePostDataChangedEvent()

RaisePostDataChangedEvent should be called by LoadPostData, so you can just ignore it if you don't need it.
LoadPostData will not be called unless the WebControl is registered with the page for postback. I do this in the override of OnInit:
if (Page != null) Page.RegisterRequiresPostBack(this);
postDataKey is the "identifier" of the control, meaning that weird UniqueID with ":" instead of "_" separating the parent control ids from the children. You can use it or not.
postCollection is the Request.Form collection, The collection of all incoming name values.

example, a Label that also adds a hidden input field and handles the postback of that field value. Try changing the value from javascript and the text value will also change on postback.

public class UselessLabelPostback:Label,IPostBackDataHandler
{
private bool changed;
public bool Changed
{get { return changed; }}

protected override void OnInit(EventArgs e)
{
base.OnInit (e);
if (Page != null) Page.RegisterRequiresPostBack(this);
changed=false;
}

protected override void Render(HtmlTextWriter writer)
{
base.Render (writer);
HtmlInputHidden hih=new HtmlInputHidden();
hih.ID=this.ClientID+"_hiddenField";
hih.Value=this.Text;
hih.RenderControl(writer);
}

public bool LoadPostData(string postDataKey, NameValueCollection postCollection)
{
string s=postCollection[this.ClientID+"_hiddenField"]; //not using postDataKey
if (s!=null)
{
s=HttpContext.Current.Server.HtmlDecode(s);
if (s!=Text) RaisePostDataChangedEvent();
this.Text=s;
return true;
}
return false;
}

public void RaisePostDataChangedEvent()
{
this.changed=true;
}
}

Important:
This is a control inherited from a Label, that's why I chose to render the hidden input manually. This has a few side effects. For example, the id of the label will be ucIPostBackTest1_UselessLabelPostback1 if the control is inside a User Control called ucIPostBackTest1. The id of the hidden field will be ucIPostBackTest1_UselessLabelPostback1_hiddenField only because I used the ClientID of the label when I manually set the field ID. For the same reason the name (the name attribute of a html item is the one that gives the postback identifier, not the id) will be the same.

The way to do it when starting from scratch is to add extra controls in the CreateChildControls() overriden method, use EnsureChildControls() in the PreRender or Render methods and the web control will render them all. Here the names and ids of the rendered child controls will differ and this is where the postDataKey comes in. But that's another story.

and has 0 comments
Except the obvious one that override cannot be used on methods not declared as virtual, there is the little nag of how the original object will use the method internally. Mainly it will use its own not overriden code, but not the methods that hide its code.

Object A has a method M virtual. B inherits A and overrides method M.
With an instance of B, B.M() will run the code in object B, while M() inside the code of object A will also run the code in object B.

Object A has a method M not virtual. B inherits A and hides method M with a new M method.
With an instance of B, B.M() will run the code in object B, while M() inside the code of object A will run the code originally in object A.

Ex:

public class PrintStuff
{
public PrintStuff() {
PrintMe();
}

public void PrintMe() {
Console.Write('ME!');
}
}

public class PrintStuff2: PrintStuff
{

public new void PrintMe() {
Console.Write('new ME!');
}
}

a code like new PrintStuff2(); will output ME! while a code like new PrintStuff2().PrintMe() will output new ME!

and has 2 comments
I've always compiled and tested web applications on the company server, but then I found myself in need of debugging so I started a project on the local machine. Then I started to get random errors when compiling the code.

===Errors from hell===
Configuration Error
Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.

Parser Error Message: Access is denied: 'Some.DLL.Library'.

Source Error:


Line 196: <add assembly="System.EnterpriseServices, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
Line 197: <add assembly="System.Web.Mobile, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
Line 198: <add assembly="*"/>
Line 199: </assemblies>
Line 200: </compilation>


Source File: c:\windows\microsoft.net\framework\v1.1.4322\Config\machine.config Line: 198

Assembly Load Trace: The following information can be helpful to determine why the assembly 'Some.DLL.Library' could not be loaded.


=== Pre-bind state information ===
LOG: DisplayName = Some.DLL.Library
(Partial)
LOG: Appbase = file:///c:/inetpub/wwwroot/WebAppFolder
LOG: Initial PrivatePath = bin
Calling assembly : (Unknown).
===

LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Post-policy reference: Some.DLL.Library
===Errors from hell===

Do you want to know what was wrong? The Indexing Service rings any bell?

PRB: Access Denied Error When You Make Code Modifications with Index Services Running

Among my most disgusting duties is creating setup projects, mostly with Visual Studio. One thing I've stumbled upon is the way to pass arguments to Custom Actions.

Imagine you want to add parameters containing spaces like:
/dir "[ProgramFiles]" /dir2 "[MyDocuments]"
In the custom action arguments box write this:
/dir "[ProgramFiles]\" /dir2 "[MyDocuments]

That's the only way I could make it work. I still don't have any idea why.
So if you want to have a parameter with spaces in it, add a quot in front of it, but don't add one at the end. If you need to have other parameters after this one, end the quot block with backslash+quot.

Update:
Apparently, Windows Vista and its MSI engine doesn't support custom actions anymore. If you want to make your setup projects "worthy" of Vista, you should avoid using custom action.

Global.asax and Session_OnEnd

You may have already used it, but I just found out about it. There is a
global.asax file in each web project, it contains a lot of events that one
can use, like Application and Session start and end events.

Now, I tried to make Session_OnEnd to work well for the last hour, the trick
is follow these rules:
1. The session must be in InProc mode
2. In the Session_OnEnd (and Application_OnEnd) you cannot use Server,
Response or Request objects. So Map.Server will fail, for example. Also,
throwing exceptions will not cause any display on the actual page or new
pages, they just go unnoticed. This also means HttpContext.Current doesn'
work.

That is it. The Session_OnEnd event will fire on:
1. Session.Abandon
2. session timeout

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.

and has 0 comments
Using Visual Studio .NET 2003 to Redistribute the .NET Framework

It is as easy as downloading the Bootstrapper .MSI file and running it. Next
time you compile a Setup project it will include the dotnetfx.exe file and
the code required to install it on demand.

Another great tool is found here: RyanVM's MSFN Files Page
It is a switchless .NET installer. Just run it (as a custom action, for
example) and it will insure that you have .NET framework installed, no
questions asked.

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.