Sunday, October 29, 2006

How to: Instantiate a class with a private constructor

Applies to C# (tested in VS2005)

On a recent post I talked about accessing (another's class) private methods through reflection; apparently not a lot of people was aware that this was possible. Well, here's another one for y'all, you can instantiate a class even if it's constructor is private

Here I'm including one example for a private constructor, one for protected and one for a (regular) public constructor, all of them using reflection.

Let's create our test class to play with:

public class TestClass {
private TestClass() {
Console.WriteLine("private TestClass constructor");
protected TestClass(int i) {
Console.WriteLine(string.Format("protected TestClass constructor (int:{0})", i));
public TestClass(string s) {
Console.WriteLine(string.Format("public TestClass constructor (string:{0})", s));

now let's see how easy is to instantiate this class using any of it's constructor, regardless of their visibility, all this through reflection:

- you need to include System.Reflection in your uses clause

The first one is a simple parameterless private constructor, not much is required here

//*** Private constructor
ConstructorInfo ci1 = typeof(TestClass).GetConstructor(
//*** Non public and instance (non static) constructor
BindingFlags.NonPublic | BindingFlags.Instance,
//*** No binder, no parameters, so no parameter modifiers
null, new Type[0], new ParameterModifier[0]);
//*** Call our constructor
TestClass tc1 = (TestClass)ci1.Invoke(new object[0]);
The second one is protected (you still still use "non-public" for the BindingFlags), 
it does include a parameter so we have to pass the parameter type
//*** Protected constructor
ConstructorInfo ci2 = typeof(TestClass).GetConstructor(
//*** non public and instance (non static) constructor
BindingFlags.NonPublic | BindingFlags.Instance,
//*** no binder, 1 parameter of type int, no modifiers for the param
null, new Type[1] { typeof(int) }, new ParameterModifier[0]);
//*** Call our constructor
TestClass tc2 = (TestClass)ci2.Invoke(new object[1] { 10 });
The third one is public, we could instantiate it without reflection, 
but I'll just leave it as an example. 
//*** Public constructor
ConstructorInfo ci3 = typeof(TestClass).GetConstructor(
//*** public and instance method
BindingFlags.Public | BindingFlags.Instance,
//*** no binder, 1 parameter of type string, no parameter modifiers
null, new Type[1] { typeof(string) }, new ParameterModifier[0]);
//*** Call our constructor
TestClass tc3 = (TestClass)ci3.Invoke(new object[1] { "test" });

That's it, that simple; this technique should rarely be used, more than anything I want you to be aware that it is possible and how easy it is

You could even combine the flags: BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance and it would instantiate the class if the access modifier was private, protected or public

You can find the full code here, have fun

By the way, I'm in Guadalajara now, I'll be here until Tuesday, then I'm going to Tulancingo Hidalgo and then Aguascalientes, if anyone wants to join me for dinner or just talk let me know

kick it on

Thursday, October 26, 2006

Javascript madness

Found this on Javi Moya's blog

1. Highlight the text below
2. Ctrl+C
3. Alt+D (Ctrl+L in opera) (or just go to the address bar)
4. Ctrl+V
5. [Enter]

javascript:scroll(0,0); R=0; x1=.1; y1=.05; x2=.25; y2=.24; x3=1.6; y3=.24; x4=300; y4=200; x5=300; y5=200; DI=document.getElementsByTagName("img"); DIL=DI.length; function A(){for(i=0; i-DIL; i++){DIS=DI[ i ].style; DIS.position='absolute'; DIS.left=(Math.sin(R*x1+i*x2+x3)*x4+x5)+"px";*y1+i*y2+y3)*y4+y5)+"px"}R++}setInterval('A()',5); void(0);

6. You can navigate to other sites and try it there too

7. Even better in sites with tons of pics

8. Don't go around sites just copying and pasting javascript code in your address bar! =oP

Wednesday, October 25, 2006

Escape characters to use reserved words as variable names in .NET

This post is a follow up to Jean-Paul's article: Naming variables using the variable type name (useless tip #1), from the MSDN documentation we get this (at the top of the C# keywords section)

Keywords are predefined reserved identifiers that have special meanings to the compiler. They cannot be used as identifiers in your program unless they include @ as a prefix. For example, @if is a legal identifier but if is not because it is a keyword.

.NET solved what was one of the biggest problems in the development area, which was seamless language interaction (because now every language compiles down to Intermediate Language).

Today in .NET you can write code in any .NET language and use it in any other .NET language; however, this does bring one issue, which is that reserved words in one language may not mean anything in other language, for example you might be programming in C# and you could call a variable begin, which in Delphi is a reserved word, and so when they used your C# code from Delphi they couldn't use it; to solve this problem, languages should (for their own good) implement some kind of escape character that allows you to use reserved words as variable names in case you are using code that was written in another language and they declared a variable name with the name of a reserved word in the language you are using

in C# you use the @ prefix

string @while = "something"

in Delphi you use the & prefix

&begin := 10;

in VB.NET you use brackets to delimit the keyword

Dim [Dim] = 20

let me know if you know the escape character for other .NET languages

p.s. just noticed Jeff calls them escaped identifiers

kick it on

Monday, October 23, 2006

How to: Execute (another's class) private methods

Applies to C# (Tested using C# 2.0)

The access modifier private is the most restrictive one, allowing access only to the containing type

Every once in a while we want to access a private method in some class that we don't have source code for (BCL anyone?); usually we shouldn't have to do that, but in case you need it for whatever reason, here's a way of doing it:

Lets create a test class to be used as our example:

public class TestClass {
public TestClass() {
private void HiddenMethod() {
Console.WriteLine("secret method, should only be called from the containing class itself");
private string HiddenMethodWithParams(string firstName, int age) {
return string.Format("hello {0}, you are {1} years old", firstName, age);

Basically this class is useless, because it doesn't expose any public methods... unless we had access to the private methods (okay, it's still useless, but this is just my lame example)

Now, let's see how we can access those private methods

TestClass tc = new TestClass();
Type testClaseType = typeof(TestClass);

MethodInfo hiddenMethod =
BindingFlags.NonPublic | BindingFlags.Instance);
hiddenMethod.Invoke(tc, null);

MethodInfo hiddenMethodWithParams =
BindingFlags.NonPublic | BindingFlags.Instance,
null, new Type[2] { typeof(string), typeof(int) }, null);
string result = (string)hiddenMethodWithParams.Invoke(tc, new object[2] { "Eber", 25 });
Console.WriteLine("result: "+ result);

Let's go in detail:

  1. 1- The first line just creates an instance (tc) of the class (TestClass) we're interested in (because it contain those precious private methods that we want)
  2. 2- The second line gets the type of the class, in this case it would be TestClass, this variable (testClassType) is used later on to query that class about it's methods.
  3. 3- Then it gets interesting, we acquire a "pointer" to the "hiddenMethod" private method and store it in the hiddenMethod variable; we do this by querying the testClassType variable, passing the name of the method; the parameter BindingFlags.NonPublic means you want a member which is not public (private in this case) and BindingFlags.Instance means you want an instance method (as opposed to an static one), remember that static methods don't get executed from an instance, but are called directly from the class.
  4. 4- Now that we have a pointer to the method we just need to call it, all we have to do is call the Invoke method of our hiddenMethod variable, we pass tc as a parameter, this is the instance on which we are executing the method (tc is the instance we created on the first line)

That's pretty much all we have to do, but of course a method that doesn't take any parameters and doesn't return anything is not very useful, so I included an example of calling a more complex method, one that takes parameters and returns something.

We just have to change a few things to make it work:

On step 3, where we get the pointer to the method, we need to pass information about the method's parameter types, this information is passed in an array, if you go to the top and look at the TestClass, you'll see that the method HiddenMethodWithParams takes 2 parameters, a string and an int, now let's see how we specify that:

new Type[2] { typeof(string), typeof(int) }

Which means: 2 parameters, the first one is a string, the second an int

You could (of course) pass any type of parameter here

Now we have the pointer to the method we want, but this method returns something, so we'll have to change the way we call it:

string result = (string)hiddenMethodWithParams.Invoke(tc, new object[2] { "Eber", 25 });

Here we create a variable to store the result, then we call the method, casting it's result to the type we know it returns (a string), the parameter tc remains the same, remember this is the instance on which we are calling the method, last we need to pass the parameters to the function, the way of passing the parameters is very similar to the way we specified their types

new object[2] { "Eber", 25 }

Which translates to: 2 parameters, the first one is "Eber", the second:25

That's it! try not to abuse this technique, full source can be found here

side node: while running Live Writer spell checking it suggested that I should call my test Class Testicles instead of TestClass

kick it on

Get first and last elements of an Enum

This article applies to C# 2.0

From time to time (not very often) we have an enumeration and we want certain parameter (perhaps coming from a db) to be within the bounds of our enumeration (remember that it's legal to cast any integer value into an Enum, even if the value is out of the range defined in your Enum), most of the code I have seen just checks if such value is less than the last element in the enum, something like:

enum TestEnum {

  Enum1 = 1, Enum2 = 2, Enum3 = 3;


TestEnum myValue; //this might be coming as a parameter to a function

if (myValue > TestEnum.Enum3) //some code to handle this situation

and each time you have to update the enumeration, you have to take care of changing this part of the code.

This function returns the first and last elements (not int values) of an Enum, I wrote it using generics so you can reuse it with any Enum type, you could modify this to be specific to your enum and the function could be used in C# 1.0 (VS2003), the use of the function is probably rare, but anyway, here it is

public void GetLowHighFromEnum<T>(out T lowElement, out T highElement) {
if (!typeof(T).IsSubclassOf(typeof(Enum))) //make sure we got an Enum
throw new ArgumentException("parameterized type should be Enum");
T[] values = (T[])Enum.GetValues(typeof(T));
lowElement = values[0];
highElement = values[values.Length - 1];

To use it, it would be something like:

TestEnum te1, te2;
GetLowHighFromEnum<TestEnum>(out te1, out te2);

Saturday, October 21, 2006

It is legal to cast any integer value into an Enum even if the value is out of the range defined in your Enum

I've been researching Enums recently and have found some very interesting facts about them, for example:

It is legal to cast any integer value into an enum even if the value is not defined in the enum.

this is valid:

public enum TestEnum {
Enum1 = 1,
Enum2 = 2,
Enum3 = 3


TestEnum t = (TestEnum)10; //WTF?

Consider when the value comes from another source, such as a database

If you are dealing with Enums, you should read this article by Krzysztof Cwalina, it is a very complete reference / guideline for Enums; then when you get into Nullable Enums it gets even more interesting, I'll post a few things I'm doing with Enums

Wednesday, October 18, 2006

using the mouse: did you know...?

did you know that the middle button serves the purpose of closing windows in most tabbed-document applications? (you have to click on the tab)

for example all the new browsers: IE7, Firefox, Flock, Opera, etc, implement this; but also Visual Studio, Some Notepad replacements, MSN Messenger, etc, most of the tabbed-documents applications implement this funcionality

also, on browsers, "middle clicking" on a link opens the link on a new tab

Monday, October 16, 2006

quest for a better CAPTCHA

Recently, Geoff got concerned with SPAM and the current alternatives to try to avoid it, ever since he has been working on a simpler approach (for the user) where he provides pictures instead of text, and you have to click on a few of the pictures, depending on the given instructions; while the idea is original, and it does make it easier on the user, I can see a few issues with the approach

  • images have to be downloaded to all your readers (bandwidth)
  • you have to have a considerable amount of pictures to make this usable (and more bandwidth problems associated with that)
  • Each implementation of this would have to have it's own set of pictures and rules associated with them (kinda hardcoded)
  • it's kinda big

This, however, has given me another idea, why don't we combine regular text with Geoff's idea?

we could have something like:

click on even numbers: 123641

click on mathematical symbols: 123+45/6*21

click on uppercase characters 1A654abPK

etc, the font of course can be different (and bigger), the advantages are:

  • very small
  • infinite number of CAPTCHAS can be generated programmatically
  • it's readable
  • taking some precautions it can be very clear and simple what the user needs to do (some times I can't tell if Geoff is smiling or he's angry =o( )

am I missing something, or did I just come up with the greatest idea against SPAM? =o)

if you still like Geoff's idea, I think at least the images (and questions associated with that) could be generated programmatically, e.g. lines in different angles, circles, triangles, etc, that by itself would solve most of the problems I see with Geoff's approach

anyway, time to go to sleep

Thursday, October 12, 2006

careful with commas in your SQL statements

yesterday we had a bug that was something like:

select field1, field2, field3
field4, field5
from SomeTable
where field1 = 'someValue'

can you spot the bug?

the query runs just fine, but it didn't output the desired results

the problem is that it's missing a comma between field3 and field4, thus is like saying:

field1, field2, field3 as field4, field5

which, you can imagine; you are expecting certain data (and data type) on that field on you get something else and you mis a field

this syntax I believe is Ansi 92 SQL standard, so you can get the same problem on MSSQL, MySQL, Oracle, etc (our code ran fine in MySQL and the bug came up in Oracle because we had different data)

Wednesday, October 11, 2006

Tour Guadalajara - Aguascalientes

I will be traveling on vacations to Guadalajara & Aguascalientes (Mexico) from the 28 of Oct - 6 Nov (I might go to Mexico city a couple of days), if anyone is interested in meeting there and have a geek dinner, talk about development and geek crap, leave me a message

Tuesday, October 10, 2006

Filemon is to files what ____ is to debugging

if you answered Debug View, you get a star, if you don't know about this gem, let me give you a little introduction:

DebugView is an application that lets you monitor debug output on your local system, or any computer on the network that you can reach via TCP/IP. It is capable of displaying both kernel-mode and Win32 debug output, so you don't need a debugger to catch the debug output your applications or device drivers generate, nor do you need to modify your applications or drivers to use non-standard debug output APIs.

DebugView works on Windows 95, 98, Me, 2000, XP, Windows Server 2003, Windows for x64 processors and Windows Vista.

Basically, on your code (pretty much any language that uses the standard windows libraries to output debug), for example C#, you just put something like:

Debug.WriteLine("this is freaking awesome");

you run Debug View, then you run your program (web app or whatever it is you are debugging) and that's it! you get the output in a window much like filemon shows the file activity

brought to you from the guy who doesn't see problems, only solutions

Monday, October 09, 2006

testing ThinkStar insert code plugin

I have not been happy with the plugins to insert code, my biggest problem is that they don't show up in the RSS feed, let's try this one (in german, but you can find the download link)
throw new Exception();//    TODO: Delete Me! For Testing Purposes

and, as for the code, we had to put this to show the logging capabilibites of our application, because we coulnd't get the app to throw any exceptions =o)

Friday, October 06, 2006

Using generics and anonymous delegates to populate a drop down list from a dictionary

but mostly just testing Douglas Stockwell's plugin
    private void LoadDropDownListFromDictionary<TKey, TValue>(DropDownList ddl,
IDictionary<TKey, TValue> dict,
GetNameDelegate<TValue> getName,
ConditionDelegate<TKey> getCondition)
foreach (KeyValuePair<TKey, TValue> pair in dict) {
if ((getCondition == null) || (getCondition(pair.Key)))
ddl.Items.Add(new ListItem(getName(pair.Value), pair.Key.ToString()));
and yes, you can also databind it directly using the dropdownlist.DataSource,
DataTextField and DataValueField

Tuesday, October 03, 2006

Doing the Filemon

I was looking for the some video where they show the filemon tool (I think I saw it on the hanselminutes) to pass it to some co-worker, and I found this instead, I was curious to see what he was doing with the Filemon or what was the deal, it got me laughing instead