Web Development
Hot Keys Made Simple

Hot Keys Made Simple

Previously I have blogged about how you can create keyboard shortcuts using JavaScript. In other words being able to add functionality to your web app for someone to do a ctrl+s. My previous example wasn't particularly hard and only used 10 lines of code, but this week I stumbled across a jQuery plugin that makes it easier.

http://code.google.com/p/js-hotkeys/

With this plugin, in just 1 line of code you can bind a function to a keyboard shortcut. What's more you don't even need to look up the correct keycodes as it takes a simple text parameters.

1$(document).bind('keydown', 'ctrl+c', fn);

Combine this with a function that just triggers a button click and you have some very cool advanced looking functionality written in around 5 - 10 minuets.

Creating Events in ASP.NET

Creating your own events on your own controls is something that is essential if you want you web app to work well and also provide you with reusable controls. It's easy to skip past the problem and find another way to get your code to do what you want it to do and detect the change another way. But you end up with much nicer code if your controls can have proper events for a piece of action, and you web page can have proper event handlers on each. Not only that but the code you need to write in generally a copy and past job and not that hard.

The Code

While it's not that hard, the amount of code that is needed is quite a lot more than you may expect. Fortunately though it's code you going to just re-use again and again changing small bits as needed.

1//1 - Event args (use default, but eventually pass in data through here)
2public class SaveCompleteEventArgs : EventArgs
3{
4 public SaveCompleteEventArgs(int inDataValue)
5 {
6 this.DataValue = inDataValue;
7 } //end of con
8
9 public readonly int DataValue;
10}
11
12//2 - define delegate
13public delegate void SaveCompleteEventHandler(object sender, SaveCompleteEventArgs e);
14
15//3 - define the event itself
16public event SaveCompleteEventHandler SaveComplete;
17
18//4 - the protected virtual method to notify registered objects of the request
19// virtual so that it can be overridden.
20protected virtual void OnSaveComplete(SaveCompleteEventArgs e)
21{
22 //if the UpdateData event is empty, then a delegate has not been added to it yet.
23 if (SaveComplete != null)
24 {
25 //event exists, call it:
26 SaveComplete(this, e);
27 } //end of if
28}
29
30//5 - method that translates the input into the desired event
31public void TriggeringMethod(int strData)
32{
33
34 // get new event args
35 //EventArgs e = new EventArgs();
36 SaveCompleteEventArgs e = new SaveCompleteEventArgs(strData);
37
38 // call the virtual method
39 OnSaveComplete(e);
40}

Custom Validator Error from Server Side

The built in ASP.NET validators are amazing as we all know. You just drag them on the page, tell them what control to validate, give them a summary control to list the errors and they do it. But what if there's something you need to add server side? Such as something that needs to check with the database before saving. You already have your validation summary control, so it would be nice to re-user that and have everything automatically looking the same. But it would appear there's no easy way of doing it built in, so here's an easy way of doing it... 

Creating a Custom Validation Error

First your going to need a class with some static class's that you can pass your error message to. Here I have two functions one for simply adding the error to the page and the other for adding the error to the page with a specific validation group. I am using a CustomValidator object to make this all work, another option is to implement IValidator but it's actually more effort than's needed. The other section to note is that I'm setting the Error.Text to a non breaking space (this is what would normally go next to the form field you're validating). This is because if you don't then it will default to the ErrorMessage which we only want to go into the summary. If you try setting it to a normal space it will still also default to the summary text.

1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Web;
5using System.Web.UI;
6using System.Web.UI.WebControls;
7
8/// <summary>
9/// Summary description for Validator
10/// </summary>
11public class ValidationError
12{
13
14 public static void Display(string Message)
15 {
16 Display(Message, "");
17 }
18
19public static void Display(string Message, string ValidationGroup)
20 {
21CustomValidator Error = new CustomValidator();
22 Error.IsValid = false;
23 Error.ErrorMessage = Message;
24 Error.ValidationGroup = ValidationGroup;
25 Error.Text = " ";
26
27Page currentPage = HttpContext.Current.Handler as Page;
28 currentPage.Validators.Add(Error);
29 }
30}

Now to trigger the error you just need to called the function as below:

1ValidationError.Display("Useful error message", "ValidationGroupName");

LINQ to SQL Inserts and Deletes

Inserting and Deleting records in a database using LINQ to SQL is just as easy as selecting information. What's not so easy is actually finding out how to do it. There are lots of excellent blog posts around such as this one by Scott Guthrie http://weblogs.asp.net/scottgu/archive/2007/07/11/linq-to-sql-part-4-updating-our-database.aspx, however most of them we're all written for the Beta version of LINQ to SQL which let you do a .Add() or .Remove() on your table, which was  changed on the final release. 

So to insert do something like this: 

1DataClassesDataContext dataContext = new DataClassesDataContext(); 
2
3//Create my new Movie record
4Movie movie = new Movie();
5movie.Name = "Tim's movie"; 
6
7//Insert the movie into the data context
8dataContext.Movies.InsertOnSubmit(movie); 
9
10//Submit the change to the database
11dataContext.SubmitChanges();

And to delete do something like this:

1DataClassesDataContext dataContext = new DataClassesDataContext();
2
3var movies = from m in dataContext.Movies
4 where m.Name == "Tim's movie"
5 select m;
6
7dataContext.Movies.DeleteAllOnSubmit(movies);
8
9dataContext.SubmitChanges();