Ajax request

Simple reusable asynchronous multibrowser ajax function.

Call a page by javascript and pass the html result to a function when it arrives (. The url to load by HTTP GET method, and the callback function name are passed as parameters. All the litteral content of the result page is passed as parameter.

Note: some security features, like in Firefox, can block AJAX request to other domains than the domain of the calling webpage (where the script is executed from).


function ajaxRequest(url, callbackFunction)
{
var xmlhttp=false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
// JScript gives us Conditional compilation, we can cope with old IE versions.
// and security blocked creation of the objects.
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
@end @*/
if (!xmlhttp && typeof XMLHttpRequest!='undefined')
{
xmlhttp = new XMLHttpRequest();
}
xmlhttp.open("GET", url,true);
if(callbackFunction != null)
{
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4)
{
callbackFunction(xmlhttp.responseText);
}
}

}
xmlhttp.send(null);

}
function sampleCallBackFunction(httpResponseText)
{
alert(httpResponseText);
}
// sample calls
//
ajaxRequest("http://www.someurl.com",sampleCallBackFunction);
ajaxRequest(document.location,sampleCallBackFunction);//show current page source

Parse HTML Table with RegEx in .NET

This is used to parse an html table. Practical to obtain results from a web page, formatted in a table.

The algorithm requires to know the number of colums to parse. Then, using regex, it loops in all the lines of the tables, and the content of each column of theeese line is inside the m.Groups[index].Value.


public void ParseHtmlTable(string html)
{

/// Basic html table pattern
string columnPattern = @"\<TD[^\>]*\>([^\<]*)\<\/TD\>";
string betweenColumnsPattern = @"[^\<]*";


/// Construct the global pattern for a given nomber of columns
int nbColums = 11;

StringBuilder sbPattern = new StringBuilder();
for (int i = 0; i < nbColums; i++)
{
sbPattern.Append(columnPattern);
sbPattern.Append(betweenColumnsPattern);
}
sbPattern.Append(columnPattern);

/// Parse the result
Regex r = new Regex(sbPattern.ToString(), RegexOptions.IgnoreCase);

foreach (Match m in r.Matches(html))
{
// example
string insideCell1 = m.Groups[0].Value;
string insideCell2 = m.Groups[2].Value;

/// do things..


}
}

Helper library to read CSV file

Here is an interesting and very well done library to read CSV files, fast and without problems:

http://www.codeproject.com/KB/database/CsvReader.aspx

With this library, excel sheets can be save as CSVs and opened safely by any .NET application without any other dependencies (jet provider, office automation or else).

Delimited string helper class in C#

Build delimited strings with less code!

Having to build a string with elements delimited with special characters for a CSV file, a HTTP GET request or any other purpose?
How many times did you made a loop to construct the string, having to user a flag to check if the delimiter have to be added, either at the beginning or the end or the string, to make sure chere is not an intrusive delimiter in the result? To make sure the string don't have the delimiter at the beginning or at the end?

This simple class uses a StringBuilder to construct a key / value string delimited with a given character or string just between elements.


using System;
using System.Text;


/// <summary>
/// To construct a string delimited only between elements.
///
/// Simple helper class to construct dynamically a delimited string
/// with the delimiter inserted automatically only between elements,
/// not at the beginnig nor at the end of the resulting string.
///
/// Uses a StringBuilder as the inner builder.
/// Denis Sauvé
/// </summary>
public class DelimitedStringBuilder
{
protected string delimiter = null;
protected StringBuilder sb = new StringBuilder();
// inner StringBuilder, as StringBuilder class cannot be inherited
/// <summary>
/// New instance of a DelimitedStringBuilder with delimiter between elements
/// </summary>
/// <param name="delimiter">delemiter to use (",", "\n", etc)</param>
public DelimitedStringBuilder(string delimiter)
{
this.delimiter = delimiter;
}
public void Append(string stringToAppend)
{
if (sb.Length >0)
if (delimiter != null) sb.Append(delimiter);
sb.Append(stringToAppend);
}
public override string ToString()
{
return sb.ToString();
}
public StringBuilder InnerStringBuilder
{
get
{
return this.sb;
}
}

}


Note: you have to make sure the delimiter is not in the keys nor in the values... But tThe Append() method could be modified easilly to check that.

Simple XML validation helper using XmlReader

Purpose: simply validate a xml file against a xsd file, in C#.

I would appreciate a one single line validation method from one of the multiple xml .NET classes, but there seems to be none with the framework. I fouded some examples too complicated for nothing on the web. So I created this helper. 

It can be used in two ways:

1- Static single line call:


bool success = XMLValidationHelper.Validate("myFile.xml", "mySchema.xsd");


2- Using helper object to collect the first error message occured:


XMLValidationHelper validator = new XMLValidationHelper("myFile.xml", "mySchema.xsd");
validator.Validate();
if (!validator.IsValid)
{
// do something...

}

Here is the class:



using System;
using System.Xml;
using System.Xml.Schema;
using System.Text;

/// <summary>
/// Helper class to check a XML against a XSD file
/// </summary>
public class XMLValidationHelper
{

string xmlFileName, xsdFileName;
string exceptionMessage;
bool isValid = false;

public string ExceptionMessage
{
get { return exceptionMessage; }
set { exceptionMessage = value; }
}

public XMLValidationHelper(string xmlFileName, string xsdFileName)
{
this.xmlFileName = xmlFileName;
this.xsdFileName = xsdFileName;
}

/// <summary>
/// Global validation state of the xml against the xsd
/// </summary>
public bool IsValid
{
get { return isValid; }
set { isValid = value; }
}

/// <summary>
/// Read the document and collects the validation exceptions if any.
/// </summary>
/// <returns></returns>
public bool Validate()
{

XmlReader schemaReader = XmlReader.Create(this.xsdFileName);

/// validation settings
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags =
System.Xml.Schema.XmlSchemaValidationFlags.ReportValidationWarnings;
settings.Schemas.Add("", schemaReader);


XmlReader myReader = XmlReader.Create(this.xmlFileName, settings);
this.isValid = true;
try
{
while (!myReader.EOF)
myReader.Read();

}

catch (System.Xml.Schema.XmlSchemaException validationException)
{
this.isValid = false;
this.exceptionMessage = validationException.Message;
}
finally
{
schemaReader.Close();
myReader.Close();
}
return this.isValid;
}


public static bool Validate(string xmlFileName, string xsdFileName)
{
XMLValidationHelper instantHelper = new XMLValidationHelper(xmlFileName, xsdFileName);
return instantHelper.Validate();
}


}






Capturing strings between stopwords



private string StringBetween(string beginTag, string endTag, string texteToParse)
{
System.Collections.Specialized.StringCollection coll = StringsBetween(beginTag, endTag, texteToParse);
if (coll.Count == 0) return "";
else return coll[0];
}
private System.Collections.Specialized.StringCollection StringsBetween(string beginTag, string endTag, string texteToParse)
{
System.Collections.Specialized.StringCollection result = new System.Collections.Specialized.StringCollection();
int pos1, pos2;
pos1 = 0;
pos2 = -1;
pos1 = texteToParse.IndexOf(beginTag);
while (pos1 > -1)
{
pos2 = texteToParse.IndexOf(endTag, pos1 + beginTag.Length);
if (pos2 > -1)
{
result.Add(texteToParse.Substring(pos1 + beginTag.Length, pos2 - (pos1 + beginTag.Length)));
pos1 = texteToParse.IndexOf(beginTag, pos2 + endTag.Length);

}
else
pos1 = -1;

}
return result;
}

Simple way to create a Culture in .NET

Here is the simplest way to create a new culture in .NET, from an existing culture.

I needed a way to have french format dates (YYYY-MM-DD) and dot symbol (.) as decimal separator in an web application. Since javascript only recognize dot as decimal separator, having to use french cultures, either "fr-FR" or "fr-CA", is a pain because the decimal specified in theese is the coma. I wanted everything from the french culture, but a dot as decimal separator, and there is no way to do this without creating a new culture.

A new culture can be created from scratch. Here is a detailed article about this.

However, the following code simply copy an existing culture, changes it, and register in with a new name ("fr-CA-QC").

The process of revistering required administrator privilege on the machine where the code is running. The code below only have to be run once.



/// Original culture
CultureInfo cultureInfo = new CultureInfo("fr-CA");
RegionInfo regionInfo = new RegionInfo(cultureInfo.Name);

/// New Culture, with a new name ("fr-CA-QC")
/// if culture already exists, we need to unregister it for overwriting:
/// CultureAndRegionInfoBuilder.Unregister("fr-CA-QC");
CultureAndRegionInfoBuilder builder =
new CultureAndRegionInfoBuilder("fr-CA-QC",
CultureAndRegionModifiers.None);

// load in the data from the original culture and region
builder.LoadDataFromCultureInfo(cultureInfo);
builder.LoadDataFromRegionInfo(regionInfo);

// make custom changes to the culture
builder.NumberFormat.NumberDecimalSeparator = ".";
builder.NumberFormat.CurrencyDecimalSeparator = ".";

/// Create this culture on this computer (NEED ADMINISTRATOR PRIVILEGES)
builder.Register();



This can be executed in a simple windows or console application. After that, any application running on the same computer or server can use this new culture with the name defined above.


Now, I just have to include theese attributes in my web.config files and I will no more have culture problems:


<globalization culture="fr-CA-QC" uiCulture="fr-CA-QC" ...