IsDateTime in .NET for both ticks and string representation

June 9th, 2006 Comments off

Some while ago I developed a Settings system, where the SettingValue type should be checked. The DateTime.TryParse function did not do all the work I wanted it to do, so I thought ‘why not develop my own workaround’ IsDateTime in .NET for both ticks and string representation icon smile ? It is posted below…

/// <summary>
/// The IsDateTime function returns whether the given expression is a DateTime or not.
/// </summary>
/// <param name="expression">Expression to check for being DateTime.</param>
/// <returns>Boolean</returns>
/// <remarks>
/// The DateTime expression can be given as ticks or as normal DateTime representation.
/// </remarks>
public static bool IsDateTime(object expression) {
if(expression == null) return false;Bert Loedeman

string stringExpression = System.Convert.ToString(expression);
if(String.IsNullOrEmpty(stringExpression)) return false;

// DateTime can be specified in ticks. In that case the string should be convertible
// to a long (System.Int64) and fit in a specific range.
long retLong;
if(Int64.TryParse(stringExpression, out retLong)) {
// Ticks: 0 = DateTime.MinValue, 0x2bca2875f4373fff = DateTime.MaxValue
if((retLong < DateTime.MinValue.Ticks) || (retLong > DateTime.MaxValue.Ticks)) return false;
return true;
}

DateTime retDateTime;
return DateTime.TryParse(stringExpression, out retDateTime);
}

Search and replace with Regular Expressions in Visual Studio .NET (2005)

March 10th, 2006 Comments off

Today I had to search and replace a text with a little variation in it in a very large project. This text looked like ‘if<zero or more spaces>(Null.IsNull(<object name>.<variable name>))’. I had to replace it with: ‘if (!<object name>.<variable name> > 0))’. This turns out to be quite a job, especially when you are not very experienced with Microsoft’s way of dealing with regular expressions. Finally I discovered a way to do the job. The expressions used for it are the following:

Search string: if[ ]*\(Null.IsNull\({:c+.:c+}\)\)
Replacement string: if (!(\1 > 0))

Note that the Regular Expression used to search does not entirely look likea normal RegEx. Microsoft seems to use their own kind of RegEx for search and replace. Important is that {} is not used to quantify like in RegEx (for instance: zo{1} matches ‘zo’ but not ‘zoo’), but to generate a tagged expression, which can be used in the replacement string by giving in \x whereby x represents a 1-base number (1st replacement = \1 and so on).

Hope I have been of some help for anybody out there Search and replace with Regular Expressions in Visual Studio .NET (2005) icon smile . Please do not be concerned about posting a comment/question. I’ll do what I can to answer you soon!

Bert