|
|||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
Note: This is an unedited contribution. If this article is inappropriate,
needs attention or copies someone else's work without reference then please
Report This Article
The download contains a VS 2008 solution with .NET 2 including unit tests. The test cases contain some Chinese characters for testing Quoted Printable encoding. BackgroundFor parsing vCard text using C# codes, I published an article vCard Reader with Lightweight Approach at CodeProject. In the article, I demonstrated how to use regular expressions to parse vCard text. The code uploaded and the article were more about proof of concept, and you need further work to integrate the code to commercial applications, which I had done later on. This article is about follow-up work to strengthen the C# .NET vCard parser. You can use it, as usual, without any warranty. Before further reading, please first read vCard Reader with Lightweight Approach at CodeProject. When testing, please be aware the following facts: vCard standard has been around for more than 10 years, and widely accepted by the industries. However, the implementations from different vendors are a bit buggy, resulting in data corruption during data exchanges. For example 1. MS Outlook 2003 can handle Unicode. When exporting to vCard, non-ASCII characters are encoded into QuotedPrintable over UTF8, however, when importing, Outlook will fail to import those characters. While NickName is not included in vCard 2.1 but in vCard 3.0, but Outlook's implementation of vCard 2.1 includes NickName. 2. Yahoo has similar problem. In addition, Rev in Yahoo vCard is not DateTime but a kind of 3-digit number, a bit doggy. These applications could not eat their own dog food. So when you are testing the exchanges of vCard objects, keep these facts in mind. For more quirks of vCard implementations, please read this summary and the vcard-errata. vCard Handling using C#
Comparing with the code in previous article, the class structures were re-constructed to separate concerns in order to improve flexibility and maintainability. public class VCardReader { /// <summary> /// Analyze vCard text into vCard properties. /// </summary> /// <param name="vCardText">vCard text.</param> /// <returns>vCard object.</returns> public static VCard ParseText(string vCardText) { VCard v = new VCard(); RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace; Regex regex; Match m; MatchCollection mc; NameValueCollection vCardLines = new NameValueCollection(); regex = new Regex(@"((?<strElement>[\w]*) (;*(ENCODING=)?(?<strAttr>(QUOTED-PRINTABLE)))* ([^:]*)* (:(?<strValue> (([^\n\r]*=[\n\r]+)*[^\n\r]*[^=][\n\r]*) )))", options); MatchCollection matches = regex.Matches(vCardText); foreach (Match match in matches) { string ss; string vCardLine = match.Value; switch (match.Groups["strElement"].Value) { case "FN": regex = new Regex(@"(?<strElement>(FN))(;CHARSET=UTF-8)? (:(?<strFN>[^\n\r]*))", options); m = regex.Match(vCardLine); if (m.Success) v.FormattedName = m.Groups["strFN"].Value; break; case "N": regex = new Regex(@"(?<strElement>(N))(;CHARSET=UTF-8)?(:(?<strSurname> ([^;\n\r]*))) (;(?<strGivenName>([^;\n\r]*)))? (;(?<strMidName>([^;\n\r]*)))? (;(?<strPrefix>([^;\n\r]*)))? (;(?<strSuffix>[^;\n\r]*))?", options); m = regex.Match(vCardLine); if (m.Success) { v.Surname = m.Groups["strSurname"].Value; v.GivenName = m.Groups["strGivenName"].Value; v.MiddleName = m.Groups["strMidName"].Value; v.Prefix = m.Groups["strPrefix"].Value; v.Suffix = m.Groups["strSuffix"].Value; } break; case "TITLE": regex = new Regex(@"(?<strElement>(TITLE))(;CHARSET=UTF-8)? (:(?<strTITLE>[^\n\r]*))", options); m = regex.Match(vCardLine); if (m.Success) v.Title = m.Groups["strTITLE"].Value; break; case "ORG": regex = new Regex(@"(?<strElement>(ORG)) (;CHARSET=utf-8)? (:(?<strORG>[^;\n\r]*))(;(?<strDept>[^\n\r]*))?", options); m = regex.Match(vCardLine); if (m.Success) { v.Org = m.Groups["strORG"].Value; v.Department = m.Groups["strDept"].Value; } break; case "BDAY": regex = new Regex(@"(?<strElement>(BDAY)) (:(?<strBDAY>[^\n\r]*))", options); m = regex.Match(vCardLine); if (m.Success) { string[] expectedFormats = { "yyyyMMdd", "yyMMdd", "yyyy-MM-dd" }; v.Birthday = DateTime.ParseExact(m.Groups["strBDAY"].Value, expectedFormats, null, System.Globalization.DateTimeStyles.AllowWhiteSpaces); } break; case "REV": regex = new Regex(@"(?<strElement>(REV)) (;CHARSET=utf-8)? (:(?<strREV>[^\n\r]*))", options); m = regex.Match(vCardLine); if (m.Success) { string[] expectedFormats = { "yyyyMMddHHmmss", "yyyyMMddTHHmmssZ" }; v.Rev = DateTime.ParseExact(m.Groups["strREV"].Value, expectedFormats, null, System.Globalization.DateTimeStyles.AllowWhiteSpaces); } break; case "EMAIL": regex = new Regex(@"((?<strElement>(EMAIL)) ((;(?<strAttr>(HOME|WORK)))|(;(?<strPref>(PREF))))* (;[^:]*)* (:(?<strValue>[^\n\r]*)))", options); mc = regex.Matches(vCardLine); if (mc.Count > 0) { for (int i = 0; i < mc.Count; i++) { EmailAddress email = new EmailAddress(); v.Emails.Add(email); m = mc[i]; email.Address = m.Groups["strValue"].Value; ss = m.Groups["strAttr"].Value; if (ss == "HOME") email.HomeWorkTypes = HomeWorkTypes.HOME; else if (ss == "WORK") email.HomeWorkTypes = HomeWorkTypes.WORK; if (m.Groups["strPref"].Value == "PREF") email.Pref = true; } } break; case "TEL": regex = new Regex(@"((?<strElement>(TEL)) ((;(?<strType>(VOICE|CELL|PAGER|MSG|FAX)))| (;(?<strAttr>(HOME|WORK)))| (;(?<strPref>(PREF)))?)* (:(?<strValue>[^\n\r]*)))", options); mc = regex.Matches(vCardLine); if (mc.Count > 0) { for (int i = 0; i < mc.Count; i++) { PhoneNumber phone = new PhoneNumber(); v.Phones.Add(phone); m = mc[i]; phone.Number = m.Groups["strValue"].Value; ss = m.Groups["strAttr"].Value; if (ss == "HOME") phone.HomeWorkTypes = HomeWorkTypes.HOME; else if (ss == "WORK") phone.HomeWorkTypes = HomeWorkTypes.WORK; if (m.Groups["strPref"].Value == "PREF") phone.Pref = true; CaptureCollection types = m.Groups["strType"].Captures; foreach (Capture capture in types) { switch (capture.Value) { case "VOICE": phone.PhoneTypes |= PhoneTypes.VOICE; break; case "CELL": phone.PhoneTypes |= PhoneTypes.CELL; break; case "PAGER": phone.PhoneTypes |= PhoneTypes.PAGER; break; case "MSG": phone.PhoneTypes |= PhoneTypes.MSG; break; case "FAX": phone.PhoneTypes |= PhoneTypes.FAX; break; } } } } break; case "ADR": regex = new Regex(@"(?<strElement>(ADR)) (;(?<strAttr>(HOME|WORK)))?(;CHARSET=utf-8)?(:(?<strPo>([^;]*))) (;(?<strBlock>([^;]*))) (;(?<strStreet>([^;]*))) (;(?<strCity>([^;]*))) (;(?<strRegion>([^;]*))) (;(?<strPostcode>([^;]*)))(;(?<strNation>[^\n\r]*))", options); mc = regex.Matches(vCardLine); if (mc.Count > 0) { for (int i = 0; i < mc.Count; i++) { Address address = new Address(); v.Addresses.Add(address); m = mc[i]; ss = m.Groups["strAttr"].Value; if (ss == "HOME") address.HomeWorkType = HomeWorkTypes.HOME; else if (ss == "WORK") address.HomeWorkType = HomeWorkTypes.WORK; address.PO = m.Groups["strPo"].Value; address.Ext = m.Groups["strBlock"].Value; address.Street = m.Groups["strStreet"].Value; address.Locality = m.Groups["strCity"].Value; address.Region = m.Groups["strRegion"].Value; address.Postcode = m.Groups["strPostcode"].Value; address.Country = m.Groups["strNation"].Value; } } break; case "NOTE": regex = new Regex(@"((?<strElement>(NOTE)) ((;CHARSET=[^;]*)?;*(ENCODING=)?(?<strAttr>(QUOTED-PRINTABLE)))* ([^:]*)* (:(?<strValue> (([^\n\r]*=[\n\r]+)*[^\n\r]*[^=][\n\r]*) )))", options); m = regex.Match(vCardLine); if (m.Success) { if (m.Groups["strAttr"].Value == "QUOTED-PRINTABLE") v.Note = QuotedPrintable.Decode(m.Groups["strValue"].Value); else v.Note = m.Groups["strValue"].Value; } break; case "URL": regex = new Regex(@"((?<strElement>(URL)) (;*(?<strAttr>(HOME|WORK)))? (:(?<strValue>[^\n\r]*)))", options); mc = regex.Matches(vCardLine); if (mc.Count > 0) { for (int i = 0; i < mc.Count; i++) { URL url = new URL(); v.URLs.Add(url); m = mc[i]; url.Address = m.Groups["strValue"].Value; ss = m.Groups["strAttr"].Value; if (ss == "HOME") url.HomeWorkTypes = HomeWorkTypes.HOME; else if (ss == "WORK") url.HomeWorkTypes = HomeWorkTypes.WORK; } } break; case "ROLE": regex = new Regex(@"(?<strElement>(ROLE)) (;CHARSET=utf-8)? (:(?<strROLE>[^\n\r]*))", options); m = regex.Match(vCardLine); if (m.Success) v.Role = m.Groups["strROLE"].Value; break; } } return v; } } If you have ever reviewed existing vCard implementations in C, PHP or Pascal, you will see using regular expression makes the parser simpler and shorter Further Works for Integrating to Other ApplicationsConsidering current implementation of vCard support in MS Outlook, MS Outlook Express, Yahoo Mail and Eudora etc., the following properties and attributes are not supported in this vCard implementation: You might need to modify the codes to adapt your needs of data exchange. The efficiency of regular expression processing can be improved by using Regex.CompileToAssembly. An example of integration exists in an open source project initialized by me, called SyncML.NET Client API with SyncML Client for Open Contacts. The latest update of the C# vCard components is located in the download area of SyncML.NET Client API.
|
||||||||||||||||||||||||||||||||||||||||