Vault of Thoughts

2006-06-27

Please visit my new blog at vaultofthoughts.net

UrlProperty and skins

While working with my validator controls that support displaying images, I have come to a situation where I needed the image to be themable. Easy you think?


Not so easy as it should be. I have added the Themeable(true) attribute to an ImageUrl property, put a control on a page set everything in the skin file, compilled and... ??? No it didn't work. Url points to the same directory as specified in the skin file but is not prefixed with the theme folder name. A quick reflector peek at the Image control and the solution was found. There is a little known UrlProperty attribute that has to be applied to a property which we want to behave as expected when applying urls from skin files.

2006-06-21

Please visit my new blog at vaultofthoughts.net

0.(9) == 1

Yesterday I have found the post about the 0.(9) (zero, and infinite number of nines) equals 1. All of you weak at heart don't read it :-).

2006-06-20

Please visit my new blog at vaultofthoughts.net

Validation controls as images - workaround

I have been trying to make the Validation controls show an image instead of plain text in case of an error. In doing so I have used Reflector a lot.


My investigation had lead me to some conclusions and even more questions. The main problem here is that for some creepy reason, the BaseValidator inherits directly from a Label control!!! Now I have always been aware of this fact but it was until not long age when it struck me how bad decision it was on Microsoft part. Keeping the parent class in mind it should be obvious that making a Label display as an image was not going to be an easy task.


There are few possible ways in which you can make the validator control show an image instead of text. One of them is providing a img tag as a Text property for the control and it works, but is very unellegant. I thought that it is time to get to know the new feature of ASP.NET 2.0 - the Control Adapters.


After a rather long time it came out that it is not possible to use the control adapters for the validation control since some of the important logic that renders the control is in the Render method of a BaseValidator class and it cannot be easily replaced. I have left the adapter path but having learned a lot nonetheless.


Afer yet more time I have realized that the only real solutions are to either create my own classes implementing the IValidator interface - good there is such a thing or use some third party controls. I had however no spare time for writing my own fully blown controls and choosing the right toolset of third party controls is also time consuming I have decided to take a dirty shortcut.


Below is a listing of all the things I have done in my inherited validator control. Baasicaly I'm changing the TagKey to img, I'm providing a property for users to specify the ImageUrl. The rest is to trick the BaseValidator control to render image instead of a label. The important thing is that the Text property has to be something different than a null, empty or white-space string - otherwise it is possible that ErrorMessage will be rendered inside the img tags which is invalid.



protected override System.Web.UI.HtmlTextWriterTag TagKey
{
get
{
return System.Web.UI.HtmlTextWriterTag.Img;
}
}
public string ImageUrl
{
get {
return (string)(ViewState["ImageUrl"] ?? String.Empty);
}
set { ViewState["ImageUrl"] = value; }
}
protected override void
AddAttributesToRender(System.Web.UI.HtmlTextWriter writer)
{
writer.AddAttribute(
System.Web.UI.HtmlTextWriterAttribute.Src,
ResolveClientUrl(ImageUrl));
if (!string.IsNullOrEmpty(Text))
{
writer.AddAttribute(
System.Web.UI.HtmlTextWriterAttribute.Title, Text);
writer.AddAttribute(
System.Web.UI.HtmlTextWriterAttribute.Alt, Text);
}
base.AddAttributesToRender(writer);
}
protected override void
RenderContents(System.Web.UI.HtmlTextWriter writer)
{
// to prevent rendering
}
[DefaultValue("Error")]
public override string Text
{
get
{
return (string.IsNullOrEmpty(base.Text) ? "Error" : base.Text);
}
set
{
base.Text = value;
}
}

kick it on dotnetkicks.com

Please visit my new blog at vaultofthoughts.net

RuntimeObjectEditor

Few days ago I have found some tool which I can honestly say is almost as good as the famous Reflector.


The tool is called RuntimeObjectEditor and does just that: it allows you to edit your applications at runtime. Amazing! You have to check it out!

2006-06-12

Please visit my new blog at vaultofthoughts.net

ClassPropertiesBuildProvider

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


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

2006-06-06

Please visit my new blog at vaultofthoughts.net

When it isn't safe to use the Parent property of a control

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.

Please visit my new blog at vaultofthoughts.net

Minor update to MyObjectDataSource

Today I have discovered an error in MyObjectDataSource that caused NullReferenceException to sometimes appear when the TypeName was not provided. I was unable to tell what was causing the problem because on some pages the control worked fine and on the others it didn’t. Sources are available as usually here and here.

Please visit my new blog at vaultofthoughts.net

Strongly typed Session object

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

Please visit my new blog at vaultofthoughts.net

The returnUrl pattern

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

2006-06-05

Please visit my new blog at vaultofthoughts.net

When is the Select method of the DataSource called?

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.

Please visit my new blog at vaultofthoughts.net

MyObjectDataSource - update

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


kick it on dotnetkicks.com

Please visit my new blog at vaultofthoughts.net

Position Absolute -The Positioning Context

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.

Please visit my new blog at vaultofthoughts.net

ASP.NET Server-Side Comments

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

2006-06-02

Please visit my new blog at vaultofthoughts.net

Understanding TDD by implementing MembershipProvider

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

Please visit my new blog at vaultofthoughts.net

Why bother with exceptions

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

2006-06-01

Please visit my new blog at vaultofthoughts.net

Generic sort utility

I have blogged about a working alternative to the ObjectDataSource control. One of the feature provided by my solution is the InternalSort mechanism. I will provide a short description here of how it works. The source code is packed together with my data source control (here and here).


The SortUtility provides a generic capability to sort any collection of custom objects. It does so without changing the original collection. Internally it uses reflection to get the values of compared properties so in performance critical operations this utility should not be used. Otherwise it greatly simplifies development. Feel free to use it as you like and remember that feedback is always welcome.

Please visit my new blog at vaultofthoughts.net

ObjectDataSource - a working alternative

I have blogged about the problems with ObjectDataSource control and proposed two solutions neither of which was perfect. Today I will present a complete working solution. The code and .dll for this project is accessible on two external sites: here and here.


My solution deals with the problem of partially updating an object by providing a way for a developer to provide an instance of a business object on Updating event. Values read from the form are then transferred to this object. This solves the problem with properties not present on the form are reset to default because of the fact that object is constructed by the data source control. It also solves the problem with forcing the developer to provide a default constructor for each business object.


Unfortunately having to hook up to the Updating event would mean that instead of providing a default constructor, the developer would have to code the event handling method. This would not be such a big gain. Fortunately it is not necessary to provide the business object to the Update method by means of Updating event. If an object is not provided, it is retrieved using the Select method for which we already should have an implementation shouldn't we? Indeed we have, because otherwise how would we have displayed the object for editing in the first place? The only problem is that the select method should be able to accept the same number of parameters as was specified for the DataKeyNames property of the control which was bound to the data source control. This should not pose any problems since such a method will exist anyway in most cases.


Using the control is almost identical to using the ObjectDataSource control in that it requires you to specify the Select, Update, insert and Delete methods and a type name of an object providing those methods. Methods may be static or not. I wouldn't recommend using business objects for this. Rather create a separate classes to serve as a service layer for the control. Additionally the control makes a lot better use of DataObjectMethod attribute then ObjectDataSource. If a required Select, Update, Insert or Delete method name is not specified, the control will search for this method using the mentioned attribute. It will also automatically choose the method with required number of parameters. This make it super easy to build an application really fast.


The proposed solution I'm providing has one more feature which everyone should find really useful. This feature is called InternalSort and does just that - it is a generic sorting mechanism which will sort any strongly typed collection using a property specified in the sort expression. (reverse sort is also possible by adding DESC to the sort expression - ASP.NET does it automatically).


Ok, you ask: Where is the catch? One major inconvenience in using the control is that it does not have any support in form of designer. This makes it necessary work with it using the property editor. It also does not interact very well with controls such as FormView - i.e.: FormView does not generate templates given the configured data source control - like it would when used with ObjectDataSource.


If the described solution looks like it would help in developing your applications faster, feel free to use it. I only ask for one thing: a feedback. I would appreciate any kind of feedback: from "you suck" comments through "I would change this and this" to sending me free pizzas or some other stuff :-)


As a final note I have to say that while creating the control I was using the Reflector quite a lot to get to the guts of the original ObjectDataSource control and SqlDataSource. I have also used the sources of CSLA.NET by Rockford Lhotka, where there is an implementation of the DataSource control which works with the business objects of CSLA which is therefore not very generic.


kick it on dotnetkicks.com