Thursday, August 03, 2006

Some time ago I have posted an article about using Build Provider feature of ASP.NET 2.0 to build a strongly typed classes for accessing the files found in the application virtual directory. I myself have been using this provider ever since for every Response.Redirect(). I hope that it serves you as well.

I have found yet two more ways of using the Build Providers to make your applications safer (the second one I will describe in few days). Today I present to you, the ClassPropertiesBuildProvider. This time we get a strongly typed way to access name of the properties of our objects. When this could be usefull? Of course everywhere where we have to specify the name of the properties using a plain string. And where could that be? Mostly in data-binding expressions such as Eval and Bind.

Take for example a sample data-binding scenario where we bind a GridView control to an array of Client objects. Each client has Age, FirstName and LastName:

As you can see we get the full intellsense over available properties. Keep in mind that those properties actually return a string containing the name of the property - exact thing needed to use the Eval or Bind. Notice also that in case some property changes its name, or is deleted, we get an instant compile time error as oposite to the runtime exception you get when you use a not strongly typed Eval("Age").

Using the ClassPropertiesBuildProvider is similiar to the PathsBuildProvider. Just add extension=".cpbp" type="ClassPropertiesBuildProvider.ClassPropertiesBuildProvider" to a web.config file and put one or more file with .cpbp extension in the App_Code directory. In this file the first line declares a namespace under which the classes will be generated ("Classes" in this example). On the following line put the name of the assemblies you would like to have analyzed.

The solution is available as a source and binary here: ClassPropertiesBuildProvider.zip (57,43 KB).

As with PathsBuildProvider, the provided solution is for demonstration purposes and as such you should be aware that it might not always work as expected. If you find some bugs, or wish to provide some improvements, please feel free to do it, and contact me so I too can benefit from it :-)

kick it on dotnetkicks.com

Thursday, August 03, 2006 4:59:21 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 

While working on MyDataSourceControl (see my other articles) I have found an interesting thing. It appears that when properties of a control are set to the values provided as attributes in the aspx file, the control is not yet very functional. The most important thing that my be not set is the Parent and other control-tree related properties of the control! It seams however that it is not always so. I may be mistaken, but from my observation it is possible that sometimes the Parent property will be set before the properties defined in the aspx. If somebody can shed some light on this I will be grateful.

Thursday, August 03, 2006 4:53:45 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 

When developing stateless applications sooner or later there comes a time, when you need to store some information between requests. In technologies such as PHP and ASP.NET there is a special object to serve this function. It is called the Session object in ASP.NET. Using it is very easy, just use an indexer in a form of a string to set and retrieve some information that you want to persist between requests. Now the main problem with such an approach is the fact that it is hard to control. As an example: suppose that there are two pages using the Session object to store some state and make it accessible to each other. The simplies approach is to just use the Session object on one page to store an object and on the other to retrieve it:

Page1.aspx
Session["SomeKey"] = "some value";

Page2.aspx
object value = Session["SomeKey"];

Suppose further that there are many pages that access the value with "SomeKey" key. Sooner or later (sooner) you will lose a track of where and what is setting and retrieving this value. More over, it is hard to change since it requires you to look through multiple files - a very error prone technique.

Another solution would be to use some kind of public constant variable in place of the "SomeKey". It is better but not perfect.

A more secure solution would be to create a strongly typed class for accessing the Session object by means of properties. This way you only have to change session related stuff in one place and every braking change is detected at the compile time. Additionaly, when working with other developers, they do not have to ask you, what kind of object is available through the Session[“SomeKey”].

As a side note I would strongly encourage you to avoid Session object whenever you can. It is a hell to work with a statefull statless application :-(

kick it on dotnetkicks.com

Thursday, August 03, 2006 4:52:46 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 

There comes a time when you have to develop a page which allows its users to go back to the page they came from. Keeping in mind the statlessnes of the web applications, it is hard to tell where our users came from since every page is (or at least should be) working on its own. Suppose that on one of the pages we want to put a kind of “Cancel” button which takes users back. One possible way of doing it would be to use some client-side JavaScript such as history.back(). What if for some reason the use of JavaScript is inacceptable?

We are left with the server-side code. But there is a problem. On the server, there is no way of telling the previous page. We have to create our own solution. There are couple of possibilities here. You can use a Session or Profile object and every time a page is loaded put some information there so we have a way of checking where the user was before. You can even use a Stack object to make it possible to drill down and up as you like. This solution has however an impact on the server resources (memory occupied by the session object). Another solution uses the query url to pass the returnUrl address of page from which the users came. In fact this pattern is used every time you try to access a page which requires authorization and you are redirected to a login page. This way you save some valuable server resources and make your solution a lot more scalable.

kick it on dotnetkicks.com

Thursday, August 03, 2006 4:44:18 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [2]  | 

Have you ever wondered when is the Select method of the ObjectDataSource called in the page life cycle? It probably depends on your particular page configuration, but on an ordinary page or user control, the select method gets called after the OnPreRender method and before the OnPreRenderComplete. Keep this in mind if you want to perform some custom logic after the whole control tree has been built.

My friend has checkd the SqlDataSource control by handling the Selecting event and the he found out that the same holds true for it also.

Thursday, August 03, 2006 4:43:18 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 

I have been using MyObjectDataSource control for some time now with great success. I have however observed one thing that was missing. The missing thing was the possibility to use the container on which the control was placed as the actual TypeName object which provides the methods for Select, Insert, Update and Delete. Oh, of course it was possible before by using the TypeName and providing the name of the type that the page inherits from, but it had two major drawbacks:

  1. It required the page object to be instantiated 2 times: one for handling the request and the second time to provide an object on which the DataSource methods were called. (possible workaround was to use static methods, but then, no page state information was available)
  2. Providing a type name for a page is not so easy. It depends on few factors. By default the type name is the name of the code behind class with _aspx postfix. But it can be anything you choose by using the ClassName attribute of the Page directive in the aspx file.

So I have made some changes to the control and now if the TypeName property is not specified, the methods of the containing object are used. Further more, the same object is used as the one used to serve the request. Of course all the rest of the functionality remains unchanged. The source code and binary file is accessible here: MyObjectDataSource.zip (30,43 KB).

kick it on dotnetkicks.com

Thursday, August 03, 2006 4:38:50 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 

For all webmasters it is a bread and butter, but I have found that most ASP.NET developers are not very skilled the CSS stuff. The one thing that I often see is the lack of understanging for the position: absolute style. Many people think that what it does is positioning a given element absolutly on the page relatively to the whole page (the View Port). Mostly so, but that’s not the whole truth. By design, the position: absolute positions the elements in relation to the nearest Postioning Context. Of course by default the View Port is the nearest positioning context but this can be changed. By design, each element that is relatively or absolutely positioned becomes a Positioning Context.

One possible and often used way is to declare an element to be relatively postioned and not offsetting it so it remains in place. This way you can absolutly position elements in relation to any element you choose.

Thursday, August 03, 2006 4:34:29 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 

There is a little known feature in ASP.NET that is called the "Server-Side Comments". What is cool about this feature is that it works server side.

Using Server-Side comment is similar to using Html comment in all respects but one. ASP.NET does not process any content a block commented in such a way. This may be very usefull if what you want is to temporarily disable some part of the page and that part performs some logic other than rendering itself. Ordinary Html comment will not prevent ASP.NET from including the commented controls in the page life-cycle so your Page_Load methods will fire with Server-Side comments they will not.

Thanks to the this kind of comments you will no longer have to temporarily delete some part of the page just to make it work, because some control was throwing exceptions.

kick it on dotnetkicks.com

Thursday, August 03, 2006 4:33:37 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 

I have always wondered how practical if at all is writing the test first. Now, for me the most questionable thing was the fact that working in such a way I do not get any help from the editor. It came to me as a surprise that not only I do not miss the intellisense telling me what parameters I must pass to the method I’m about to call but I get a far more powerful feature instead...

I had already modeled the problem domain in classes. One of those classes was the User class. Now the time came to create a custom MembershipProvider that will integrate smothly with my classes. The classes of course were not created with the Membership feature in mind, so it was obvious that some methods will need to be implemented. I have started coding. At first I have created MyMembershipProvider and inherited it from the MembershipProvider class. Next I have moved to implementing each method. Suppose that I have started with nothing more than an empty User class declaration. The first method to implement on the MyMembershipProvider was the ChangePassword method. I have started typing:

Note that there are no methods to chose from, so I start typing the desired method name:

Once I get to the end Visual Studio detects that there is no such method defined on the User class and offers me an option to generate it (using the smart tag - ALT+SHIFT+F10). Of course I use the feature and what I get in the User class is a static GetUset method with two string parameters named after the variables I have used. The method also returns a user object. It also throws an Exception with message that the method is not implemented (I wonder why not the NotImplementedException). I have implemented the whole MyMembershipProvider in such a way and it went really smothly.

It is not hard to imagine what would happen if the place I first write the GetUser method is in fact a test method and the whole implementation of MembershipProvider is in fact a NUnit TestFixture. We would have a test-first written fragment of code which is what TDD is all about.

I strongly encourage everyone to try this approach. It is not only possible but it also leads to a much cleaner solution with only those methods that you really need and not the ones you think you will probably sometime use.

kick it on dotnetkicks.com

Thursday, August 03, 2006 4:26:16 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 

Recently I have argued with one of my fellow developers. On the topic was the point of validating input parameters for null values. The standard practice is for a null valued parameter (that we do not expect to be null) to throw some kind of exception: ArgumentNullException - most likely. But what if we don’t check the parameter and let the execution flow? It is possible that in the few instructions, the null reference exception will occur.

Now what is the difference between those two kinds of exception? Ultimately both signal that something went in an unexpected way. they both halt the execution of the code etc. Why bother?

There are numerous reasons why you should bother some of them include:

  • ArgumentNullException is way more meaningful when it comes to finding out the cause of the problem. For one, it allows you to specify the name of the parameter - something the automatically thrown NullReferenceException does not.
  • Throwing earlier saves both memory and processor time since if ultimately we are going to get the exception it is better to get it before executing some possibly time consuming sub-routine. Additionally it is easier to rollback since there is nothing to rollback :-).
  • It is easier to debug the code. It is just a single line where you throw “connection cannot be null”. Compare this to a line where there are multiple instructions invoked as it often happens and you wonder which one of the calls caused the exception.
  • What are you going to tell the author of the component if you happen to not have the stack trace for the exception - just message? That their component is not good :-P.
  • I personally believe that it is a shame then one of my methods throws a null reference exception.

In the extreme case, you could want to forget about exceptions altogether but what would you say if .NET Framework was written in such a way? You wouldn’t be happy yes?

As for the very good description of how you should handle exceptions I suggest reading the chapter on exceptions in Jeffrey Richter’s book.

kick it on dotnetkicks.com

Thursday, August 03, 2006 4:15:56 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [1]  |