jQuery Quick Tip: Extract CSS Background Image

jQuery allows you to get the background image of any element on a web page:

$("#myelement").css("background-image");

However, this returns it in an undesirable format: url(http://example.com/images/image.jpg) or url("http://example.com/images/image.jpg"). With a bit of string replacement, you can get extract the URL:

function extractUrl(input)
{
 // remove quotes and wrapping url()
 return input.replace(/"/g,"").replace(/url(|)$/ig, "");
}

So now you can just do this:

extractUrl($("#myelement").css("background-image"))

Which will return the URL on its own http://example.com/images/image.jpg.

ASP.NET Snippet: Delete All Users and Roles

Deleting all users and related data from a site using ASP.NET authentication is fairly simple. Useful if copying a database and you want to remove all the users, but keep the structure and other data (e.g. user content) intact.

Delete all users:

foreach (MembershipUser u in Membership.GetAllUsers())
{
 Membership.DeleteUser(u.UserName, true);
}

Delete all roles:

foreach (string role in Roles.GetAllRoles())
{
 Roles.DeleteRole(role);
}

ASP.NET Snippet: Quick Password Reset

Here is a simple way, via code to reset a password when you are using the built-in ASP.NET authentication system. Useful if you either don’t have a reset password form, or you just want to quickly change a password. Create a blank page, and place in the code behind Page_Load event.

C#

    protected void Page_Load(object sender, EventArgs e)
    {
        MembershipUser u = Membership.FindUsersByName("Username")["Username"];
        u.UnlockUser();
        u.ChangePassword(u.ResetPassword(), "newpassword");
    }

VB

    Public Sub Page_Load(sender As Object, e As EventArgs)
        Dim u As MembershipUser = Membership.FindUsersByName("Username")("Username")
        u.UnlockUser()
        u.ChangePassword(u.ResetPassword(), "newpassword")
    End Sub

Just delete the page when done.

Update (8 July 2009): If a question and answer is required when you create a user, you have to pass on the answer to u.ResetPassword, e.g. u.ChangePassword(u.ResetPassword("answer"), "newpassword"), otherwise ResetPassword won’t work.

jQuery Validation Plugin Tip: Highlight Field

The validation plugin for jQuery is a very useful plugin for validating forms before they are submitted. This tip shows you how you can highlight the field if there is an error with it.

var validator = $("#myform").validate({
 onblur: function(el)
 {
  if(validator.check(el))
   $(el).removeClass(validator.settings.errorClass);
  else
   $(el).addClass(validator.settings.errorClass);
 },
 onkeyup: function(el)
 {
  if(validator.check(el))
   $(el).removeClass(validator.settings.errorClass);
  else
   $(el).addClass(validator.settings.errorClass);
 }
});

This adds the errorClass (normally ‘error’) to the field being validated, which can then be styled via CSS:

input.error { border: 1px solid #c00; background: #fee }