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.

$(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.

Advertisements

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.

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

/// <summary>
/// Summary description for Validator
/// </summary>
public class ValidationError
{

    public static void Display(string Message)
    {
        Display(Message, "");
    }

  public static void Display(string Message, string ValidationGroup)
    {
  CustomValidator Error = new CustomValidator();
        Error.IsValid = false;
        Error.ErrorMessage = Message;
        Error.ValidationGroup = ValidationGroup;
        Error.Text = "&nbsp;";

  Page currentPage = HttpContext.Current.Handler as Page;
        currentPage.Validators.Add(Error);
    }
}

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

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

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 - Event args (use default, but eventually pass in data through here)
    public class SaveCompleteEventArgs : EventArgs
    {
        public SaveCompleteEventArgs(int inDataValue)
        {
            this.DataValue = inDataValue;
        } //end of con

        public readonly int DataValue;
    }



    //2 - define delegate
    public delegate void SaveCompleteEventHandler(object sender, SaveCompleteEventArgs e);

    //3 - define the event itself
    public event SaveCompleteEventHandler SaveComplete;

    //4 - the protected virtual method to notify registered objects of the request
    //	virtual so that it can be overridden.
    protected virtual void OnSaveComplete(SaveCompleteEventArgs e)
    {
        //if the UpdateData event is empty, then a delegate has not been added to it yet.
        if (SaveComplete != null)
        {
            //event exists, call it:
            SaveComplete(this, e);
        } //end of if
    }

    //5 - method that translates the input into the desired event
    public void TriggeringMethod(int strData)
    {

        // get new event args
        //EventArgs e = new EventArgs();
        SaveCompleteEventArgs e = new SaveCompleteEventArgs(strData);

        // call the virtual method
        OnSaveComplete(e);
    }

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: 

DataClassesDataContext dataContext = new DataClassesDataContext(); 

//Create my new Movie record
Movie movie = new Movie();
movie.Name = "Tim's movie"; 

//Insert the movie into the data context
dataContext.Movies.InsertOnSubmit(movie); 

//Submit the change to the database
dataContext.SubmitChanges();

And to delete do something like this:

DataClassesDataContext dataContext = new DataClassesDataContext();

var movies = from m in dataContext.Movies
                  where m.Name == "Tim's movie"
                  select m;

dataContext.Movies.DeleteAllOnSubmit(movies);

dataContext.SubmitChanges();