Sunday, April 20, 2008
Moving House
My new address is http://seesharper.wordpress.com
Thursday, April 17, 2008
When are there just too many generics?
One of the peices of code I wrote this week was a generic entity retrieval command. I already had a command signature that looked a little like this:
internal void MyCommand : Command <TRequest,TResponse>
No problems here. A request, a response.Now this was ok, but I couldn't really get an entity of any type like this. I tried putting the type in the request as a parameter, but it didn't really work. So then I moved to this..
internal void MyCommand<TEntityType> : Command <TRequest,TResponse>
Now I've got 3 generic parameters. 1 that specifies the type of entity I'm requesting, and 1 each for the request and response types. I might be getting a bit zesty with my generics. However this lets me go and get a table from my context like so:
Table<TEntityType> myQueryTable = myDataContext.GetTable<TEntityType>
Which is nice I think, as it lends itself to almost any table that you've got mapped in your data context.
Now, in case there weren't already enough generics in my class definition, I also needed to know what type I was returning in my response! So....
internal void MyCommand<TEntityType> : Command<TRequest,TResponse<TEntityType>>
So I really still only have 3 types here, but now I have the TEntityType on the response as well. Do I have too many generics? Am I creating a readability and maintainability issue here? I'm eagerly awaiting the code review on this one actually... I'm interested to see what is said.
What do you think? 1 too many? 2 too many? What the hell am I doing? Would you have done it differently?
Friday, April 04, 2008
ASP.Net View State
- It a base64 encoded string that exists in a hidden field in the page
There is apparently significantly more to this beast than that. I'm not going to re-hash it here, as there are some really good articles on it already. I highly recommend this article in particular. When combined with the MSDN ASP.Net Page Object help it gives an excellent picture of exactly where view state sits in the scheme of a web page, and it's intented use.
Lets go with an example of why you'd use it. I have a repeater control. In the repeater list, I have check boxes for the rows, so that the users can group items for actioning. I can group items, and all is well, until I attempt to sort the list. As soon as I post back, my checks are all lost! Why?
Well, the most likely cause is that I'm binding my data to the repeater in, or after the page load.
The issue here lies in when the view state is loaded into the state bag. If you take a look at the two articles I've referenced above you'll get a more in depth discussion of this, but the short answer is to move the loading and binding of data back into the init page method. What this does is ensures all the controls that the repeater creates (in my case - the check boxes) are all in the control tree before the view state is loaded.
The reason for the second one being an issue is that even though I'm now binding in the init method, is that I'm also rebinding after I do the sort. This causes the view state that I had before to no longer be applicable. The answer here? Some custom view state manipulation. In this example, what we can do is ensure that during the databinding, the check box for each row is given a meaningful id - I used the Id of the item I was binding to. Then, when the check box is checked, add an item to the view state using the id of the check box for the key (view state is a dictionary) and the check box checked value (true, false) as the value.
The next step is to put some code into the page that will retrieve this key/value pair and set the checked value when the page is posted back. The most important thing here to remember is that you should be calling this AFTER the init. Yep, after. The reason? Well, if the init is before the view state load, then it makes sense that if you're attempting to use something that should be in the view state to wait until after it's loaded right? :)
I personally put my custom state handling in the override of the ViewStateLoad method in the page. It's important to make sure you've made the call to the base method before you do your loading though - otherwise you're still before the view state load.... :)
So that's a quick bit of info on view state. If you're unsure at all of what view state is, and when it's loaded, what it's intended for and what you should and shouldn't use it for make sure you check out that first article. It really is a highly valuable read!
Thursday, March 27, 2008
Why Blog?
When they say it's a good way to practice project management I would say it's more than just a way to practice. I would say that a blog is a way to teach. Not in a condescending sense, but as a sharing exercise. Something I've picked up recently is that there are three key tenets to learning - discover, master, influence. Blogging is a significant part of mastering, and influencing in my opinion.
The reason being that in my opinion you don't truly know something until you can successfully teach it to somebody else. Once you have that ability you have mastered the subject. You can then influence peoples thinking by guiding them in their learning while teaching. This not only reinforces your subject matter knowledge but also drives your social interaction skills, which they also mention.
So why do you blog?
Wednesday, March 26, 2008
ASP.Net AJAX Auto Complete Control Extension
Configure your script manager to allow calls to page methods...
Add the following method to your page. It's important to make sure the signature matches exactly!
Then simply add the code you need to retrieve your item list to the method body. The hook will now catch the GetCompletionList method as it should and the extender will populate as normal.
Where to next? I'm currently investigating the possibility of using the StackFrame class to branch to different methods based on the caller to this method. There is potential then to have multiple auto complete extenders on the same page across various controls.
If you've done something similar - or have a better way to do this, leave a comment and let me know. I'm sure there's a better way out there... I just haven't got there yet :)
Tuesday, March 25, 2008
MaxLengthTextBox - AJAX Control Extender
Now all you should need to do is add the extender as per any normal extender. Set a max length for your text box, and you should be good to go!
If you've got any comments, suggestions, improvements or even ideas for other controls leave a message on the codeplex page, or here on the blog.
Wednesday, March 19, 2008
ASP.Net AJAX Extenders
What's going on here is that the TextBox control is rendered in 2 ways. Normally it's rendered as an input control, which allows the max length property to work as intended. However, in multiline mode it renders as a TextArea control, which doesn't implement the MaxLength property! No good for those of us attempting to limit our user input lengths...
So how to fix it? After spending some time playing with validation controls combined with update panels I decided it just wasn't going to happen unless I started writing some script. Now I normally shudder at the possibility of working with script, but I really have to say that it's been quite pleasent this time around.
I downloaded the ASP.Net AJAX control toolkit and took a look around to see how these extenders are put together. Basically they consist of a behaviour (client script), an extender (server side code), and a designer (to allow for use in the IDE). It seems that with the toolkit, most of the hard work wiring things together is done for you. All you really need to do is define any public properties you'd like to implement in your server side code, wire them up using the provided Get and Set methods from the toolkit then get to coding your behaviour in the script files.
For my particular problem there was already a number of solutions out there, on CodeProject and also on various blogs. I've ended up with a nice mesh of a few solutions that involves filtering the key down event to check the user input once the control reaches the max length then allows or denies the key press events to continue firing. It's not quite in the wild yet, but I'm hoping it will survive the rigours of beta use and prove a worthy addition to our internal toolset.
I'm also putting together an article on how I went about writing the extender for those interested. So if that's you - watch this space :)
References:
Multiline TextBox with MaxLength Validation
ASP.Net AJAX Control Toolkit
Keyboard restriction textbox with options and ñ
Detecting keystrokes
Monday, March 17, 2008
Http Request Validation
What the good old trace told me was that my page was attempting to validate the HTTP request before it was sent to the server. It turned out the page was throwing a HTTPValidationException which due to the error model used was being swallowed by the page and subsequently presented as the more general HTTP 500 error. Below is the screen I would have got, had I not swallowed the error...
Now I knew what I was dealing with I went to take a look deeper into what was happening here. Down my stack trace there was a pointer to the Page.ProcessRequest method with the HTTPContext being passed in. What was going on was that when this method was called it was validating the request to ensure there was no potentially nasty hacker bits in there.
So - ASP.Net was being a good mother and making sure I couldn't inadvertently hurt myself by allowing people to insert HTML tags into my text fields. Wow I thought, that's pretty neat! As neat as it was though, I had to fix the error. So where to from here?
The next step was once again google. I came across a number of posts on the ASP.Net request validation process - I've linked a couple at the bottom that I think are worth a read, and in summary there is 2 ways you can handle this type of error.
1. Disable request validation on either a page by page, or application basis.
2. Handle the error gracefully in the Application_Error method of your global.asax file
Needless to say, they both have their merits. For my particular scenario, where I wanted to allow the widest possible range of input I chose to go with option 1. The problem with option 2 is that even if you do handle the error, the best you can do is hand the user back to their previous page, with or without their previously entered data and a warning not to be so naughty next time.
Even though I chose to disable the request validation in some of my pages, I still needed to cater for the possibility of script tags being inserted into text fields. Otherwise, I was vulnerable to various forms of scripting attacks. So what to do? The answer is really quite simple, use the HTTPUtility class member HtmlEncode (string Server.HtmlEncode(string)) to render the input back into it's HTML equivalent. This converts all angled brackets into their < and > equivalents and renders any attempted script pretty much useless.
There is one last gotcha to be aware of... In some controls you will need to decode the HTML back into it's character form. This can be done once again with the HttpUtility class member HtmlDecode (string Server.HtmlDecode(string)).
There are other approaches to solving this problem, and you should consider doing more than just the HTML conversion of input if you intend to turn off request validation at an application level. I suggest that you head over to the MSDN guide on preventing script injection attacks at least to take a look at some other approaches. That or let ASP.Net do your heavy lifting and validate all your requests for you!
Refs:
1. Security Practices: ASP.NET 2.0 Security Practices at a Glance
2. How To: Protect From Injection Attacks in ASP.NET
3. ASP.NET Internals – IIS and the Process Model
4. Scott Hanselman's ComputerZen.com
Saturday, March 01, 2008
Now with Vista!
Now to spend the morning re-installing VSTS, Office and all the 3rd party apps! :)
Wednesday, February 27, 2008
Multithreading is cool... Like fireworks...
See it applies in a couple of ways.
1. Threading can keep a user looking at something pretty, while a bunch of things go on below the surface like fireworks and the firemen who used to run around lighting them when I was a kid in the country.
2. Threading can be extremely powerful, but needs to be used responsibly. Otherwise, you can end up without some of your digits!
3. If you use common sense both threading and fireworks can produce really good results, with very little effort and danger.
Anywho - after our discussion it seems I had piqued John's interest as about an hour later he sent me a bunch of articles on threading which were really good reads so I thought I'd share a couple...
Threading in C# - Joseph Albahari covers a a few different ways to approach synchronisation Use Thread Local Storage - Doug Doedens which talks about thread level storage, which is a concept I hadn't heard of before but reminds me a little of the Session object in ASP.NET. The second article comes with a VB warning though :P
Sunday, February 24, 2008
Patterns and Performance
I got sent a couple of articles today from a colleague at work. One to do with the Null-Object pattern and one to do with achieving performance increases through better use of the .Net base class library.
First - the performance article. This one is an older article (Jan 2006) but is a handy one to have in the library. Having not previously read it, I was surprised by a couple of things. First of all the old String vs StringBuilder comparison. I was under the impression that it's never better to use string over StringBuilder when concatenating strings. Apparently, that's not quite right. The magic number of operations (with the caveat in this case of concatenating 25 character strings) seems to be around 7.
Of course, even if you're only doing a couple of small additions you've got future proofing to consider. Is this likely to be wrapped in some form of recursion? Is my 1 or 2 concatenation function going to be called 55 times by a higher purpose? Is that under my control?
The conclusion I've come to - though it may go against the article is that it's almost always better to use the StringBuilder. But I tend to err on the safe side...
The other article was on the Null-Object pattern. This pattern advocates the use of a class which implements all the required members of an interface - with either a default functionality or empty code block. See here or here for a more detailed description.
To me, this is really a dependent pattern. By itself I don't see much value in it. However when coupled with a factory pattern - it becomes valuable. Why? Well part of the purpose of the null-object pattern is to remove the need for object equals null checks in code. If you can't control the object however, the null check is still required as the caller/client could still potentially hand you a null object and therefore cause an exception (which is expensive - see above mentioned article!).
However - if you're using a factory of some sort to supply you an object based on an interface this solves the issue of what to do if the factory doesn't know which instance to return by giving it a default implementation. So you can then have what is basically a stub being returned to allow your code to run safely, sans null checks.
Originally, I wasn't so keen on this. It makes the code look flaky. After a chat about it, some more coffee and a bit of perhaps not so quiet reflection (I mutter when I think) I've come to see the benefits of this particular beast. It makes your code more concise. There is less code for codes sake, and more action going on – and that makes me happy :P
Saturday, February 23, 2008
Office Furniture
Brilliant.
Friday, February 15, 2008
Back in the market...
I'm also looking to try my hand at Facebook app development. So if you have a Facebook app idea that you'd like to see done, leave a comment and let me know!