public IEnumerable <Row> CreateRows(vCardCollection cards) { List <Row> rows = new List <Row>(cards.Count); foreach (vCard card in cards) { Row row = new Row(); row.AppendChild(_textTemplate.Create(card.GivenName)); row.AppendChild(_textTemplate.Create(card.FamilyName)); row.AppendChild(_textTemplate.Create(card.FormattedName)); foreach (PhoneNumber phoneNumber in card.PhoneNumbers) { row.AppendChild(_textTemplate.Create(_phoneTypeToText.Convert(phoneNumber.Type))); row.AppendChild(_textTemplate.Create(phoneNumber.Number)); } foreach (EmailAddress emailAddress in card.EmailAddresses) { row.AppendChild(_textTemplate.Create(emailAddress.Email.Address)); } rows.Add(row); } return(rows); }
public void SaveCollectionsWithVersions() { if (File.Exists("vcardcollection2.vcf")) { File.Delete("vcardcollection2.vcf"); } vCardCollection vcardCollection = new vCardCollection(); vCard vcard = new vCard { Version = Version.V2 }; Assert.DoesNotThrow(delegate { vcardCollection.Save("vcardcollection2.vcf", Version.V2); }); Assert.Throws <InvalidOperationException>(delegate { vcardCollection.Save("vcardcollection2.vcf", Version.V2); }); Assert.DoesNotThrow(delegate { vcardCollection.Save("vcardcollection2.vcf", Version.V3, WriteOptions.Overwrite); }); // Assert.Throws<NotImplementedException>(delegate // { // vcardCollection.Save("vcardcollection2.vcf", Version.V4, WriteOptions.Overwrite); // }); }
protected void OnOfdSelectVcardSelectionChanged(object sender, EventArgs e) { if (File.Exists(ofd_select_vcard.Filename) && (System.IO.Path.GetExtension(ofd_select_vcard.Filename) == ".vcf" || System.IO.Path.GetExtension(ofd_select_vcard.Filename) == ".vcard")) { vCardCollection collection = vCard.FromFile(ofd_select_vcard.Filename); foreach (vCard vcard in collection) { Node node = new Node(); node.FullName = vcard.FormattedName; node.EmailAddress = vcard.EmailAddresses.Count > 0 ? vcard.EmailAddresses [0].Email.Address : ""; node.PhoneNumber1 = vcard.PhoneNumbers.Count > 0 ? vcard.PhoneNumbers [0].Number : ""; node.PhoneNumber2 = vcard.PhoneNumbers.Count > 1 ? vcard.PhoneNumbers [1].Number : ""; Store.AddNode(node); } } else { MessageDialog md = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Error, ButtonsType.Close, "The selected file either doesn't exist, or is of an incorrect format."); md.Run(); md.Destroy(); } }
public void SaveCollectionsWithVersions() { if (File.Exists("vcardcollection2.vcf")) { File.Delete("vcardcollection2.vcf"); } vCardCollection vcardCollection = new vCardCollection(); vCard vcard = new vCard(); vcard.Version = 2.1f; Assert.DoesNotThrow(delegate { vcardCollection.Save("vcardcollection2.vcf", 2.1f, WriteOptions.ThrowError); }); Assert.Throws <InvalidOperationException>(delegate { vcardCollection.Save("vcardcollection2.vcf", 2.1f); }); Assert.DoesNotThrow(delegate { vcardCollection.Save("vcardcollection2.vcf", 3.0f, WriteOptions.Overwrite); }); Assert.Throws <NotImplementedException>(delegate { vcardCollection.Save("vcardcollection2.vcf", 4.0f, WriteOptions.Overwrite); }); Assert.Throws <ArgumentException>(delegate { vcardCollection.Save("vcardcollection2.vcf", 5.4f, WriteOptions.Overwrite); }); }
public void vCardCollectionConstructorTest() { vCardCollection target = new vCardCollection(); //vCard card = new vCard( //vCardReader reader = new vCardReader(); //reader.Read( //target.Add( }
public int CalculateMailColumns(vCardCollection cards) { List <int> numbersPerRecord = new List <int>(); foreach (vCard card in cards) { numbersPerRecord.Add(card.EmailAddresses.Count); } return(numbersPerRecord.Max()); }
public int CalculatePhoneColumns(vCardCollection cards) { List <int> numbersPerRecord = new List <int>(); foreach (vCard card in cards) { numbersPerRecord.Add(card.PhoneNumbers.Count); } return(numbersPerRecord.Max()); }
public void FromFileTest() { string filePath = Path.Combine(assemblyFolder, "v2.vcf"); vCardCollection collection = null; Assert.DoesNotThrow(delegate { collection = Deserializer.FromFile(filePath); }); Assert.AreEqual(1, collection.Count); }
public void InsertAndRemove() { Assert.DoesNotThrow(delegate { vCard vcard = new vCard(); vCardCollection vcardCollection = new vCardCollection(); vcardCollection.Add(vcard); vcardCollection[0] = vcard; vcard = vcardCollection[0]; vcardCollection.Remove(vcard); }); }
/// <summary> /// Writes a vcard collection object to a file /// </summary> /// <param name="vcardCollection">The vcard collection object to be written</param> /// <param name="filePath">The path the collection should be saved to</param> /// <param name="version">The version to be serialized into</param> /// <param name="options">tate whether the card should be overwritten if it exists</param> /// <returns>A value stating if the serialization was successful or not</returns> /// <exception cref="InvalidOperationException">Thrown when the file path exists and the overwrite option is not invoked</exception> /// <exception cref="ArgumentNullException">Thrown when the vcard supplied is null</exception> public static bool Serialize(vCardCollection vcardCollection, string filePath, Version version, WriteOptions options = WriteOptions.ThrowError) { if (options == WriteOptions.ThrowError) { if (File.Exists(filePath)) { throw new InvalidOperationException( "A file with the given filePath exists." + " If you want to overwrite the file," + " then call this method and pass the " + "optional overwrite option" ); } } if (vcardCollection == null) { throw new ArgumentNullException("The vcard collection cannot be null."); } var vcardCollectionString = ""; if (version == Version.V2) { foreach (vCard vcard in vcardCollection) { vcardCollectionString += Serialize(vcard, Version.V2); } } else if (version == Version.V3) { foreach (vCard vcard in vcardCollection) { vcardCollectionString += Serialize(vcard, Version.V3); } } else { foreach (vCard vcard in vcardCollection) { vcardCollectionString += Serialize(vcard, Version.V4); } } try { File.WriteAllText(filePath, vcardCollectionString); return(true); } catch (Exception e) { Console.WriteLine(e); return(false); } }
public void ProcessV3_0Coverage() { string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string filePath = Path.Combine(assemblyFolder, "version30.vcf"); vCardCollection vcardCollection = null; Assert.DoesNotThrow(delegate { vcardCollection = vCard.FromFile(filePath); }); Assert.IsNotNull(vcardCollection); Assert.AreEqual(vcardCollection.Count, 1); }
public void SerializeVcardCollectionErrorTest() { string filePath = null; vCardCollection vcardCollection = new vCardCollection(); Assert.DoesNotThrow(delegate { Serializer.Serialize(vcardCollection, filePath, Version.V2); }); Assert.DoesNotThrow(delegate { Serializer.Serialize(vcardCollection, filePath, Version.V3); }); }
public void InsertAndRemoveNonExistentIndices() { vCardCollection vcardCollection = new vCardCollection(); Assert.Throws <IndexOutOfRangeException>(delegate { var vcard_ = vcardCollection[0]; }); var vcard = new vCard(); Assert.Throws <IndexOutOfRangeException>(delegate { vcardCollection[0] = vcard; }); }
protected void OnOfdSelectVcardSelectionChanged(object sender, EventArgs e) { if (File.Exists(ofd_select_vcard.Filename) && (System.IO.Path.GetExtension(ofd_select_vcard.Filename) == ".vcf" || System.IO.Path.GetExtension(ofd_select_vcard.Filename) == ".vcard")) { // Remove previous content Store.Clear(); // Get new data try { vCardCollection collection = Deserializer.FromFile(ofd_select_vcard.Filename); foreach (vCard vcard in collection) { Node node = new Node(); node.FullName = vcard.FormattedName; node.EmailAddress = vcard.EmailAddresses.Count > 0 ? vcard.EmailAddresses[0].Email.Address : ""; node.PhoneNumber1 = vcard.PhoneNumbers.Count > 0 ? vcard.PhoneNumbers[0].Number : ""; node.PhoneNumber2 = vcard.PhoneNumbers.Count > 1 ? vcard.PhoneNumbers[1].Number : ""; Store.AddNode(node); } } catch (NotImplementedException exception) { Console.WriteLine(exception.Message); MessageDialog md = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Error, ButtonsType.Close, "The selected file not yet supported by this library.\nError: " + exception.Message); md.Run(); md.Destroy(); } catch (Exception exception) { Console.WriteLine(exception.Message); MessageDialog md = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Error, ButtonsType.Close, "The selected file is of an incorrect format.\nError: " + exception.Message); md.Run(); md.Destroy(); } } else { MessageDialog md = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Error, ButtonsType.Close, "The selected file either doesn't exist, or is of an incorrect format."); md.Run(); md.Destroy(); } }
public void Export(vCardCollection cards, string filePath, string fileName) { // Create a spreadsheet document by supplying the filepath. // By default, AutoSave = true, Editable = true, and Type = xlsx. SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument. Create(filePath, SpreadsheetDocumentType.Workbook); // Add a WorkbookPart to the document. WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart(); workbookpart.Workbook = new Workbook(); // Add a WorksheetPart to the WorkbookPart. WorksheetPart worksheetPart = workbookpart.AddNewPart <WorksheetPart>(); var sheetData = new SheetData(); worksheetPart.Worksheet = new Worksheet(sheetData); // Add Sheets to the Workbook. Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook. AppendChild <Sheets>(new Sheets()); // Append a new worksheet and associate it with the workbook. Sheet sheet = new Sheet() { Id = spreadsheetDocument.WorkbookPart. GetIdOfPart(worksheetPart), SheetId = 1, Name = fileName }; sheets.Append(sheet); sheetData.AppendChild(_headerPart.CreateRowHeader(cards)); var body = _bodyPart.CreateRows(cards); foreach (var row in body) { sheetData.AppendChild(row); } workbookpart.Workbook.Save(); // Close the document. spreadsheetDocument.Close(); }
public List <Contact> GetContactsFromFile(string filePath) { List <Contact> ListOfContacts = new List <Contact>(); vCardCollection contacts = Deserializer.FromFile(filePath); foreach (vCard contact in contacts) { ListOfContacts.Add(new Contact() { FirstName = contact.GivenName, LastName = contact.FamilyName, MobilePhone = (contact.PhoneNumbers.Count > 1) ? contact.PhoneNumbers[0].Number.ToString() : "N/A", Email = (contact.EmailAddresses.Count > 1) ? contact.EmailAddresses[0].Email.ToString() : "N/A" }); } return(ListOfContacts); }
public void FromStreamReaderTest() { string filePath = Path.Combine(assemblyFolder, "v2.vcf"); StreamReader streamReader = null; Assert.DoesNotThrow(delegate { streamReader = Helper.GetStreamReaderFromFile(filePath); }); Assert.IsNotNull(streamReader); vCardCollection collection = null; Assert.DoesNotThrow(delegate { collection = Deserializer.FromStreamReader(streamReader); }); Assert.AreEqual(1, collection.Count); }
/// <summary> /// Retrieves a vcard /// </summary> /// <param name="streamReader"><see cref="StreamReader"/> containing a vcard(s)</param> /// <returns>A <see cref="vCardCollection"/></returns> public static vCardCollection FromStreamReader(StreamReader streamReader) { vCardCollection collection = new vCardCollection(); string contactsString = Helper.GetStringFromStreamReader(streamReader); string[] contacts = Helper.GetContactsArrayFromString(contactsString); foreach (string contact in contacts) { string[] contactDetails = Helper.GetContactDetailsArrayFromString(contact); if (contactDetails.Length <= 0) { continue; } vCard details = GetVcardFromDetails(contactDetails); collection.Add(details); } return(collection); }
public vCardCollection Read(string filePath) { //var contents = File.ReadAllText(filePath); //var vCardArray = Regex.Split(contents, @"(BEGIN:VCARD.*?END:VCARD)", RegexOptions.Singleline); //List<string> cleanedCards = new List<string>(); //foreach (var text in vCardArray) //{ // if (!String.IsNullOrWhiteSpace(text)) // { // cleanedCards.Add(text); // } //} //var vCards = cleanedCards.Select(x => Deserializer.GetVCard(x)); //return vCards; vCardCollection contacts = Deserializer.FromFile(filePath); return(contacts); }
public void ReadsCardsWithoutErrors() { string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string filePath = Path.Combine(assemblyFolder, "v2.vcf"); vCardCollection collection = null; Assert.DoesNotThrow(delegate { collection = vCard.FromFile(filePath); }); Assert.IsNotNull(collection); Assert.IsTrue(collection.Count > 0); filePath = Path.Combine(assemblyFolder, "v3.vcf"); collection = null; Assert.DoesNotThrow(delegate { collection = vCard.FromFile(filePath); }); Assert.IsNotNull(collection); Assert.IsTrue(collection.Count > 0); }
public void SaveCollections() { if (File.Exists("vcardcollection1.vcf")) { File.Delete("vcardcollection1.vcf"); } vCardCollection vcardCollection = new vCardCollection(); vCard vcard = new vCard(); vcard.Version = 2.1f; vcardCollection.Add(vcard); Assert.DoesNotThrow(delegate { vcardCollection.Save("vcardcollection1.vcf"); }); vcard.Version = 3.0f; vcardCollection.Add(vcard); Assert.DoesNotThrow(delegate { vcardCollection.Save("vcardcollection1.vcf", WriteOptions.Overwrite); }); Assert.Throws <InvalidOperationException>(delegate { vcardCollection.Save("vcardcollection1.vcf"); }); // vcard.Version = 4.0f; vcardCollection.Add(vcard); Assert.Throws <NotImplementedException>(delegate { vcardCollection.Save("vcardcollection1.vcf", WriteOptions.Overwrite); }); // vcard.Version = 5.0f; vcardCollection.Add(vcard); Assert.Throws <ArgumentException>(delegate { vcardCollection.Save("vcardcollection1.vcf", WriteOptions.Overwrite); }); }
public Row CreateRowHeader(vCardCollection cards) { var headerRow = new Row(); headerRow.AppendChild(_headerTemplate.AddHeader("Nombres")); headerRow.AppendChild(_headerTemplate.AddHeader("Apellidos")); headerRow.AppendChild(_headerTemplate.AddHeader("Nombre Completo")); var telephones = _telephoneCalculator.CalculatePhoneColumns(cards); for (int i = 0; i < telephones; i++) { headerRow.AppendChild(_headerTemplate.AddHeader($"Tipo Teléfono {i + 1}")); headerRow.AppendChild(_headerTemplate.AddHeader($"Número Teléfono {i + 1}")); } var emails = _mailCalculator.CalculateMailColumns(cards); for (int i = 0; i < emails; i++) { headerRow.AppendChild(_headerTemplate.AddHeader($"Correo Electrónico {i + 1}")); } return(headerRow); }
public void SerializeVcardCollectionTest() { string filePath = Path.Combine(assemblyFolder, "invalid.vcf"); vCardCollection vcardCollection = null; Assert.Throws <InvalidOperationException>(delegate { Serializer.Serialize(vcardCollection, filePath, Version.V3); }); Assert.Throws <ArgumentNullException>(delegate { Serializer.Serialize(vcardCollection, filePath, Version.V3, WriteOptions.Overwrite); }); vcardCollection = new vCardCollection(); filePath = Path.Combine(assemblyFolder, "testV2collection.vcf"); Assert.DoesNotThrow(delegate { Serializer.Serialize(vcardCollection, filePath, Version.V2); }); FileAssert.Exists(filePath); filePath = Path.Combine(assemblyFolder, "testV3collection.vcf"); Assert.DoesNotThrow(delegate { Serializer.Serialize(vcardCollection, filePath, Version.V3); }); FileAssert.Exists(filePath); filePath = Path.Combine(assemblyFolder, "testV4collection.vcf"); vcardCollection.Add(new vCard()); Assert.Throws <NotImplementedException>(delegate { Serializer.Serialize(vcardCollection, filePath, Version.V4); }); }
static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("Specify a folder for vcf files!"); return; } var folder = args[0]; if (!Directory.Exists(folder)) { Console.WriteLine($"Folder for vcf files '{folder}' does not exist!"); return; } string outFile; if (args.Length > 1) { outFile = args[1]; } else { outFile = Path.Combine(folder, "../csv/contact-groups.csv"); } System.Console.WriteLine($"Starting at '{folder}'..."); var data = new Dictionary <string, List <string> >(); // Enumerate all vCard files from folder var vcfFiles = Directory.EnumerateFiles(folder, "*.vcf", SearchOption.AllDirectories); foreach (var vcfFile in vcfFiles) { var group = Path.GetFileNameWithoutExtension(vcfFile).ToUpperInvariant(); var isGeneralGroup = string.Equals(group, allGroup, StringComparison.CurrentCultureIgnoreCase); // Read this vCard file and extract all contacts using (var sr = new StreamReader(vcfFile, Encoding.UTF8)) { vCardCollection contacts = Deserializer.FromStreamReader(sr); // Fill groups for each contact foreach (vCard contact in contacts) { foreach (EmailAddress email in contact.EmailAddresses) { if (!data.ContainsKey(email.Email.Address)) { data.Add(email.Email.Address, new List <string>()); } if (isGeneralGroup) { continue; } if (!data[email.Email.Address].Contains(group)) { data[email.Email.Address].Add(group); } } } } } // Build the output csv file using (var writer = new StreamWriter(outFile)) using (var csv = new CsvWriter(writer)) { foreach (var item in data) { var groups = FormatGroups(item.Value); csv.WriteRecord(new { Email = item.Key, Groups = groups }); csv.NextRecord(); } } System.Console.WriteLine($"Written at '{outFile}'."); }