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.

Update July 2016: This post is really old and obsolete. In it I was describing getting both attributes of DOM elements and properties of the element object, a thing that should rarely be useful. Even so, I will update the post with the better way of doing this.

First of all, looping through the properties of a Javascript object:
// for ... in ...
for (var key in obj) {
console.log(key,obj[key]);
}

// using Object.keys (IE9+) and a normal for loop
var keys=Object.keys(obj);
for (var i=0; i<keys.length; i++) {
var key=keys[i];
console.log(key,obj[key]);
}

// using the Array.prototype.forEach function (IE9+)
Object.keys(obj).forEach(function(key) {
console.log(key,obj[key]);
});

// for ... of ... from the new ES6 specification
for (var key of Object.keys(obj)) {
console.log(key,obj[key]);
}

All of the methods above are similar, but not exactly the same. For example, the for...in loop goes over all the properties of an object, including those coming from its prototype. Object.keys (the other three methods, which all basically iterate over an array) only takes the set properties of the object itself. One can determine if an object has the property or it comes from the prototype using Object.prototype.hasOwnProperty and can determine if the object has a property of any kind using
var hasProperty = (typeof obj[key] != 'undefined')
or the relatively more recent
var hasProperty = (obj[key] !== undefined)
I say relatively more recent because in some browsers the value of undefined could be set. (Note the strict inequality sign, because undefined==null, but undefined!==null).

Now that we went through methods of iterating over the elements of arrays, it's trivial to enumerate the HTML attributes of an element, because they are stored in an attributes NamedNodeMap, which even if it looks like an array, with a length property and numeric indexes, it is not. forEach doesn't work, for example.

for (var i=0; i<obj.attributes.length; i++) {
var attr=obj.attributes[i];
console.log({
index:i,
name:attr.nodeName,
value:attr.nodeValue
});
}

Note that console.log(attr) will return a string like representation of the object because for some reason attributes have a valueOf overload that turns them into a string like key="value". You can also transform the NamedNodeMap into an array using Array.from (not in IE or Opera!) then use forEach, if that's your thing.

And below is the 2006 post... yuck!

I've always needed to read the attributes of objects in Javascript for my
custom controls. Imagine a tag like this:
<span id=test1 attribute1="value">
followed by a Javascript code like this:
test1.attribute2="anotherValue";

There are two solutions for reading the attributes of an object:
1. for-in loop:
for (var name in test1) alert(name+':'+test1[name]);
2. use the attributes property (the W3C DOM way)
for (var c=0; c<test1.attributes.length; c++) {
var attr=test1.attributes[c];
alert(attr.name+':'+attr.value);
}
Or, if you are fortunate enough to know the attribute name, you can use
obj.setAttribute(name,value);
value=obj.getAttribute(name);

How nice. Now the good part, these pieces of code work differently for IE
and non IE browsers. What a surprise.
IE:
- both loops show all the properties of an object, including methods,
attributes specified in JS code or in html tags. The functions specified in
a tag are returned as [object]s.
- also setAttribute and getAttribute work the same, returning object
properties or tag attributes
FireFox, Opera and Netscape:
- the for-in loop returns only the object properties and methods, NOT the
things defined in the HTML tag
- the attributes loop returns ONLY the tag attributes
- getAttribute will only return the tag attribute while setAttribute will
change only the attributes, not the object model
- in the case that a tag attribute is automatically transformed by the
browser in an object property (like an event onchange="test();")
obj.onchange will return a function object, while
obj.getAttribute('onchange') will return a string

Therefore the only way I found to loop through all the properties of both
html tag and DOM object is by using both loops. ex:
function PassAttr(elem1,elem2) {
for (var c=0; c<elem1.attributes.length; c++) {
var attr=elem1.attributes[c];
if (attr.name.substring(0,5)=='list_')
elem2.setAttribute(attr.name.substring(5),attr.value);
}
for (name in elem1)
if (name.substring(0,5)=='list_')
elem2.setAttribute(name.substring(5),elem1[name]);
}

and has 0 comments
Ok, non IT post (rambling) about religion. Episode two from The World Sucks internationally renowned series.
Religion sucks! I mean, not only that they advertise a two thousand year old fairy tale, but they do it agressively, violently and with no taste whatsoever. And I am not even talking about stupid people blowing themselves up because some other guy told them a deity said so. I am talking about Christians. Yes, the religion of the one God who must use hidden adverts to get more followers to donate to churches all over the place, as I like to call it.

I was searching for online adventures, as my favourite game site has been down for a few days and I found this fairy tale made in flash, with things to uncover, hidden alphabets, complex storyline. I like this kind of games, so I started playing it. In no time I realized that the hidden messages were not useful in the game, but rather poetic allegories to something. Then, when I needed to fight the evil dragon, the only solution was to abandon all my weapons and face him, while a SHEPPERD was fighting the dragon and DYING FOR ME. Later I find that the shepperd has been a KING that death CANNOT HOLD. Guessed it yet? Yeees. Congratulations for winning this absurdity of a game, let the dragon consume you and join our idiotic church! The next game in the google search had a similar purpose.

Of course, this is just an example of why religion sucks, and one might argue that the moral values advertised by most religions are more important than a few zeleous spammers and their annoying actions. You might even have a point, and as there is no way to prove a god exists or not, there is no way to disprove its existence as well. Therefore I submit my point of view: the dragon is real, he takes care of us by bitting the head of dumbass religion freaks, hates spammers and burns any god to a crisp with his firey breath. What? You don't believe me? Do you have any proof that HE doesn't exist? I mean, there are a lot of freaks out there who lost their head over religion and I haven't seen any of your gods doing anything of value lately. And of course the dragon hates spammers, everyone does!

Religion sucks! It's my firm religious belief. And I have 65100 Google followers.

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

Download this nice utility from Microsoft:

Internet Explorer Developer Toolbar

Then go in Internet Explorer and add the Developer toolbar. It is very nice
for web developers and javascript programmers

Also, check this out:
Code Spy

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 :)