My Resume | Contact Me | RSS Feed | Follow Me on Twitter

Code Capers

The Ninja Coding Dojo
RSS Feed Twitter Email

How to Backup a SQL Express Database

clock March 19, 2010 by author Michael Ceranski

bigstockphoto_Hard_Disk_On_Fire_3005619sm There are a lot of programs that ship with SQL Express these days. For example, when you install development tools like Visual Studio or SharePoint it is common practice to bundle it with an express version of SQL Server.

Most of the time, SQL Express is intended to be used for small development databases. However, once a SQL instance is made available to someone they will undoubtedly start using it for other reasons. The major problem with SQL Express is that it has no SQL Agent which is generally used to schedule maintenance jobs like a full backup. Before you know it, you have a mission critical application running off your SQL Express instance with no backups.

So how do we schedule a backup without using the SQL Agent? Well, we could shut down the database services and copy the mdf and ldf files but that means we have to take an outage. If the applications running on express are mission critical then this method will not go well with your end users. Therefore our only real choice is to run a hot backup by using a batch file which passes arguments to a command line sql tool. Here is the script that I came up with:

@echo off
SET BACKUP_DIR=D:\Backups
SET SERVER=localhost

for /f "tokens=2" %%d in ('echo %date%') do (
   for /f "tokens=1-3 delims=/" %%j in ('echo %%d') do (
      set month=%%j
      set day=%%k
      set year=%%l
   )
)
set /a day=%day%-1
if %day% lss 10 (
   set day=0%day%
)
set year=%year:~2,3%
set mydate=%month%%day%%year%
for /f "tokens=1-2 delims=: " %%a in ('time /t') do set XTime=%%a%%b

sqlcmd -S %SERVER% -d master -Q "exec sp_msforeachdb 'BACKUP DATABASE [?] TO DISK=''%BACKUP_DIR%\?.Full.%mydate%.%XTIME%.bak'''


Note: Before you run this batch file you will probably want to change the BACKUP_DIR and the SERVER variables declared at the top of the file. In addition, if you are using SQL Authentication instead of windows you may want to specify the -U (login) and -P (password) switches for the sqlcmd. If you are running this on a SQL 2000 environment then you will probably need to use the osql command instead of sqlcmd. osql was replaced with sqlcmd starting with SQL 2005.

If everything goes right you should have a backup of all your databases. The files should include the database name followed by the date and time it was taken. This makes the files very easy to identify in the event that you have to perform a restore. Finally, I want to mention the fact that if you run this job on a regular frequency you will probably want to develop a routine which purges the old backups. Here is a script that I found on the Hey, Scripting Guy! Blog which will take care of that problem.



First Encounters of the MEF Kind

clock March 14, 2010 by author Michael Ceranski

One of the newest additions to the .NET 4 framework is MEF. MEF stands for the Managed Extensibility Framework and is the answer to your prayers if you are building an app that allows developers to extend its functionality by building plugins.

MEF makes the task of loading assemblies and utilizing their functionality very simple. Before we go any further there are a few basic terms that you must understand before you start using MEF:

  • The Catalog is responsible for loading assemblies. There are several types of catalogs to chose from such as DirectoryCatalog and AssemblyCatalog which we will discuss in more detail later on. 
  • The Container holds one or more catalogs.
  • The Export attribute is used to decorate objects so they can be consumed by MEF.
  • The Import attribute lets MEF know that an object is the target for one of more exported objects.
  • A part is any object that is exported or imported.

So in order to start using MEF, you need to create one or more catalogs, add them to a container and then call a method named “ComposeParts” which will search the assemblies in the catalog for “parts” which are marked with export or import attributes. In order to help understand the process better, lets look at some code..

A Real Life Example:

All the code you are about to see has been taken from my WeBlog project on Codeplex. WeBlog is a next generation blogging platform written in MVC 2 and .NET 4.0. I am using MEF in WeBlog to take care of loading widgets like Tag Clouds and search boxes. Here is a screenshot:

image

In order to get things started, I first needed to create a WidgetModel class. Here is the declaration:

public abstract class WidgetModel {
    public Guid? ID { get; set; }     
    public abstract string Name { get; }
    public string Title { get; set; }
    public Boolean ShowTitle { get; set; }        
    public string[] AllowedRoles { get; set; }

    public WidgetModel() {
        AllowedRoles = new string[] { };
    }
}


To make a widget, I inherit from the WidgetModel class and override a few properties. Then I mark the class with the Export attribute so MEF can find it later on:

[Export(typeof(WidgetModel))]
public class SiteAdminWidget : WidgetModel {
    public SiteAdminWidget() : base () {
        Title = "Site Admin";
        AllowedRoles = new string[] { "admin" };
    }

    public override string Name {
        get {
            return "SiteAdmin";                
        }
    }
}


At the heart of WeBlog, I have the WidgetManager class which is responsible for loading widgets from the assemblies. When the WidgetManager class is instantiated I call the DiscoverWidgets method. The DiscoverWidgets method creates an aggregate catalog. An aggregate catalog is used when you need to search multiple locations for parts in MEF. In this case, we used an AssemblyCatalog and a DirectoryCatalog. In particular, this code is adding the currently executing assembly to the container in addition to all the files in the Widget directory which end in “Widget.dll”. Once the catalogs are created, we add them to the CompositionContainer. Then we call ComposeParts on the container object, which finds all the objects decorated with import or export attributes.

namespace WeBlog.Extensibility {
    public class WidgetManager {
        private IDataProvider _provider = Engine.GetProviderInstance();        
        private static CompositionContainer _container;
        private const string WIDGET_PATTERN = "*Widget.dll";
        private AggregateCatalog _catalog;

        [ImportMany(typeof(WidgetModel),AllowRecomposition=true)]
        public IEnumerable<WidgetModel> Widgets { get; set;}

        public WidgetManager() {            
            DiscoverWidgets();
        }        

        private DirectoryInfo WidgetDirectory {
            get {
                return new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Widgets"));
            }
        }

        private void DiscoverWidgets() {
            //search the widget directory and also the current assembly for Widgets
            _catalog = new AggregateCatalog(
                new DirectoryCatalog(WidgetDirectory.FullName, WIDGET_PATTERN),
                new AssemblyCatalog(Assembly.GetExecutingAssembly()));
            _container = new CompositionContainer( _catalog );
            _container.ComposeParts(this);        
        }
    }
}

 

When this code executes, MEF will find the objects marked with the export attribute. In addition, MEF will also discover any objects marked with Import attributes and match them up with the exports. In my case I have three WidgetModel objects being exported and one property being imported (WidgetManager.Widgets). Since the ImportMany attribute is an IEnumerable list of WidgetModels, MEF will take all the exported WidgetModels and assign them to the Widgets property for us automatically. Alternatively, if you do not want to automatically assign objects to a property then you can always query the container yourself. Since each composable part in the container has metadata associated with it you can use LINQ to return the objects you desire.

Once the Widgets property is loaded, I can enumerate over the list and display them on the page:

<div id="page">    
    <div id="content">        
        <div class="posts">
            <asp:ContentPlaceHolder ID="MainContent" runat="server" />
        </div>
    </div>    
    <div id="sidebar">    
        <% foreach (var widget in Engine.WidgetManager.Widgets) { %>            
            <%= Html.RenderWidget( widget ) %>        
        <% } %>        
    </div>    
</div>


Just for clarification, RenderWidget is an HTMLHelper that I wrote, which is functionally similar to the RenderPartial method. It takes a WidgetModel object as an argument and displays it on the page. However, it wraps the contents of the Widget with some additional html tags that are used to delete, move and edit the widget data from the user interface.

Additional Resources

If you want to learn more about MEF then here are a few sites which you may find useful:

Finally, if you start using MEF and you get stuck then try asking for help on Twitter. While I was putting together some code for WeBlog I posted a message about MEF on twitter using the #MEF hash tag. I was very excited when Glenn Block (@gblock) responded. Glenn is the primary developer on the MEF project. In any case, it is apparent that Glenn is very passionate about MEF and very responsive to questions. He has put together a excellent library and we should all be thankful for his hard work. Thanks Glenn!



Goodbye Http Handler, Hello FileResult

clock March 7, 2010 by author Michael Ceranski

If you have been developing applications in ASP.NET MVC then you are probably familiar with the ActionResult class. The ActionResult is the most common type of object returned from an action. When building MVC apps, most of time you will use the ActionResult class.

    Last week while I was working on my open source project WeBlog, I built an HTTP Handler to serve up images. I started using an HTTP Handler for images because I needed a mechanism to prevent bandwidth leeching. The only bad thing about using an HTTP handler for images is that you end up with some pretty ugly URLS. In my case the URL ended up looking like this:

/Image.axd?image=sample.png

Luckily, my friend Ron noticed my new HTTP Handler and mentioned that I could have accomplished the same thing with a controller action that returned a FileResult instead. After a bit of investigation, I realized that Ron was absolutely right. I deleted my HTTP Handler and replaced it with this code, which was added to the Home Controller:

private string GetContentType(string filename) {
    FileInfo file = new FileInfo(filename);            
    switch (file.Extension.ToUpper()) {
        //images
        case ".PNG" : return "image/png";                                
        case ".JPG" : return "image/jpeg";                    
        case ".JPEG": return "image/jpeg";                    
        case ".GIF" : return "image/gif";                    
        case ".BMP" : return "image/bmp";                    
        case ".TIFF": return "image/tiff";
        default:
            throw new NotSupportedException("The Specified File Type Is Not Supported");
    }            
}

public FileResult GetImage(string id) {
    string path = Path.Combine(Engine.GetImageDirectory().FullName, id);            
    return base.File(path, GetContentType( path ) );
}
 

Since this code resides in my Home controller I would need to use the URL like “/Home/GetImage/sample.png” to display an image. Admittedly this URL is still a big ugly, so I decided to use a custom route to clean it up. The new custom route is named “Images” and is mapped it to the Home controller’s GetImage method. Here is the entry used in the global.asax file:

routes.MapRoute("Images",
    "Images/{id}",
    new { controller = "Home", action = "GetImage", id = "" });

Now I can display images by using the following URL:

”/Images/sample.png”

To the end user, this looks like a traditional file path. However, in reality there is no “Images” folder in the root directory. “Images” is just the name of the route being used. In reality, the image files are actually stored in the App_Data/Images folder.

By using a FileResult object with MVC you not only get a pretty URL but you also get a lot of flexibility on where you want your images to reside. You can store images anywhere you want and the URL will never need to change!



Building a Star Rating System with ASP.NET MVC and jQuery

clock March 1, 2010 by author Michael Ceranski

While working on the WeBlog project I realized that I needed a star rating system for blog posts. A star rating allows your readings to rate content based on a 0-5 scale.

image 

A fully lit star represents a full point on the rating scale. Therefore in order to give half point increments each star uses two images. 

Left off: star-left-off Left on: star-left-on Right off: star-right-off Right on: star-right-on

When you put a left and a right image together it forms a complete star. So If you have a rating a 3.5 you would have the following stars displayed: Star #1 left on, right on #2 left on, right on #3 left on, right on #4 left on, right off #5 left off, right off.

Displaying the Current Rating

In MVC, the logic to determine which stars (images) should be initially displayed is best accomplished with a HTML helper:

public static string Ratings(this HtmlHelper helper, PostModel post) {
    StringBuilder sb = new StringBuilder();
    sb.AppendFormat("<span class='rating' rating='{0}' post='{1}' title='Click to cast vote'>", post.Rating, post.ID);
    string formatStr = "<img src='/Content/images/{0}' alt='star' width='5' height='12' class='star' value='{1}' />";

    for (Double i = .5; i <= 5.0; i = i + .5) {
        if (i <= post.Rating) {
            sb.AppendFormat(formatStr, (i * 2) % 2 == 1 ? "star-left-on.gif" : "star-right-on.gif", i);
        }
        else {
            sb.AppendFormat(formatStr, (i * 2) % 2 == 1 ? "star-left-off.gif" : "star-right-off.gif", i);
        }
    }
    sb.AppendFormat("&nbsp;<span>Currently rated {0} by {1} people</span>", post.Rating, post.Raters);
    sb.Append("</span>");
    return sb.ToString();
}

This helper method builds the images based on the post's current rating. The loop, which creates the images, steps in half point increments. If the counter variable is less than or equal to the post rating then a "turned on" image is displayed. There is also logic in the loop to determine if a right or left image is displayed based on the current counter value. Once, the helper method is in place you can display the rating control with the following line of code :

<%=Html.Ratings( Model ) %>

 

User Rating Mode

When a user hovers over the stars, the control goes into "user rating mode". Instead of the stars showing the average rating it will now show the rating that the user is trying to apply to the post. So if I hover over the first half of the third star, all the images up to that point will show as turned on, and the remaining images will be turned off. In order to toggle the images on and off I used jQuery.

The following code is fired whenever a user puts their mouse over an element which uses the class name "star". All the images in the star rating control use are utilizing the “star” class. Each image element also has an attribute "value" which contains the rating for that particular element. For example the first half star has a value of .5, the second star has a value of 1 and so on and so forth. The images are then updated using the setRating function which we will discuss momentarily.

$(".star").mouseover(function () {
    var span = $(this).parent("span");
    var newRating = $(this).attr("value");
    setRating(span, newRating);
});

A similar function is used to re-draw the average rating when the user’s mouse is moved out of the control. Whenever a user leaves the control the average rating needs to be displayed again. The average rating value is stored in a rating attribute on the span that encapsulates all the images:

$(".star").mouseout(function () {
    var span = $(this).parent("span");
    var rating = span.attr("rating");
    setRating(span, rating);
});

Here is the setRating function. This function updates the images based on the rating value:

function setRating(span, rating) {
    span.find('img').each(function () {
        var value = parseFloat($(this).attr("value"));
        var imgSrc = $(this).attr("src");
        if (value <= rating)
            $(this).attr("src", imgSrc.replace("-off.gif", "-on.gif"));
        else
            $(this).attr("src", imgSrc.replace("-on.gif", "-off.gif"));
    });
}

The final piece of jQuery code is used to handle the click event. The click event is responsible for casting the vote to the server:

$(".star").click(function () {
    var span = $(this).parent("span");
    var newRating = $(this).attr("value");
    var postID = span.attr("post");
    var text = span.children("span");
    $.post("/Post/SetRating", { id: postID, rating: newRating },
        function (obj) {
            if (obj.Success) {
                text.html("Currently rated " + obj.Result.Rating + " by " + obj.Result.Raters + " people"); //modify the text
                span.attr("rating", obj.Result.Rating); //set the rating attribute
                setRating(span, obj.Result.Rating); //update the display
                alert("Thank you, your vote was casted successfully.");
            }
            else {
                alert(obj.Message); //failure, show message
            }
        }
    );
});

This code is fired whenever you click on one of the stars. The Post controller has a method called SetRating  ("/Post/SetRating") which is called using jQuery's post method. This makes an asynchronous call to the server and saves the rating to the data store. When the results are returned from the server an object is returned which contains a Boolean flag (obj.Success) indicating the data was updated successfully, an optional message (obj.Message) which can display and errors caught in the controller and a Result (obj.Result) object which contains the updated value for the number of raters (obj.Result.Raters) and the average rating (obj.Result.Rating). Here is the code for the SetRating method:

public JsonResult SetRating(Guid id, double rating) {
    try {
        if (CanUserVote(id, rating) == false) {

            return Json(new JsonResponse
            {
                Success = false,
                Message = "Sorry, you already voted for this post"            
            });
        }
        PostModel post = Engine.Posts.SetRating(id, rating);
        return Json(new JsonResponse
        {
            Success = true,
            Message = "Your Vote was cast successfully",
            Result = new { Rating = post.Rating, Raters = post.Raters }
        });
    }
    catch (Exception ex) {
        return Json(new JsonResponse
        {
            Success = false,
            Message = ex.Message                    
        });
    }
}

In the code above, there is a call to the method named CanUserVote. This code prevents users from voting multiple times on the same post by storing a cookie. Basically, all this method does is store an entry for each post in a cookie named "Votes". If the post is not in the cookie then it returns true, meaning you can vote. Otherwise it returns false.

private Boolean CanUserVote(Guid id, double rating) {
    HttpCookie voteCookie = Request.Cookies["Votes"];

    if (voteCookie != null) {
        if (voteCookie[id.ToString()] != null) {
            return false;
        }
    }

    //create the cookie and set the value
    voteCookie = new HttpCookie("Votes");
    voteCookie[id.ToString()] = rating.ToString();
    Response.Cookies.Add(voteCookie);
    return true;
}
 

Conclusion

Building a star rating system is a lot of fun. The algorithms are straightforward and jQuery makes the client side code easy to write. If you want to see the working demo then download the source from the WeBlog project. WeBlog is the open source blogging engine that I started a couple of months ago. WeBlog is written in MVC2 and NetFx 4 and relies on jQuery for the client side magic. You will need Visual Studio 2010 RC in order to compile it.



Client Side Validation with jQuery

clock February 24, 2010 by author Michael Ceranski

Validating user input on the client definitely has its advantages. It not only avoids unnecessary round trips to the server but it can also drastically improve the user experience. When I think about client side validation I think about jQuery. If you are familiar with jQuery, then you know that there are a ton a plug-ins available. Just like an Apple IPod has “an app for that”,  jQuery has a “plugin for that”. Anyway, after a quick search I discovered the jQuery Validation plugin.

There are two different ways to use the Validation plugin. The first way, is to the pure JavaScript route. This means you establish all the validation rules, messages and callback events from code. The second way is to decorate your input fields with special CSS classes. The plugin will then inspect the class attribute of each field at runtime and apply validation rules accordingly. In the upcoming example, I used the CSS approach. However, if you decided that you want to go in the other direction there are some excellent demos on the validation plugin homepage.

There are a bunch of different class names that the plugin will honor. The most basic class name is required. However in addition to checking if a field is required you can also perform pattern matching. For example my form has an email field. When someone fills out this field I not only want it to be required, but I also want to make sure that a valid email address is entered. In order to achieve this I use the class name required email. Similar validators are available for website addresses, dates, credit card numbers and more. See the documentation page for the complete list.

Here is a  screenshot of my comment form:

 image

Here is the HTML markup for my form. Notice the class names used in each of the input fields. From the html you can deduce that the full name is required. The Email is required and must be a valid address. The website field is optional but if text is entered is must be a valid URL. Finally, the comment field is required: 

<form id="comment_form" action="#">
<fieldset>
    <ul>
        <li>
            <label>Full Name *</label>                
            <input type="hidden" id="postID" name="postID" value='<%=Model.ID %>' />
            <input type="text" id="author" name="author" class="required" value="" size="40"/>
        </li>
        <li>
            <label>Email *</label>
            <input type="text" id="email" name="email" class="required email" value="" size="40"/>
        </li>        
        <li>
            <label>Website</label>
            <input type="text" id="website" name="website" class="url" size="40" />
        </li>        
        <li>
            <label>Comment *</label>
            <textarea id="comments" name="comments" rows="8" cols="60" class="required"></textarea>
        </li>
        <li>
            <label></label>
            <input type="submit" id="btnSaveComment" value="Save Comment" class="submit" />        
            <img id="ajax_loading" src="/Content/images/ajax_loading.gif" alt="loading" />          
        </li>
    </ul>
</fieldset>
</form>     


To wire up the plug-in you only need one line of code in the document.ready event:

var validator = $("#comment_form").validate();

Summary

Client side validation is a great way to enhance user experience. However, keep in mind that client side and server side validation can be used together. As always, pick the right tool for the job. For example, if you are working with mobile devices that have limited capabilities it may make more sense to use server-side validation.


Special thanks to Elijah Manor who helped me troubleshoot an issue with the validator plugin. I originally only had the id attribute on the input fields which caused some problems with validation, adding id and name is required for this plugin to work correctly.

When it comes to jQuery, Elijah is an expert. If you want more information about jQuery then you should check out the jQuery Podcast (hosted by Elijah), or follow his tech tweets on twitter. Oh, did I mention he has a website too?



About the author

MikeMy name is Michael Ceranski. I am a software developer from Buffalo NY. I have been writing code for over 10 years starting with Borland Delphi and later migrating to the .NET stack. I enjoy blogging about .NET, MVC and jQuery and I hope to spread my enthusiasm for technology by sharing my thoughts and ideas with you.

View my resume

Cumulus

This will be shown to users with no Flash or Javascript.

Sign in