Today, I had to build web form that took user input from standard ASP.NET input controls. In one of the text boxes the user must to enter a valid URL, so I had to make some validation logic. But first of all, I had to find out what kind of URL’s we would accept as being valid. These are the rules we decided upon:

  • The protocol must be http or https
  • Sub domains are allowed
  • Query strings are allowed

Based on those rules, I wrote this regular expression:

(http|https)://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?

It is used in a RegularExpressionValidator control on the web form and on a business object in C#.

<asp:RegularExpressionValidator runat="Server"

  ControlToValidate="txtUrl"

  ValidationExpression="(http|https)://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?"

  ErrorMessage="Please enter a valid URL"

  Display="Dynamic" />

Here is the server-side validator method used by the business object:

using System.Text.RegularExpressions;

 

private bool IsUrlValid(string url)

{

  return Regex.IsMatch(url, @"(http|https)://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?");

}

You can add more protocols to the expression easily. Just add them to the beginning of the regular expression:

(http|https|ftp|gopher)://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?

You can also allow every thinkable protocol containing at least 3 characters by doing this:

([a-zA-Z]{3,})://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?

Back in February I wrote a post on how to export DataTables to XML and Excel and I still get a lot of search engine traffic to that post. People have been asking me to simplify the example and only concentrate on the Excel export, so that’s what I will do now.

All spreadsheet applications (Excel, Calc etc.) understand semicolon separated files natively, so everyone can use this method – you don’t even have to use Excel for it to work.

public static void ExportToSpreadsheet(DataTable table, string name)

{

  HttpContext context = HttpContext.Current;

  context.Response.Clear();

 

  foreach (DataColumn column in table.Columns)

  {

    context.Response.Write(column.ColumnName + ";");

  }

 

  context.Response.Write(Environment.NewLine);

 

  foreach (DataRow row in table.Rows)

  {

    for (int i = 0; i < table.Columns.Count; i++)

    {

      context.Response.Write(row[i].ToString().Replace(";", string.Empty) + ";");

    }

    context.Response.Write(Environment.NewLine);

  }

 

  context.Response.ContentType = "text/csv";

  context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + name + ".csv");

  context.Response.End();

}

>

Then just call this method and pass the DataTable and the filename as parameters.

ExportToSpreadsheet(table, "products");

The method is static so you can use it anywhere in a web application. Put it on a page, a HTTP Handler, add it to the App_Code folder or stick it in a separate assembly. As long as you call it from a web application it will work.