Vault of Thoughts

2006-07-31

Please visit my new blog at vaultofthoughts.net

Javascript in the address bar

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

2006-07-21

Please visit my new blog at vaultofthoughts.net

Using Bind with nested properties

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

2006-07-19

Please visit my new blog at vaultofthoughts.net

Debugging with immediate window

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.

2006-07-18

Please visit my new blog at vaultofthoughts.net

The Best resource on threading

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.

2006-07-17

Please visit my new blog at vaultofthoughts.net

Creating object instance without calling its constructor

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

Please visit my new blog at vaultofthoughts.net

Master Page ContentPlaceHolder inside head element

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

2006-07-14

Please visit my new blog at vaultofthoughts.net

FireFox memory consumption

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 :-(.

2006-07-13

Please visit my new blog at vaultofthoughts.net

GetHashCode of the string class

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

2006-07-11

Please visit my new blog at vaultofthoughts.net

A custom container control

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.

2006-07-07

Please visit my new blog at vaultofthoughts.net

Visual Studio mystery line

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.

2006-07-06

Please visit my new blog at vaultofthoughts.net

PathsBuildProvider update

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 and here

2006-07-05

Please visit my new blog at vaultofthoughts.net

GetWebResourceUrl method catch

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.

2006-07-04

Please visit my new blog at vaultofthoughts.net

Optimizing rendered page size

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 defaul ContentPlaceHolder1 as a place for pages to put their contnet. Now it is only 19 characters long yes? But when you look at the generated html, you will see that each control put on a page using such a Master Page has its ID prefixed with the ID of the placeholder. A quick calculation on one of my pages and It appeared that for 100 controls on a page I was wasting 2000 characters only for the id of the placeholder!!! Just renaming the placeholder from the default ContentPlaceHolder1 to something like CPH saves 1700 characters. Such a name change does not cause any major inconvinience on the developer's part since you will rarely reference the placeholder by its ID.


The same mechanism holds true especially for controls such as GridView and UserControls which tend to have a long ID.


Currently I'm renaming all my controls that I put inside a GridView or FormView templates to one letter strings since I'm not using them. I also rename all my controls on pages to a shortest string that I can come up with without loosing the meaning.


kick it on DotNetKicks.com