Tuesday, August 29, 2006

Every now and then somebody just has to do it. They need to override the GetHashCode method either because overriding Equals method or for some other reason. Doing so, you should follow the guidelines provided to us by one and only Microsoft:

http://msdn2.microsoft.com/en-us/library/system.object.gethashcode.aspx

The main problem with guidelines regarding the GetHashCode method is that the change from time to time which causes some confusion.

The last change I have noticed is the fact that now GetHashCode can return different values for the same object if the state of the object that the GetHashCode relies on, has been modified. Previously GetHashCode allways had to return the same value for a given object (which caused it alomost impossible to override both the GetHashCode method and the Equals method and at the same time have a mutable object). The change to the rule makes it easier, but has some other implications...

The most important implication of having an object return a different hash code during its lifetime is the fact that no it is possible to put someting in the hashtable never to be seen again (at least not in a way we would expect it to). When this happens is when we put some value in the hashtable using some object as a key. Then we change the object so that it returns a different hash code and we have a situation where the value in the hashtable is inaccessible using the same key we have used to put it there.

As a quick example try the following code:

public class Class1
{
public override int GetHashCode()
{
return new Random().Next();
}

public static void Test()
{
Hashtable t = new Hashtable();
Class1 c1 = new Class1();
t.Add(c1, 1);
Class1 c2 = new Class1();
t.Add(c2, 2);
object o1 = t[c1];
object o2 = t[c2];
}
}

What would you expect o1 and o2 to be? Given no knowledge of the hashtable object I would expect to get what I have put earlier i.e.: 1 and 2, but I get nulls. That is because the Hashtable uses the GetHashCode method as a key to find values. Keep this in mind when overriding the nasty method.

kick it on DotNetKicks.com

Tuesday, August 29, 2006 2:04:18 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
 Wednesday, August 23, 2006

In my two previous article on relational database schemas I have described problems that arise when dealing with sql database schema that needs to be changed. I have also provided a quick tip on using Enterprise Manager to get the schema of your database. Those are the problems of relational world...

As described in the mentioned articles there are problems when it comes to keeping your database schema up to date etc. There are also problems when you need to keep the application code in sync with a database. Either you do a database-driven design and add fields in a database and then adjust the model to reflect this change, or you do a more model-driven design i.e.: the other way around - change the model and then adjust the database you always have the problem of synchronization. Tools are available that generate either a model or a database from eiher the database or the model, but is it perfect?

Far from it. One thing that I really appreciate when using Db4o is that I have no such problems. Simply because there is no database schema or in other words: the database schema reflects what I have in my model.

Now I'm not suggesting that object databases are the solution to all your problems. There are problems with data migration also however I haven't encountered one yet.

Wednesday, August 23, 2006 1:40:57 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 

As promised in my article on upgrading database schemas, I will show you the trick that I have learned when I was preparing SQL database upgrade scripts for my databases (that is before I thought on using some automation such as SQL Delta).

The fastes way I have found to get the database schema from a Microsoft SQL Server 2000 is to use the Enterprise Manager. Just navigate to a database you want, select the Tables node and select the tables you want to get schema for (you can select multiple tables using either shift or control key). As an example I have selected two tables of MyGallery database:

Having selected the desired tables use the context menu and select Copy or use the ctrl+c shortcut. Now open some kind of text editor such as Notepad. Paste the content of a clipboard and what you get is something like:

Now that is very cool isn't it? I have used this technique fo comparing two databases some time ago. Just get the schemas from two databases, save them to files on your disk and use some text diff tool.

Far from perfect but if you have no tool this is what you got. One more thing to mention is that you can use this copy and past mechanism also with stored procedures.

kick it on DotNetKicks.com

Wednesday, August 23, 2006 1:28:01 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 

Every now and then there comes a time when you release a new version of you application. Some of the new versions do not require changes to the database schema, but there are times when such a change needs to be done.

So imagine that we have an application that several hundred of our customers run. The best possible situation is that all of them have the same version of a database schema. Then we do not have to test all the possible upgrade scenarios. Mostly however there will be multiple versions of databases that are out there and you have to handle all of them.

But what is really the problem you ask? We have developers that designed the database at some point in time, created an application that was sold with that particular schema version. Then, upgrades were made, between that version and the version that we are about to release now and developers have been told to create SQL upgrade scripts so that the we can ship them with a new version. All fine if developers were doing those upgrade scripts while changing the database. Worse if you have to make a diff of the initial database schema and the desired one. Either way it was, is and always will be prone to human error. People are error prone. We, developers make mistakes, especially when doing some mindless (most of the time) activities such as comparing databases.

So, how sure you are that the database upgrade scripts that you are about to ship are the right ones? Hard question. One thing you could do is to take an initial database, run the scripts and compare the schemas. I will post a short tip on how I do it with Microsoft SQL Server 2000 Enterprise Manager. If there are errors, correct them, run the scripts again, repeat until there are no differences (or you see none).

Another problem is that the schema is not the only thing that needs to be shipped. Imagine that there is some fixed data in your database that is constant. Imagine that this data need to be altered. Same solution exists as mentioned above. Do it by hand either at the end or incrementally.

Is this solution perfect? Is it cheap? Is it time and cost effective? When you think about it you will find out that there should be some automation available. And rightfully so. There are tools that let you compare the databases, point out the differences and even create an SQL upgrade script for you. Keeping in mind what was said earlier it should be obvious that such a tool is a must have tool in every software development company that does sometime upgrade its databases.

As mentioned, there are tools that help you automate this process. I have recently found the SQL Delta application that lets you do eliminate this time consuming and error prone process of manualy generating upgrade scripts. Now if I had such a tool back when I was wasting my time making the scripts instead of solving the real business problems...

kick it on DotNetKicks.com

Wednesday, August 23, 2006 1:05:41 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
 Friday, August 18, 2006

Today I have added a little "Add to del.icio.us" link at the bottom of each article. Feel free to use it :-).

Now the technical stuff. First of, for the blog engine I'm using ThinkJot. It is an ASP.NET 2.0 port of a popular dasBlog application. As any dasBlog user should know, the engine supports macros with which you can add some dynamic content to your posts. To use them you have to edit your template and use something like <%itemTitle%>. There are plenty of macros documented on the official dasBlog site and even more macros are supported that are not documented - or at least I haven't found the documentation.

So the procedure I went through while adding a del.icio.us link was a bit painful. First of when you google for an answer what you find is mostly far from perfect. Most sites just suggest adding a simple linkt to del.icio.us and provide some parameters in the url. What I have found on the del.icio.us site was far better.

The solution from del.icio.us by default uses javascript and a popup window for adding links and if javascript is not enabled it works just as a simple link.

The hard part was to integrate the solution with the dasBlog macros engine. I have found a dasBlogExtraMacros.aspx">ready made solution. I have needed something more customizable so I have not used it however. I have editted my itemTemplate.blogtemplate file by adding something like this below the item text:

<a href="http://del.icio.us/post" onclick="window.open('http://del.icio.us/post?v=4&noui&jump=close&url='+encodeURIComponent('<%permalinkUrl%>')+'&title='+encodeURIComponent('<%itemTitleText%>'), 'delicious','toolbar=no,width=700,height=400'); return false;"> Save This Page</a>

It is basicaly the script offered by del.icio.us but I have replaced the location.href with a standard permalinkUrl macro which I think is not documented. Secondly I have replaced the document.title part with itemTitleText - my own macro that returns current item's title as text. There is of course an itemTitle macro but it is an html anchor so it cannot be used (this can be changed in the config file, but since I want my article titles to be links I could not do it).

Creating the itemTitleText macro was very easy. All I had to do is add a property to an ItemMacros class as follows:

public virtual Control ItemTitleText
{
get
{
Control control;
string title = entry.Title;
if (requestPage.SiteConfig.ApplyContentFiltersToWeb)
{
control = new LiteralControl(Utils.FilterContent(entry.EntryId, title));
}
else
{
control = new LiteralControl(entry.Title);
}
return control;
}
}

That's it. I now have a del.icio.us link :-)

kick it on DotNetKicks.com

Friday, August 18, 2006 12:15:41 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [1]  | 
 Thursday, August 10, 2006

There is a feature in Visual Studio 2005 called Code Snippets. Basically what this feature allows you to do is type in a code editor, some special string such as "prop":

And then by pressing the TAB key once (or twice if using the provided intellisense), Visual Studio generates some code for you as on the picture below:

Notice that there are reqions highlited witha green color. You can tab through those regions with a TAB key. On the above example, If you eddit the type of the field, the type of the property is automaticaly updated for you. The same holds true for the field name which is used inside the property.

Visual Studio 2005 comes boundled with a couple of useful code snippets of which I use the "prop" the most. However, If you do mostly ASP.NET applications you know that the standart property with underlying field is not so widely used here. What we need is a property which uses ViewState as a storage medium. Fortunatelly it is very easy to create your own snippets. Just go to the folder where VS is installed - for me it was: "c:\Program Files\Microsoft Visual Studio 8\VC#\Snippets\1033\Visual C#". There you will find all the available snippets. When you look any one of them what you will find is a simple xml defining the snippet behavior. From there it should be no problem to create your own snippets.

Being ASP.NET developer myself I have created few snippets that help me doing my work faster and those are: propv, propvd, props and test. First two generate a property that uses the ViewState, the third one generates a static property and the third one a method that has a Test attribute of an NUnit testing framework. You can download the snippets here: Snippets.zip (2,23 KB). Just put them together with the rest of the snippets.

As a side note I must say that I'm mostly a C# developer, but I have written my share of the code in VB.NET so I know what I'm missing using C#. One of the things that I miss is the snippet support. VB.NET comes with WAY more standard snippets and those snippets can do a lot more such as add a using statement or a reference to an assembly. There are even application that support creating snippets for VB.NET. Given the limitations of C# snippets I don't think we need such a tool at the moment :-(. Additionaly I recommend browsing the internet for more information as this article is just an overview of what else Visual Stidio can do for you if you just ask :-).


Do you own a business that requires the latest in wireless barcode scanner technology? Find this as well as a wide selection of barcode printers or a the best brands of credit card reader at the barcode experts.

kick it on DotNetKicks.com

Thursday, August 10, 2006 10:51:58 AM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [2]  | 
 Tuesday, August 08, 2006

Since I have first seen Db4o database it has became my database of choice for every personal project that I do. You can read more about this database on its home page and I strongly recommend you to do so, even if you are not planning to leave the relational world. Reading about object databases will broaden your horizons and maybe it will change the way you implement your applications as it changed mine.

Tuesday, August 08, 2006 8:09:01 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 

In the first article about optimizing rendered page size I have pointed out that you should consider using short names for content placeholders on your master pages because each control's id inside those placeholders is prefixed with the id of the placeholder. But when you look inside the page there is of course another field where you can make some improvements - the ViewState.

There are lot of articles about what you can do to make the ViewState smaller. Mainly - disable it everywhere where it isn't needed. This is a first step you can take. Amongst other things you can also use the SavePageStateToPersistenceMedium and LoadPageStateFromPersistenceMedium methods of the Page class. The purpose of those methods according to MSDN is to save and load any view state information from and to a page object. And that is true. But how to use those methods?

Browsing the results returned by google you can find plenty of solutions out there each unique in its way. Why they are different? The problem with those methods is not saving the state. To save the state you can use anything from the Session object, flat files or even database. The real problem is making sure that when a form is submited to a server, its ViewState is properly loaded - the concrete ViewState that was saved for that concrete page. A solution to just use Session["ViewState"] as a storage medium won't do, because then we can only have one ViewState for each user - no multiple windows/frames allowed.

My solution would be to include a hidden field on each page, name it somehow and use its value as a key for identifying which ViewState to load. Such a hidden field may be added dynamicaly in a base page so no additional work is required when adding new pages to a project. This field of course shoud hold some unique value (such as guid) in order to distinguish one page request from the other.

kick it on DotNetKicks.com

Tuesday, August 08, 2006 7:41:13 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [2]  | 

I'm in process of creating one web site on which I needed a checkbox but I needed it to de displayed in form of an image. So I went to google and performed a search for a ready to use control. What I have found was not satisfying at all so I have created my own and the result is available within my controls pack as along with some other controls here.

Tuesday, August 08, 2006 2:05:25 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 

I have created an ASP.NET controls pack that I'm using on a daily basis. The pack includes:

Control Name Description
Button A Button that supports a Confirmation message before submitting a form.
Image An Image that allows you to set the MouseOverImageUrl property.
ImageButton An ImageButton that supports a Confirmation message before submitting a form and a MouseOverImageUrl.
ImageCheckBox A CheckBox that renders itself as an image either checked or unchecked. It also supports MouseOverImageUrl for both states.
MyObjectDataSource An ObjectDataSource that supports build in sorting and filtering of returned objects.
CompareValidator A CompareValidator that supports displaying error messages as an image.
RequiredFieldValidator A RequiredFieldValidator that supports displaying error messages as an image.
PageParameter A parameter that can be used in DataSource controls parameter collections such as SelectParameters. It allows you to get parameters from properties of a page.
TemplateControlParameter A parameter that can be used in DataSource controls parameter collections such as SelectParameters. It allows you to get parameters from properties of a nearest TemplateControl.

I find those control very helpful on a daily basis and hope you will like it also. Note also that some of them I have described earlier but now I provide them as a one download with a full source code. It is available here: Controls.zip (50.7 KB).

Using most of the controls should be obvious. The most complicated one is the MyObjectDataSource. Mostly I have described it in my previous articles about this control. I have added a filtering feature by specifying FilterParameters on the data source control. There are two options: you can either use the internal filter mechanism which will filter values for you or by providing an additional parameter to a select method that is used for selecting objects. This additional parameter should be of type Dictionary<string, object> where the key is the name of the property to filter. Working with internal filter requires almost no code for example using ControlParameter:

<asp:ControlParameter Name="Role.Id" ControlID="Role" PropertyName="SelectedValue" />

Where Name attribute corresponds to a name of the property by which you want to filter and PropertyName corresponds to a property on a control that provides a value to filter by. (I know it my not be very intuitive, but that is what ASP.NET provides and I have been building on top of that). Filtering currently works similar to SQL LIKE command with wildcards before and after the expression.

If you work without internal filter you have the responsibility to filter the collection yourself given the filter parameter to passed to a select method.

kick it on DotNetKicks.com

Tuesday, August 08, 2006 12:06:14 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [1]  | 
 Monday, August 07, 2006

So after two days of configuration and moving my articles from my old blog I finally have my new blog set up :-). I'm still to create my own template, but for now the standard one will have to suffice.

Monday, August 07, 2006 6:55:15 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 

I haven't played with it a lot but but the most obvious was the far from complete support from the IDE. Given it is not a complete product I'm not blaming MS for it. What I blame MS for is the fact that installing LINQ is a destructive process i.e.: it damages some of the existing features of VS 2005.

For me the One thing that hurt the most was the fact that the refactoring SmartTags stopped working from a keyboard shortcut and that the Refactor option was missing from the context menu of the code window.

Since I could not imagine working without some useful shortcuts I started the process to recover the lost features. I've tried to reset the shortcuts from Tools-Options-General-Keyboard menu but it had no effect. Next I have tried to reset all settings using Tools-Import and Export Settings - no effect. Next there came Google.

I have found and that someone had a similar problem and there was a solution. Few posts from the top there is a 4 steps instruction (which didn't work for me) and than a 5th step which finally worked. I'm putting the stepps I have followed in for your convenience:

  1. Start up RegEdit.exe
  2. Open HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio\8.0\Packages\{A066E284-DCAB-11D2-B551-00C04F68D4DB}\SatelliteDLL
  3. Edit the "Path" value and change it from "C:\Program Files\Microsoft Visual Studio 8\VC#\VCSPackages\1033\" to "C:\Program Files\Microsoft Visual Studio 8\VC#\VCSPackages\"
  4. Restart Visual Studio and see if these problems are fixed?
  5. Go to C:\Program Files\Microsoft Visual Studio 8\Common7\IDE and run devenv /setup followed by devenv /resetuserdata followed by devenv /resetsettings CSharp.

All this stuff makes me wonder. I have been using beta software since I have learned using computers but I cannot remember having this kind of problems. Maybe the betas I use are not as complicated as Microsoft products but hey! They are not developed by the army of developers!

kick it on DotNetKicks.com

Monday, August 07, 2006 10:12:55 AM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 

All of us who have been using any kind of ASP.NET Templated Controls such as FormView, sooner or later come to a problem of extracting value from a field inside a template. For example when you are using a FormView control and want to programatically access a control inside one of the templates. What are the options? You have to resort to some kind of FindControl calls which are way from perfect. I have been thinking about this issue for some time now and I have an idea.

The idea is to change tha way the PageBuildProvider constructs the part of class that represents the ASPX file of your page. (the other one is of course the code behind). So what could be changed? Imagine a situation where you have a page and there is just one FormView on it. The FormView has its templates defined in an ASPX file. What happens now is the ASP.NET framework builds the part of the class given this ASPX file and what we get is a nice intellisense in the code behind telling us that the our class has a field FormView1 of type FormView which of course does not have any knowledge about controls inside the templates. But what if...

But what if instead of the FormView1 being of type FormView, the part of the class constructed from ASPX file provided us with a field FormView1 of type derived from the FormView but with few additional properties which represent controls found inside the templates - in a strongly typed manner.

Now. The benefits of such a solution are obvious mainly compile time type checking.

Is it possible to make ASP.NET 2.0 to provide such a solution? This is a hard question. I have checked the major components that are responsible for the way the classes are constructed now. I haven't gone deep into details but it it looks like some changes inside the PageBuildProvider (or some base classes) would be required. Also a ControlBuilder responsible for building a templated control would have to constuct a whole new class representing our control. I suppose that the major problem lies in constructing such a derived class with all those properties representing inner controls.

So basically I hope MS will/is thinking about making our lives easier and more type safe :-) or maybe some brave developer is willing to try to implement my concept? Either way it would be nice to have such a feature some time in the future.

Some additional considerations include the problem with accessing controls from ItemTemplate of a FormView control when in Edit mode. Another issou would be with controls such as GridView where some of the templates represent a repeating content and not a single data etc...

kick it on DotNetKicks.com

Monday, August 07, 2006 10:11:13 AM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 

I have written few times about the little known features of variuos products etc. Today I will add one more to the list. There is a little known feature that web browsers have that can be very useful...

The feature I'm talking about is the possibility to execute simple (or even complex) Javascript code from the address bar. While reading this go ahead and type something like:

javascript: alert(2+2);

in your brwoser's address bar and hit enter. You will see a messagebox containing the result of the expression passed as the argument to the altert function. A simple calculator, but you can go and create more complex scripts such as scripts modifying some DOM elements.

Here is a script that I sometimes use to get the current DOM of the page - after it has been modified by any user actions/javascripts such as AJAX calls.

javascript: var x = window.open(); x.document.write(document.childNodes[1].innerHTML.replace(new RegExp(/</g), "&lt;").replace(new RegExp(/>/g), "&gt;"))

If the page you are trying to view does not have the DOCTYPE declaration just change the document.childNodes[1] to document.childNodes[0]. I have tested this with IE 6.0 and it seems to work well. For FireFox users there are a lots of plugins available to do the same thing.

kick it on DotNetKicks.com

Monday, August 07, 2006 10:10:05 AM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 

ASP.NET 2.0 comes with a mechanism called two way databinding which allows us to declaratively bind a form element to a property of an object in such way that updates are supported. For the readonly display you typically use the Eval method in your aspx page. For the two way mechanism, you use the Bind keyword (or method?).

Using the Bind keyword is really simple in most scenarios that you encounter, especially if you are using the SqlDataSource control. Problems start to come up when you try to use a more object oriented approach and use the ObjectDataSource control.

Now, still in most cases using ObjectDataSource will not cause you any problems when what u bind is a simple property such as a name of a client i.e.: you have a collection of clients that you bind to a GridView and one of the columns displays the name of the client. To do so you use something like Bind("Name"). The problem arises when you need to bind to a subproperty such as in Bind("Address.StreetName"). This won't work unfortunatelly...

Why it is not possible to perform a two way databinding in such a way, there are discussions over the Internet. BTW: Eval("Address.StreetName") works as expected. So what can we do about it? Of course there is a solution for this problem and it has came to me when I was thinking why there is no such a problem when you use the SqlDataSource control.

The reason why there is no such problem when you are working with relational data is that you are creating an SQL query that is a VIEW of the data that you want to display i.e.: it has all the columns you need and there are no "sub-columns". So what we need to do is to translate this to an object world.

So basically what we need to do is create an object that will serv as a view on our objects and bind to this view object. For example given the aforementioned client object with a name and an address we create a ClientView object that encapsulates our client object and exposes the needed properties such as Name or StreetName. Those properties in turn call on the properties of the client object either directly as in Name or to some nested property as in Address.StreetName.

Making a select method used by the DataSourceControl to return the collection of ClientView object should not pose any problem. When using such a technique I would suggest putting the view classes somewhere outside the domain model since the only reason they exist is to allow for the two way databinding to work so there is no reason to pollute the model.

kick it on DotNetKicks.com

Monday, August 07, 2006 10:08:44 AM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 

Sometimes you really need to debug some part of the application but you don't want to start it. For example you want to debug some lower layer of the application and the startup time takes too long. There is a quick solution for this problem. You can use the Immediate Window from Visual Studio to start a debug session. Just type a class name (with namespace) and a method name you want to call if it is static. Otherwise you have to add a call to constructor in a form of "new" keyword. Just remember to put a breakpoint somewhere :-)

As far as I know this window is not available by default so use Debug/Widnows/Immediate to show it.

The sad thing is that it does not work for an ASP.NET project, but other than that you can use it not only for testing your own methods, but to call methods of the built in classes such as System.DateTime.Now.

Monday, August 07, 2006 10:07:58 AM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [2]  | 

I'm not working with threads much since ASP.NET hides almost all of this complexity from me, but then I'm not working with ASP.NET exclusively. There are times when I need to do some multi-threading. In times like this I'm very happy that there are resources such as this available on the Internet. Currently It is the best article on threading I have seen. A good read.

Monday, August 07, 2006 10:07:22 AM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 

For a long time I have been in need of a mechanism that allows me to create an instance of an object without calling any of its constructors like the Activator.CreateInstance does. All this time I have also been aware of the fact that it can be done. My motives weren't strong enough to dig dipper in to the problem, though. Until recently...

On my recent project I have enforced the use of a factory pattern for creating each object so for example to create a Document object we use something like Document.CreateDocument(). To enforce the use of this method, all classes should have a no public constructors declared. So it worked that way for some time now. Recently I have been forced to make some changes to the code and I have found the public parameterless construcor on the class that I have been modifying. A quick scope change to private and no compiler errors - good I thought. But..

Then came the runtime exceptions :-(. A quick memory refresher to remind me that the reason the public parameterless constructor is there lies in the parts of the code which use the late binding mechanisms of Reflection such as Activator.CreateInstance which throws errors in the runtime. I have used this mechanism in MyObjectDataSource control to create objects for insertion. Another place was a simple in house data mapper.

Now my motivation has been upgraded to a level that pushed me to make some investigation and after a while I've found the solution: FormatterServices.GetUninitializedObject. This thingy creates your objects without calling any constructor. Sweet! No more problems for me.

I have also checked the performance of this kind of instantiation and it is very good, much faster than Activator.CreateInstance. The only drawback is that any logic from the constructors is not invoked, but that is not a major issue for me since mostly the objects construced in such a way are data transfer objects. I also wonder WHY Microsoft controls such as ObjectDataSource does not use this technique but forces you to have the parameterless construcor?

kick it on DotNetKicks.com

Monday, August 07, 2006 10:06:38 AM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [2]  | 

Today I have been struggling with a typical table layed out page. It was a MasterPage with few ContentPlaceHolder controls - one for content, one for menu and few for other things. The problem was that the place holders were inside the td elements and some of the elements were made in such a way that they dropped shadow (background-image) and it was not possible from the content page to override this behavior (at least not in a clean way). First I have tried to override the style which made the cell to have an image at the bottom by adding the style element inside one the contents. Unfortunatelly it is not valid html to do so. Then I have thought about adding a ContentPlaceHolder inside the head element. Unfortunatelly Visual Studio does not provide the ContentPlaceHolder control in the intellisense so I thought that it will not wokr... But it did!!!

What is a very good thing to know is that despite the VS not telling you about it, you can put a ContentPlaceHolder inside the head element. You can work with it just like with any other ContentPlaceHolder by providing default content for example. It can also be used as a place for additional page level style elements. One great feature that VS DOES provide is the fact that in the content page, when you edit the head ContentPlaceHolder, you get the intellisense for the head element so you wont see any divs or other body elements there.

After this discovery I have made a search on google to find if anyone had the same problem and I have found the following: artcle.

kick it on DotNetKicks.com

Monday, August 07, 2006 9:59:46 AM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 

While working on one of the web projects in asp.net that was targeted for FireFox browser only I have found an interesting thing. Take a look at the memory consumption of a FireFox process:

Now, I wasn't doing anything unusual. Just testing how the site looks like in the browser. And I have only used 1 tab and only for this one application. Also the memory consumption got as high as 300mb in few hours. On my machine (1gb ram) FF stopped working around 500mb. So I think that is just one proof for all you FireFox lovers, that not only IE has problems :-P.

BTW: I have sat with one of the FireFox lovers from my company and tuned some caching options but it didn't help :-(.

Monday, August 07, 2006 9:57:58 AM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 

Being a curious person I have wondered how the GetHashCode method of the string class is implemented so I have performed some research. The results are interesting at least.

First thing I have checked is if the GetHashCode method for the same string say "xxx" on two separate machines returns the same value - and in fact it does. This has led me to use the Reflector to see the internals of the GetHashCode of the string class. What I have found there? It turns out that the hash code for any given string is calculated based on the characters making the string - that's why on two machines, the hash code is the same. But the question arises: how does this impact performance? A quick test has shown that for a very long string, calling the GetHashCode method can take a considerable amount of time because the result is not cached after the first call. For short strings it my not be a problem but for a larger ones? And what about a hash table with strings? There I suppose the GetHashCode is called very often.

Now I ask myself: why the hash code is calculated using the strings that the string is made of? Since strings are using the mechanism called interning (which more or less makes ensures that any particular string representation is kept in memory only in one place and string objects are only pointing to it). Given this fact, it would be orders of magnitude more performant to use the memory addres of such an interned string as a base for the hash code.

The same question araises for the Length property. It is also taking longer the longer the string, and subsequent calls are not faster.

So as for the algorithm for generating string hash code I have no idea why it uses characters and not some memory address. As for why the results of the calculation are not caches I suppose it has to do with memory consumption - caching a hash code would reqiore an additional integer variable. If anyone has some more insight on this topic, I would gladly read it - in the comments section. :-)

Monday, August 07, 2006 9:56:13 AM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [1]  | 

I have made some research on how to create a container control - a control which works in a similar way as the Panel control does. There are three key thing you have to do in order to make it work:

  • Add ParseChildren(false) attribute
  • Add PersistChildren(true) attribute
  • Add Designer(typeof(PanelDesigner)) attribute where PanelDesigner is a custom class deriving from ContainerControlDesigner. I haven't tried it, but I suppose that using the ContainerControlDesigner in with Designer attribute would also do.

It's all. You do not have to add any more code. Since, the custom PanelDesigner does not require any code, the question arises - why do we need it? Shouldn't it be some kind of attribute?

A creative usage for such a control could be for example when you need a panel control which has some kind of static content, or maybe images as borders. You get the picture.

Monday, August 07, 2006 9:54:06 AM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 

From time to time a strange thing happens to my Visual Studio - a strange line appears on the screen in a random place and stays there until VS is restarted. It is only visible in VS, when switching to other programs it disappears. Switching between windows inside visual studio does not help.

This is just one of the hidden and secret features of the VS that most people don't know about. The other one, a more common one, is the fast disappearing feature which makes VS dissapear (self terminate devenv.exe process) at random when you are working.

Monday, August 07, 2006 9:52:51 AM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 

I have used my PathsBuildProvider a while now and I have came across some issues. I have found two major issues.

The first issue had to do with the fact that from some strange reason the development web server treats root directory "/" in a different way than IIS. So redirecting to /aplicationname/page.aspx has different effect those two servers. I have made a change so that the property is not statically encoded to return a string but rather to use System.Web.VirtualPathUtility.ToAbsolute("~/Default.aspx"). As far as I know it works on both IIS and the development server.

The second issue has to do with the application name being encoded in the code as in Paths.WebTest.Default_aspx. Imagine however that you deploy your application under a different name say WebTest2. It no longer works and strange things happen. To overcome this I have changed the code to allways use the AppRoot as a root directory name.

I have also included the changes proposed by Will Gant. The changes are simple yet brilliant. He proposed that the properties returning file paths to be static. In fact that was what I have first implemented but then I have run to a problem with doing something like Paths.AppRoot.Directory1.Directory2.Default_aspx since if all properties are static than I'm not able to return anything meaningful (an object instance) from such property. Will's solution uses a fact that when you reference a directory as in Paths.AppRoot.Directory1 what you really get is not a property Directory1 of AppRoot object/class, but a namespace qualified Directory1 class name which in turn has static properties.

As usuall, the code is available here PathsBuildProvider.zip (11,13 KB).

Monday, August 07, 2006 9:48:46 AM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 

After a lot of time spent on working with the Page.ClientScript.GetWebResourceUrl method made it work and it was good. I had my ImageCheckBox control which worked well using this method. The problem occured when I have inherited from the control in another project. It stopped to properly reference the javascript from the resource url. After short investigation I have found the that the problem was caused by the call Page.ClientScript.GetWebResourceUrl(GetType(), ...); The GetType method of course returns a different type when called inside the inherited control and so, the web resource url was incorrect. A quick change to typeof(ImageCheckBox) fixed the issue.

So basically it is worth to take a minute and think when to use the GetType and when to use the typeof.

Monday, August 07, 2006 9:47:51 AM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 

I do not often rename the controls that I do not use in the code behind code, so when I place a Label on a page it most often is named something like Label1. It does not make a big difference when you are not paying for the bandwidth and you only have a few controls on a form. Imagine however that you are working with Master Page and there you are using the defau