Using KnockoutJS with SignalR in ASP.NET MVC

KnockoutJS is a MVVM implementation for JavaScript written by Steve Sanderson, in my opinion the author of the best ASP.NET MVC textbooks available. Simply put it lets you bind a JavaScript object model to your HTML UI using a Read more

A MongoDB Tutorial using C# and ASP.NET MVC

In this post I'm going to create a simple ASP.NET MVC website for a simple blog that uses MongoDB and the offical 10gen C# driver. MongoDB is no NOSQL database that stores information as Binary JSON (BSON) in documents. I Read more

Linq To SQL Tutorial

Check out some of my other Linq to SQL posts: EntityBase Inheritance Modifiers with SQLMetal Linq to SQL with WCF Services Linq to SQL Framework (Repository/Business wrapper) ObjectDataSource binding with server side paging and sorting Load Options Generic Framework using reflection This is a basic tutorial for Read more

Recursive FindControl Extension Method

Posted on by Joe in ASP.NET, C# | Leave a comment

When working with templated controls it’s quite common to need a recursive FindControl method to navigate down through the control hierarchy to find the control you want.

Here is a simple extension method I wrote for Control to do this:


public static Control FindControl(this Control ctrl, string id, bool recursive)
{
    if (recursive)
    {
        foreach (Control child in ctrl.Controls)
        {
            if (child.ID != null && child.ID.Equals(id))
            {
                return child;
            }

            if (child.Controls.Count > 0)
            {
                Control found = FindControl(child, id, true);
                if (found != null)
                {
                    return found;
                }
            }
        }
    }
    else
    {
        return ctrl.FindControl(id);
    }

    return null;
}

CheckBoxList ListBox SelectedItems Extension Method

Posted on by Joe in ASP.NET, C# | Leave a comment

I’ve been working with the CheckBoxList control and it’s annoying there is no property to get the selected items.

I wrote a simple extension method for ListControl, the abstract class that CheckBoxList and ListBox derive from, to get the selected items:


public static ListItemCollection GetSelectedItems(this ListControl source)
{
    ListItemCollection selectedItems = new ListItemCollection();

    foreach (ListItem item in source.Items)
    {
        if (item.Selected)
        {
            selectedItems.Add(item);
        }
    }

    return selectedItems;
}

I could loop through the selected items like so:

foreach (ListItem item in myCheckBoxList.GetSelectedItems())
{
    //Do something with the item
}

It would be even better if Microsoft implemented extension properties so that I can loose the parenthesis.

ObjectDataSource Exception Handling

Posted on by Joe in ASP.NET, C# | Leave a comment

I was using the ObjectDataSource today to display and delete data using a GridView.  When I tried to delete a record that was referenced in another table an exception was thrown due to referential integrity.

I found that in implementing the Deleted event of the ObjectDataSource, the ObjectDataSourceStatusEventArgs class had a boolean property called ExceptionHandled.  Setting this to true stops the ObjectDataSource from re-throwing the exception, allowing you to handle it yourself.  You can obtain the underlying exception using the Exception property.

protected void odsUser_Deleted(object sender, ObjectDataSourceStatusEventArgs e)
{
    if (e.Exception != null)
    {
        e.ExceptionHandled = true;
        //Perform own exception handling
        lblError.Text = e.Exception.Message;
    }
}

You could also use the same approach with the Updated event.

ASP.NET Property Parameter for Data Sources

Posted on by Joe in ASP.NET, C# | 3 Comments

A few years ago I wrote a custom parameter for data sources such as the ObjectDataSource which used the value of a property on the page for a parameter.

I needed this functionality again so I found what I had previously written and improved it to make it more usable.

Read more

Fill PDF Form Fields from an ASP.NET page using iTextSharp

Posted on by Joe in ASP.NET, C# | 2 Comments

Download the source code: PDFTest.zip

For a project I’m working on I needed to be able to generate PDF’s containing data from my page.  I came across a library called iTextSharp which is a C# port of the Java library iText.  Using this library allows you to generate PDF files on the fly.  You can download the library here, and need to add it as a reference in your project.

In Adobe Acrobat I created a rather crude looking PDF with two Form Fields for Forename and Surname, named txtForename and txtSurname respectively.

Read more

Using the CustomValidator’s ClientValidationFunction

Posted on by Joe in ASP.NET, C#, JavaScript | 2 Comments

The ASP.NET CustomValidator allows you to create custom validation that fits into its validation framework.  The CustomValidator has a server side event called OnServerValidate and a client side event called ClientValidationFunction.

You can use the CustomValidator by just implementing the OnServerValidate event, but any other validation controls that are validated client side will need to be valid before the CustomValidator will be used.  Doing this causes a postback to validate the CustomValidator and as it’s not client side the validation message will not be shown in a ValidationSummary.

Read more

Show a JavaScript confirm dialog box after client validation

Posted on by Joe in ASP.NET, C#, JavaScript | 7 Comments

It’s quite common to use a JavaScript confirm dialog on a button press to ensure that the user wants to submit the page.  If you are using any of the ASP.NET validators that use client side validation you will find the confirm appears before the validation, whereas it would be better if the confirm box only appeared if the page was valid.

Luckily the framework supplies some JavaScript functions that can be used for validation.  Page_IsValid is a boolean indicating if the page is valid which can be used in client script.  This value is set when the JavaScript function Page_ClientValidate is executed.

For this example I have set CausesValidation to false on the button that will show the confirm dialog, as I will call the client side function myself.  If I don’t to this my validation will be called twice.  In the OnClientClick I then need to add some JavaScript to call Page_ClientValidate if the function exists, and then only show the confirm dialog if Page_IsValid is true:

<asp:LinkButton ID="btnSubmit"
                CausesValidation="false"
                OnClientClick="if (typeof(Page_ClientValidate) == 'function') { Page_ClientValidate(); if(Page_IsValid) { return confirm('You are sure?'); } };"
                runat="server"
                onclick="btnSubmit_Click">

Generate a CSV from a generic list of objects using reflection and extension methods

Posted on by Joe in ASP.NET, C# | 12 Comments

Download the source code for this post: ReflectionCSV.zip

Last week I wrote a post about generating a CSV from a DataTable. As I hardly use DataTables these days I thought it would be good to write a function that does this for a generic list of objects using reflection to get the properties of the object and export them.

In this example I have done this using an extension method on the generic list. This approach could also be easily applied to the DataTable example.

Read more

Show ‘Are you sure you want to navigate away from this page’ message like Hotmail

Posted on by Joe in ASP.NET, JavaScript | 2 Comments

If you start typing an email in Hotmail then navigate away without saving or sending it you get the following message:

OnBeforeUnload

This is done by using the onbeforeunload window event.  This event can be used to perform any processing needed before navigating to a new page, but if the event handler returns a string you get this confirmation dialog with your own string replacing “You haven’t sent this message. Are you sure you wan’t to discard it?“.  If you press OK then the navigation continues, and if you press Cancel then you remain on the same page.

Here is an example of how to use the event:

<script language="javascript" type="text/javascript">
    window.onbeforeunload = function() { return "Your message here:"; }
</script>

This could come in useful if you had a form on your page, and you don’t want the user to accidentally navigate away from the page and loose what they have entered.

ObjectDataSource – Cannot convert value of parameter value from System.String to System.DateTime

Posted on by Joe in ASP.NET, C# | 9 Comments

One bug I’ve come across a few times and again just recently is when using an ObjectDataSource with a GridView to update dates.  When doing the update the ObjectDataSource always uses the en-US culture and not the culture defined for the application.

The bug has been acknowledged by Microsoft but never fixed.

If you are in the US then you’ll have no problems, but if you are using a culture that uses the dd/MM/yyyy date format such as the UK or Australia you data will display in the correct format on your page, but you will get the following error when you try to save:

Cannot convert value of parameter ‘value’ from ‘System.String’ to ‘System.DateTime’

Read more