When adding a service reference to an OData service, the generated entities classes are made partial classes. This provides a useful extensibility point for extending the model, and for providing custom logic within entities themselves.
The EbayModel.Item
class, for example, contains a TimeLeft
property. This property is provided as a string. If it was of type TimeSpan
, however, it would be easier to work with.
This section creates a new partial Item
class and, within it, a TimeSpan
property that converts the string value provided by the OData service into a TimeSpan
value.
The following is an example of the format used by the TimeLeft
string:
P0DT0H13M8S
The string contains tokens that indicate value positions for days, hours, minutes, and seconds. Unfortunately, this format is not compatible with the TimeSpan.Parse
method. Therefore, we need to break up the string into its constituents parts. This can be done using a regular expression.
When you construct regular expressions, they can quickly become complex. Having a decent work bench for constructing them can make life easier. I really like the free regular expression tool called Expresso (www.ultrapico.com). Expresso allows you to specify sample text to see whether your regular expression produces the appropriate result (see Figure 27.6). It also includes other interfaces that assist in the construction of regular expressions.
The regular expression to deconstruct the TimeLeft
value can be plugged in to a new partial Item
class (see Listing 27.10).
public partial class Item
{
public TimeSpan? TimeLeftCustom
{
get
{
return ConvertToTimeSpan(TimeLeft);
}
}
TimeSpan? ConvertToTimeSpan(string timeLeft)
{
Regex regex = new Regex(
@"P(?<Days>d+)DT(?<Hours>d+)H(?<Minutes>d+)M(?<Seconds>d+)S");
Match match = regex.Match(timeLeft);
if (match.Success)
{
string timeSpanString = string.Format("{0}.{1}:{2}:{3}",
match.Groups["Days"].Value,
match.Groups["Hours"].Value,
match.Groups["Minutes"].Value,
match.Groups["Seconds"].Value);
TimeSpan result;
if (TimeSpan.TryParse(timeSpanString, out result))
{
return result;
}
}
return null;
}
}
The TimeLeftCustom
property is now able to be used in the view, like any of the other Item
class’s properties.
52.14.204.142