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

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# | 3 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 | 3 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# | 18 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

Create a virtual directory in IIS using ASP.NET and C#

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

Update 30th July 2009: After deploying this to a development server there were a few tweaks I needed to make to get it working. I  have amended the post as necessary.

I needed to be able to create a virtual directory in IIS via my ASP.NET application.  I found this nice little example in VB.NET and converted it to C#.  You need to add a reference to System.DirectoryServices to use it.  The VB.NET example always puts the new virtual directory in the default website, so I have amended it to allow choosing the server and website you want to place the virtual directory under.


private void CreateVirtualDir(string serverName, string website, string appName, string path)
{
    DirectoryEntry IISSchema = new DirectoryEntry(string.Concat("IIS://", serverName, "/Schema/AppIsolated"));
    bool canCreate = IISSchema.Properties["Syntax"].Value.ToString().ToUpper() != "BOOLEAN";
    IISSchema.Dispose();

    //get the identifier for the site we want
    int identifier = 0;
    DirectoryEntry root = new DirectoryEntry(string.Concat("IIS://", serverName, "/W3SVC"));
    foreach(DirectoryEntry de in root.Children)
    {
        if (de.SchemaClassName.ToUpper().Equals("IISWEBSERVER") &&
            de.Invoke("Get", "ServerComment").ToString().ToUpper().Equals(website.ToUpper()))
        {
            identifier = Convert.ToInt32(de.Name);
            break;
        }
    }

    if (canCreate && identifier > 0)
    {
        bool pathCreated = false;
        try
        {
            DirectoryEntry iisAdmin = new DirectoryEntry(string.Format("IIS://{0}/W3SVC/{1}/Root", serverName, identifier));

            //make sure folder exists
            if (!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);
                pathCreated = true;
            }

            //If the virtual directory already exists then delete it
            foreach (DirectoryEntry vd in iisAdmin.Children)
            {
                if (vd.Name.Equals(appName))
                {
                    iisAdmin.Invoke("Delete", new string[] { vd.SchemaClassName, appName });
                    iisAdmin.CommitChanges();
                    break;
                }
            }

            //Create and setup new virtual directory
            DirectoryEntry vDir = iisAdmin.Children.Add(appName, "IIsWebVirtualDir");
            vDir.Properties["Path"][0] = path;
            vDir.Properties["AppFriendlyName"][0] = appName;
            vDir.Properties["EnableDirBrowsing"][0] = false;
            vDir.Properties["AccessRead"][0] = true;
            vDir.Properties["AccessExecute"][0] = true;
            vDir.Properties["AccessWrite"][0] = false;
            vDir.Properties["AccessScript"][0] = true;
            vDir.Properties["AuthNTLM"][0] = true;
            vDir.Properties["EnableDefaultDoc"][0] = true;
            vDir.Properties["DefaultDoc"][0] = "default.htm,default.aspx,default.asp";
            vDir.Properties["AspEnableParentPaths"][0] = true;
            vDir.CommitChanges();

            //the following are acceptable params
            //INPROC = 0
            //OUTPROC = 1
            //POOLED = 2
            vDir.Invoke("AppCreate", 1);
        }
        catch (Exception ex)
        {
            if (pathCreated)
            {
                System.IO.Directory.Delete(path);
            }

            throw ex;
        }
    }
    else
    {
        throw new ApplicationException("Failed to create Virtual Directory");
    }
}

To create a new virtual directory I can then call the method like this:

try
{
    CreateVirtualDir("localhost", "MyWebSite" "MyVirtualDirectory", @"c:\sites\mysite");
}
catch (Exception ex)
{
    lblMessage.Text = string.Concat("An error occurred: ", ex.Message);
}

When I deployed this to a development server I got an ‘Access is denied’ error on this following line:

vDir.CommitChanges();

This is because IIS administration need to be done by a user in the administrator group which is the ASPNET user is not.  To resolve this I created a new window user on the server which was a member of the administrator group.  I then added the following to my Web.config:

<system.web>
    <identity impersonate="true" userName="username" password="password" />
</system.web>

You could also wrap this in an pages element to restrict which pages will impersonate this identity.

How to create a CSV from a DataTable

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

In a project I’ve been working on I came across the need export a DataTable to CSV and this is how I did it.  I have split up the functionality as I also use them to concatenate several DataTables into one CSV.

I need to import for following namespaces in this example.

using System.Data.SqlClient;
using System.Text;

The first method gets the DataTable.  It could easily be changed to use stored procedures and add parameters.


private DataTable GetDataTable()
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
    SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM MyTable", con);
    DataTable dt = new DataTable();

    using (con)
    {
        da.Fill(dt);
    }

    return dt;
}

The next method creates the CSV using a StringBuilder.  First it creates the headings by looping through the DataTable’s Columns collection, then creates each row by iterating through the Rows.  I’m also checking for any commas in the value which would break the CSV, and putting the value in quotes which escapes the comma.  Finally it’s checking for any \r or \n characters and replacing them with a space.  There may well be other characters that break the CSV but for now this is fine for what I’m doing, although it is very simple  just to add extra conditions to the method to check for invalid characters.


public string GetCSV(DataTable dt)
{
    StringBuilder sb = new StringBuilder();

    //Line for column names
    for (int i = 0; i < dt.Columns.Count; i++)
    {
        sb.Append(dt.Columns[i]);

        if (i < dt.Columns.Count - 1)
        {
            sb.Append(",");
        }
    }

    sb.AppendLine();

    //Loop through table and create a line for each row
    foreach (DataRow dr in dt.Rows)
    {
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            if (!Convert.IsDBNull(dr[i]))
            {
                string value = dr[i].ToString();

                //Check if the value contans a comma and place it in quotes if so
                if (value.Contains(","))
                {
                    value = string.Concat("\"", value, "\"");
                }

                //Replace any \r or \n special characters from a new line with a space
                if (value.Contains("\r"))
                {
                    value = value.Replace("\r", " ");
                }
                if (value.Contains("\n"))
                {
                    value = value.Replace("\n", " ");
                }

                sb.Append(value);
            }

            if (i < dt.Columns.Count - 1)
            {
                sb.Append(",");
            }
        }

        sb.AppendLine();
    }

    return sb.ToString();
}

Now we have the CSV as a string you could easily save it to a file, but I want to write it to the page’s HttpResponse so the user can download it in the browser.  To do this I have the following method.

private void ExportCSV(string csv, string filename)
{
    Response.Clear();
    Response.AddHeader("content-disposition", string.Format("attachment; filename={0}.csv", filename));
    Response.ContentType = "text/csv";
    Response.AddHeader("Pragma", "public");
    Response.Write(csv);
    Response.End();
}

Now to put this all together I have a button click event like this:

protected void btnCreateCSV_Click(object sender, EventArgs e)
{
    try
    {
        string csv = GetCSV(GetDataTable());
        ExportCSV(csv, "MyCSV");
    }
    catch (System.Threading.ThreadAbortException)
    {
        //Thrown when calling Response.End in ExportCSV
    }
    catch(Exception ex)
    {
        lblMessage.Text = string.Concat("An error occurred: ", ex.Message);
    }
}

When using Response.End in a Try block as the ExportCSV does, a ThreadAbortException is thrown.  For this reason I handle this Exception first, then any other Exception which will be a true error. See here for more info.