Tuesday, 10 May 2011

ASP.NET: Regular Expression client side date validation using "d MMMM yyyy" format

In my apps, I like to use the AJAX CalendarExtender control to allow the user to select dates from the calendar picker. I also like to allow the display of the full date format since I believe it to be more readable, for example

31 December 2012

The problem is, I find it really tough to validate this date format and even when I tried to switch to other date formats and change the localization settings in web.config, I still had no real success. I tried CompareValidators, CustomValidators and various combinations of RegularExpressionValidator but simply could not get it to work.

Eventually, I found a regular expression which pretty much does the trick. I don't believe it’s over-engineering the solution, because I could not find another solution which works.

Basically I added the regular expression to my web.config file so that it was only listed in one place, should I need to change it. Then I created a little shared function which returns the RegEx, and on Page_Load I set the ValidationExpression property of the RegularExpressionValidator controls to the result of the function, and therefore to the RegEx.

Here's the code:
Page Markup


<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

<asp:TextBox ID="txtStartDate" runat="server" AutoPostBack="true" ></asp:TextBox>
<asp:CalendarExtender ID="calStartDate" runat="server" TargetControlID="txtStartDate" Format="dd MMMM yyyy"></asp:CalendarExtender>

<asp:RegularExpressionValidator ID="reValStartDate" runat="server" ControlToValidate="txtStartDate"
ErrorMessage="Enter a valid date" ></asp:RegularExpressionValidator>

Code Behind

Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
reValStartDate.ValidationExpression = UIUtils.DateValidatorRegEx()
End If
End Sub

''' <summary>
''' Return the regular expression used to validate dates
''' </summary>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Function DateValidatorRegEx() As String
Return ConfigurationManager.AppSettings("DateValidatorRegEx")
End Function

Web.Config

<add key="DateValidatorRegEx" value="^(?:((31 (January|March|May|July|August|October|December))|((([0-2]\d)|30) (January|March|April|May|June|July|August|September|October|November|December))|(([01]\d|2[0-8]) February))|(29 February(?=-((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))) ((1[6-9]|[2-9]\d)\d{2})$"/>

This solution isn't perfect, because the above validator does not allow for leap years (i.e. 29 February 2008 was a valid date), and I don't really like having to explicitly bind the ValidationExpression property of every date validation control in the code behind. I think it would have been better to set the ValidationExpression in the markup and directly reference the function result, but I couldn't get that to work. Apparently you can use a CodeExpressionBuilder to set server side control properties using code blocks, but I felt that would be over-engineering the solution.

Anyway, I hope this is of use to someone. I'll certainly be using this method in future projects.

Friday, 28 January 2011

HTC Desire HD turns itself off: Solved!

I recently bought an HTC Desire HD to replace my iPhone 3GS.
It's an excellent phone in many ways, but has one or two flaws. When on a business trip I set my alarm for the next morning and left it switched on and plugged into the charger. I had never used the Alarm Clock app before.

Since I had been caught out recently by the iOS alarm clock bug on January 1 and 2, I didn't entirely trust that the alarm would go off.

My mistrust was well placed, and it was lucky I set the bedside alarm too, because the phone alarm didn't go off. The phone's power had cut out.

When I turned it back on, much to my dismay the phone kept turning itself off at random every 20-30 minutes and for no apparent reason. I couldn't figure out what was going on and thought maybe it was something to do with a loose connection in the phone or the battery.

I was about to send the phone back under warranty, and thought I should really spend some time to see if I can find the answer before going to the trouble of being phoneless for a few days while it gets fixed.

So I eventually stumbled across the answer on AndroidForums (The link takes you to the main page because I found the post last night and since haven't been able to locate it).

1. Turn phone off and remove the battery, SIM, and memory card.
2. Leave the phone for a minute and put the memory card and battery back in (not the SIM).
3. Turn back on, allow to boot and then switch off again.
4. Take the battery out again, wait a moment and put back in with SIM too. Turn on.

Apparently this type of reboot clears out some files that a normal restart wont, and causes certain programs that are set to start (and that could be the cause of the issue) to be disabled.

I'm not sure if the Alarm Clock was the problem, but it seems a coincidence that this happened after the very first time I had set an alarm on the phone.

Anyway, I found that not only did this simple fix solve my issue and thus prevent me from having to send the phone back, but the Desire HD started working at lightning speed after this!

Result!

Friday, 7 January 2011

SSIS: Mapping parameter inside of a Execute SQL Task, OLE DB Source Component or Datareader component

In trying to use SSIS for some ETL, I wanted to be able to pass variables about in my packages to use in updating the status of tasks in a SQL Server database.

I got my package to set a variable to the result passed OUT of a stored procedure, but I could not get it to work when trying to pass variables IN to a stored procedure. I kept getting errors such as "The query failed to parse. Syntax error, permission violation, or other nonspecific error".

I spent hours trying to get it to work.

It would not work.

It drove me nuts.

Then I found this post on Rafael Salas' blog which, ten minutes after reading, led me to the answer to my problem and a working DTSX package.

Basically all that's involved is creating another package variable to contain the SQL you want to use, then evaluating it as an expression which allows you to use your other variables in the SQL and to execute the stored procedure as desired.

There's nothing quite like seeing those DTSX package tasks lighting up green as it runs successfully!

Thursday, 6 January 2011

SQL Server Business Intelligence Development Studio 2005: Variables Window Invisible

When trying to create a DTSX package in SQL Server Business Intelligence Development Studio 2005, I was looking to add a variable to assign to the result of a stored procedure.

When I clicked the SSIS menu option and chose Variables or right clicked on the DTSX designer surface and chose the same option, nothing at all happened. It quickly drove me nuts and no matter what I did, I could not get the damned Variables window to appear!

Then finally I opened the Window menu and clicked Auto Hide All. When I did this, the Variables window appeared next to the Toolbox and stayed visible when I reopened my project!

Who knows why this happened, but if you happen to be struggling with this obscure issue then hopefully this solution will work for you.

Saturday, 18 December 2010

D-Link ShareCenter Pulse and Microsoft Sync Toy: Automatically sync files and folders in Windows

Since I had no decent way of backing up my files and photos other than using an Internet based service, I recently bought a NAS box, namely the D-Link ShareCenter Pulse DNS-320 for £69.99 from Amazon (the price seems to have gone up since I bought it). See this review.


My first impressions after a few days are that it's a brilliant unit which comes with an iTunes server, uPnP server for streaming to PS3, Xbox 360 etc and also a built in BitTorrent client for downloading files without the need for a power hungry PC.

It doesn't come with drives (which you'd expect at that price) so I put a 500GB SATA disk in which is more than enough for my needs just now. It's very quick to set up, and within an hour or so I had it ready to accept my files and it was streaming my iTunes and AV library on the LAN to the PC, PS3 and 360.

But the problem I had was that I wanted to back up certain folders on my PC to the NAS without having to copy things manually. Ideally I wanted a utility that would monitor certain folders and if their contents changed, the changes would be mirrored between my PC and the NAS box. After some Googling around, I found a nice straightforward solution which does exactly what I needed: Microsoft SyncToy.

It's free, and is a very straightforward utility that you can use to sync folders automatically. You just pick the folders you want to sync, decide whether changes should be reflected on both devices or just one way, and off you go. It will mirror the two folders and any changes you make to one will be reflected in the other.


So now if I copy photographs onto my PC, as long as the NAS box is up and running the pictures will be mirrored to the folder on the NAS.

Wednesday, 29 September 2010

ASP.NET: Web Application Spell Checking with jQuery and AtD (After the Deadline)

Why did I need it?
In a recent project, we had a very large form with wizard steps and several multiline text area controls. The form was submitted to senior managers, so the requirement was raised to provide some kind of automated spell checking functionality.

Given that this is a web application, it wasn't obvious which solution to choose. You can ask you users to install browser plugins which will check spelling, but this isn't really pratical since very few people would actually do it. Or you can install a full third party application on your server and use some kind of AJAX call to check spelling.

If a spell checker does not make good suggestions to fix spelling or grammar mistakes, then it becomes pointless. So we needed something with a good comprehensive dictionary and it had to be quick.

After some rooting around and consideration of third party products and also possibly somehow piggybacking on SharePoint's spell checking service, I found a product called AtD (After the Deadline).

What is AtD?
AtD is an open source solution which you can plug into your website using the wonderful jQuery (though it also offers other spell checking methods). It seems like an odd name to me, but apparently AtD is named after a similarly titled blog in the New York Times.

It's a fantastic product and only takes a short time to set up. Using the jQuery version which I chose, it runs client side and will highlight spelling and grammar errors, and provide a good set of suggestions to fix them. It's quick, user friendly and it even works in IE6. Use this link to download the source code and view a couple of tutorials, though the tutorial I found most valuable was this one:

Demo 3

Here is Demo 3 in action:

You can use that page to try out AtD for yourself, and if you view its source you can follow the simple step by step instructions to get started.

There are tutorials on the site, but basically you either link to the source code and css, or embed it in your project, use a little bit of jQuery code to assign the spell checker to each textarea on your page, do any layout customisations you need and wham bam - it works. You don't need to add any markup to your existing page, the jQuery will do the legwork for you.

It wasn't all plain sailing…
I did have a small problem in getting up and running with AtD. What's the problem I most often come up against in web development? That's right, Internet Explorer.

Basically the issue was in getting the spell checker buttons to float to the right hand side of the textarea controls (to me, this seems the most obvious place to put them), but by default AtD will add the spell checker button to the top right hand side of the textarea using a dynamically rendered span element.

I thought it'd be easy to get the spell checker button to sit where I needed it simply by modifying the css to make the spelling button float to the right of the textbox. This worked perfectly in Firefox, but in IE when you float the button, the onclick behaviour inexplicably stops working, thus rendering the whole thing useless. That was no good.

Of course, you can edit the css used to render the AtD elements. So I played around with it for a while and ended up changing the default CSS for the spelling buttons to look like this:


.AtD_proofread_button
{
width: 14px;
height: 14px;
background-image: url('../images/writing.gif');
margin-left: 465px;
position: absolute;
}
.AtD_edit_button
{
width: 14px;
height: 14px;
background-image: url('../images/editing.gif');
margin-left: 465px;
position: absolute;
}

I removed the display:block property, added position: absolute and added a left margin which is roughly equivalent to the width of the textarea controls in my project. This meant that the buttons sat nicely alongside the textboxes, and the absence of a float property meant that IE and Firefox would render the whole thing nicely.

Conclusion
After the Deadline makes for a superbly straightforward and lightweight spell checking solution for web applications which adds real value. I'll certainly be using this in any future web project where spell checking is required.

Friday, 24 September 2010

ASP.NET: Limiting the length of a multiline textbox

ASP.NET comes with a lot of nice validator controls which save you the hassle of writing a lot of JavaScript components yourself.

The TextBox control has a MaxLength property which allows you to easily restrict the length of the input. But bizarrely, a TextBox with its TextMode property set to MultiLine does not have this property.

But of course, you still need a way to limit the amount of text input or your database operations could fail.

Previously, I was using a JavaScript function attached to these textboxes with a function which was fired on keyup or lost focus which counted the number of characters and prevented overflow of a maximum set amount.

That's the long way of doing it though: you can achieve the same validation using a RegularExpressionValidator, as highlighted on this post by Raj Kaimal.

Fundamentally, you create a RegularExpressionValidator control, point it at your multiline textbox and set this as the RegEx (300 in this example obviously being the maximum number of characters allowed):

^[\s\S]{0,300}$

Et Voila! A simple and elegant solution - and no custom JavaScript required!

Thursday, 16 September 2010

ASP.NET: InvalidCastException from Strongly-Typed DataSet (XSD)

This one has had me tearing my hair out for months.

In most of my ASP.NET projects I would have an XSD DataSet which models my database schema and acts as the data access layer for the application. But in several situations I would get unbelievably annoying exceptions from the designer file whenever my code attempted to get a boolean or date value from the database which was null. You would receive an exception like this:

StrongTypingException was unhandled by user code.

The value for column 'abcdefgh' in table 'tblAbcdef' is null.

My first step was to open the Properties of the column in the XSD designer and make sure that the AllowDbNull property is set to true. Then in the NullValue property I tried to change the behaviour from (Throw exception) to (Empty) or (Nothing). But Visual Studio blew up in my face and informed me that my selection was invalid.

'Fine' I thought, 'I'll just check the value for DbNull before trying to set it in my code'. But when I tried to do such an IF statement, the StrongTypingException would still occur because before my expression tried to evaluate the column value, the designer would throw the StrongTypingException, thus never allowing the evaluation to take place.

I couldn't find the answer to this, until a much smarter colleague pointed out the extremely simple answer. The designer file catches a InvalidCastException and then throws a StrongTypingException. So in my own code, I just need to catch the StrongTypingException and ignore it - assuming that ignoring it is the correct thing to do in that piece of code. I had been trying to catch the InvalidCastException which of course is incorrect because the designer had replaced that with the other exception type.


Try
.ClientContact = dbRecord.ClientIsStudent
Catch ex As Global.System.Data.StrongTypingException
' Ignore since these are generated from the typed DataSet designer
End Try


This worked and I am delighted to finally have the answer to this problem which has been bugging me for ages!

If I had actually read the designer file code I might have spotted that it throws a different type of exception to the one I was trying to catch.

Friday, 3 September 2010

ASP.NET: Failed to access IIS metabase (IIS)

When installing everything on my new machine, came across a problem in IIS when publishing my projects there. I got the error:

Failed to access IIS metabase
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code

The error directs you to a Microsoft KB which isn't particularly helpful.

I had seen this error before when using SQL Server Reporting Services but the method I used last time works for SSRS, but not in this case. After a bit of Googling I found that this is a problem with the account permissions that ASP.NET runs under in IIS, as well as a method to solve it.

1. Gave permissions to the ASPNET account using "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis –ga machinename\ASPNET".
2. Reset IIS (iisreset on command line) and that resolved the issue for ASP.NET 2.0.
3. We registered ASP.NET 1.1 with IIS as well using command "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\aspnet_regiis –i".
4. Reset IIS again.

That did the job for me. Some other people had to go to greater lengths such as uninstalling .NET and reinstalling it, but the above steps resolved the problem in my case.

Tuesday, 31 August 2010

Solved: Lenovo ThinkPad W510: High pitched squealing noise

I recently got a Lenovo ThinkPad W510 laptop, which is a bit of a beast (PC Advisor Review). There's an Intel Core i7 CPU running at 1.73 GHz, 3GB RAM and a nice 15.6" LED Screen. It's very well put together and feels like it will last for a long time, especially with the hard disk shock detection technology which turns off your hard drive if the chassis detects that the machine is dropped onto the ground

However, I had an issue with the laptop where it would make a constant high pitched squealing noise, almost so high pitched that only dogs would hear it, but unfortunately not quite.

I thought I could live with it but when you're sitting next to it for 7-8 hours a day and the sound is drilling into your mind, it becomes quite annoying. But fortunately, unlike many others who had the same problem, the answer proved to be achievable without making any support phone calls or having any parts replaced.

There's a very comprehensive suite of Lenovo settings which are preinstalled on the machine, and in particular there's an application called Power Manager.

Since it's a high performance machine designed for development or graphics editing and therefore has heavy battery usage by default, it gives you fine grained control over the balance between performance and power. You can slow down the CPU, dull the screen and switch off optical drives if you're running on battery power, and when you're on AC you can disable all that and let it run at full tilt.

These types of controls are nothing new, but in there was the answer to my squealing problem.

As part of Power Manager, there's a setting called 'Deep Sleep' which is some kind of CPU power management function. This was the cause. So I created a new 'power management profile' within the Power Manager applet and set Deep Sleep to off, then saved it.

After activating my new profile, the noise immediately went away! Thank goodness for that, because I had to get rid of the noise one way or another before it drove me nuts.