Пример #1
0
 private static vCard Deserialize(string vcardData, vCardStandardReader serializer)
 {
     using (var reader = new StringReader(vcardData))
     {
         return(serializer.Read(reader));
     }
 }
Пример #2
0
        public void ReadProperty_String_Name_Subproperty_Value()
        {

            vCardStandardReader reader =
                new vCardStandardReader();

            vCardProperty property =
                reader.ReadProperty("NAME;SUB:VALUE");

            Assert.AreEqual(
                "NAME",
                property.Name,
                "The Name is incorrect.");

            Assert.AreEqual(
                1,
                property.Subproperties.Count,
                "The Subproperties collection has an incorrect number of items.");

            Assert.AreEqual(
                "SUB",
                property.Subproperties[0].Name,
                "The Subproperty value is incorrect.");

            Assert.AreEqual(
                "VALUE",
                property.Value,
                "The parsed value is incorrect.");

        }
Пример #3
0
        public void ReadProperty_String_Name_Value()
        {

            // This function tests the parsing function
            // against a basic string like NAME:VALUE.

            vCardStandardReader reader = new vCardStandardReader();

            vCardProperty property = reader.ReadProperty(
                TestName + ":" + TestValue);

            Assert.AreEqual(
                TestName,
                property.Name);

            Assert.AreEqual(
                TestValue,
                property.Value,
                "The parsed value is incorrect.");

            Assert.IsEmpty(
                property.Subproperties,
                "The Subproperties collection should be empty.");

        }
Пример #4
0
        public void ReadProperty_String_Name_Subproperty_Subvalue_Value()
        {

            vCardStandardReader reader =
                new vCardStandardReader();

            vCardProperty property =
                reader.ReadProperty("TEL;TYPE=WORK:800-929-5805");

            Assert.AreEqual(
                "TEL",
                property.Name,
                "The name of the property should be TEL");

            Assert.AreEqual(
                1,
                property.Subproperties.Count,
                "There should be exactly one subproperty.");

            Assert.AreEqual(
                "TYPE",
                property.Subproperties[0].Name,
                "The name of the subproperty should be TYPE.");

            Assert.AreEqual(
                "WORK",
                property.Subproperties[0].Value,
                "The value of the subproperty should be WORK.");

            Assert.AreEqual(
                "800-929-5805",
                property.Value,
                "The value of the property is not correct.");

        }
Пример #5
0
        /// <summary>
        ///     Writes a card, then reads it back and compares fields.
        /// </summary>
        public static void CycleStandard21(vCard card)
        {
            if (card == null)
            {
                throw new ArgumentNullException("cycle");
            }

            // Create a memory stream to hold the contents of the card.

            MemoryStream stream = new MemoryStream();

            StreamWriter textWriter = new StreamWriter(stream);

            // Create a standard vCard writer and export the
            // card data to the stream.

            vCardStandardWriter writer = new vCardStandardWriter();

            writer.Write(card, textWriter);
            textWriter.Flush();

            // Reset the stream (back to its beginning), then
            // create a stream reader capable of reading text
            // lines from the stream.

            stream.Seek(0, SeekOrigin.Begin);
            StreamReader streamReader = new StreamReader(stream);

            vCardStandardReader standardReader = new vCardStandardReader();
            vCard reloaded = standardReader.Read(streamReader);

            Equals(card, reloaded);
        }
Пример #6
0
        /// <summary>
        ///     Loads a new instance of the <see cref="vCard"/> class
        ///     from a text reader.
        /// </summary>
        /// <param name="input">
        ///     An initialized text reader.
        /// </param>
        public vCard(TextReader input)
            : this()
        {
            vCardReader reader = new vCardStandardReader();

            reader.ReadInto(this, input);
        }
Пример #7
0
        public void ReadProperty_Blank_Subproperty()
        {
            vCardStandardReader reader =
                new vCardStandardReader();

            Assert.DoesNotThrow(
                () => { reader.ReadProperty("NAME;:VALUE"); },
                "Exception was thrown.");
        }
Пример #8
0
 /// <summary>
 ///     Loads a new instance of the <see cref="vCard"/> class
 ///     from a text file.
 /// </summary>
 /// <param name="path">
 ///     The path to a text file containing vCard data in
 ///     any recognized vCard format.
 /// </param>
 public vCard(string path)
     : this()
 {
     using (StreamReader streamReader = new StreamReader(path))
     {
         vCardReader reader = new vCardStandardReader();
         reader.ReadInto(this, streamReader);
     }
 }
Пример #9
0
        public void ReadProperty_String_SingleColon()
        {
            vCardStandardReader reader = new vCardStandardReader();
            reader.ReadProperty(":");

            Assert.AreEqual(
                1,
                reader.Warnings.Count,
                "A single colon should have caused a warning.");

        }
Пример #10
0
        public void ReadProperty_String_Whitespace()
        {
            vCardStandardReader reader = new vCardStandardReader();
            reader.ReadProperty("  ");

            Assert.AreEqual(
                1,
                reader.Warnings.Count,
                "A string with only whitespace should have caused a warning.");

        }
        public void ReadProperty_String_MissingColon()
        {
            vCardStandardReader reader = new vCardStandardReader();

            reader.ReadProperty("TEL 911");

            Assert.AreEqual(
                1,
                reader.Warnings.Count,
                "A missing colon should have caused a warning.");
        }
Пример #12
0
        public void ReadProperty_String_MissingName()
        {
            vCardStandardReader reader = new vCardStandardReader();
            reader.ReadProperty(":VALUE");

            Assert.AreEqual(
                1,
                reader.Warnings.Count,
                "A missing name should have caused a warning.");

        }
Пример #13
0
        private static List <Contact> Parse(TextReader reader)
        {
            vCardReader  vcReader = new vCardStandardReader();
            List <vCard> data     = vcReader.ReadList(reader);

            List <Contact> contacts = new List <Contact>(data.Count);

            foreach (vCard each in data)
            {
                contacts.Add(ParseVCard(each));
            }

            return(contacts);
        }
 private static vCard Deserialize(string vcardData, vCardStandardReader serializer)
 {
     using (var reader = new StringReader(vcardData))
     {
         var card = serializer.Read(reader);
         if (serializer.Warnings.Count > 0)
         {
             var warningsBuilder = new StringBuilder();
             foreach (var warning in serializer.Warnings)
             {
                 warningsBuilder.AppendLine(warning);
             }
             s_logger.WarnFormat("Encountered warnings while reading vCardData:\r\n{0}\r\n{1}", warningsBuilder, vcardData);
         }
         return(card);
     }
 }
Пример #15
0
        /// <summary>
        ///     Loads a new instance of the <see cref="vCard"/> class
        ///     from a text file.
        /// </summary>
        /// <param name="path">
        ///     The path to a text file containing vCard data in
        ///     any recognized vCard format.
        /// </param>
        public vCard(string path)
            : this()
        {
            using (StreamReader streamReader = new StreamReader(path))
            {
                vCardReader reader = new vCardStandardReader();
                reader.ReadInto(this, streamReader);
            }

            //String example = "BEGIN:VCARD\nVERSION:3.0\nN:;Saad;;;\nFN:Saad\nTEL;TYPE=CELL:418-271-3874\nTEL;TYPE=HOME:418-524-7721\nEND:VCARD";
            // using (MemoryStream s = GenerateStreamFromString(example))
            //{
            //    vCardReader reader = new vCardStandardReader();
            //    TextReader streamReader = new StreamReader(s, Encoding.Default);
            //    reader.ReadInto(this, streamReader);
            //}
        }
Пример #16
0
        public void SamplevCardReadAndWriteTestWithEmailTypeFormat()
        {
            vCard card = new vCard();

            card.EmailAddresses.Add(new vCardEmailAddress()
            {
                Address = "*****@*****.**", EmailType = vCardEmailAddressType.Internet, IsPreferred = true, ItemType = ItemType.WORK
            });



            card.UniqueId = Guid.NewGuid().ToString("N");

            string text = card.ToString();

            vCardStandardWriter writer = new vCardStandardWriter();

            using (StringWriter sw = new StringWriter())
            {
                writer.Write(card, sw);

                sw.Flush();
                text = sw.ToString();
                sw.Close();
            }


            Assert.IsNotNull(text);


            vCardStandardReader reader = new vCardStandardReader();

            using (StringReader sr = new StringReader(text))
            {
                vCard cardFromReader = reader.Read(sr);

                Assert.AreEqual(1, cardFromReader.EmailAddresses.Count);

                var email = cardFromReader.EmailAddresses.First();
                Assert.AreEqual(true, email.IsPreferred);
                Assert.AreEqual(ItemType.WORK, email.ItemType);
                Assert.AreEqual(vCardEmailAddressType.Internet, email.EmailType);
                Assert.AreEqual("*****@*****.**", email.Address);
            }
        }
Пример #17
0
        public void ReadProperty_String_QuotedPrintable()
        {

            const string encodedValue =
                "LABEL;" +
                "HOME;" +
                "ENCODING=QUOTED-PRINTABLE:" +
                "129 15th Street #3=0D=0A" +
                "Minneapolis, MN 55403=0D=0A" +
                "United States of America";

            const string decodedValue =
                "129 15th Street #3\r\n" +
                "Minneapolis, MN 55403\r\n" +
                "United States of America";

            vCardStandardReader reader =
                new vCardStandardReader();

            // Read the property string.  It should
            // be decoded by the reader.

            vCardProperty property =
                reader.ReadProperty(encodedValue);

            Assert.AreEqual(
                "LABEL",
                property.Name,
                "The name of the property should be LABEL.");

            Assert.IsTrue(
                property.Subproperties.Contains("HOME"),
                "The property should have a subproperty called HOME.");

            // Now for the big test.  The loaded property
            // value should be decoded.  It should not have the
            // quoted-printable escape sequences.

            Assert.AreEqual(
                decodedValue,
                property.ToString());

        }
Пример #18
0
        public void ShouldReadvCardWithIMFromEmClient()
        {
            string vCardRequest = @"VERSION:3.0
NAME:Aqib Talib
N:Talib;Aqib;;;
FN:Aqib Talib
ADR;HOME:;;1 Aqib Way;Foxboro;MA;;United States
EMAIL;TYPE=INTERNET;TYPE=HOME:[email protected]
IMPP;X-SERVICE-TYPE;TYPE=OTHER::google:[email protected]
IMPP:ymsgr:talibonyahoo
IMPP:xmpp:talib_jabber
PRODID:-//eM Client/5.0.19406.0
REV:2014-01-15T21:02:43Z
TEL;CELL:(362) 733-2833
UID:D69D252D-3A87-4EC2-A438-800F0234BC54
END:VCARD";

            vCardStandardReader cardReader = new vCardStandardReader();

            using (StringReader sr = new StringReader(vCardRequest))
            {
                var card = cardReader.Read(sr);


                var im = card.IMs.FirstOrDefault(m => m.ServiceType == IMServiceType.GoogleTalk);

                Assert.IsNotNull(im);

                Assert.AreEqual(IMServiceType.GoogleTalk, im.ServiceType, "service type not set to google talk");
                Assert.AreEqual("*****@*****.**", im.Handle);

                var yahooIM = card.IMs.FirstOrDefault(m => m.ServiceType == IMServiceType.Yahoo);
                Assert.IsNotNull(yahooIM);
                Assert.AreEqual(IMServiceType.Yahoo, yahooIM.ServiceType, "serviceType not set for yahoo");
                Assert.AreEqual("talibonyahoo", yahooIM.Handle);


                var jabberIM = card.IMs.FirstOrDefault(m => m.ServiceType == IMServiceType.Jabber);
                Assert.IsNotNull(jabberIM);
                Assert.AreEqual(IMServiceType.Jabber, jabberIM.ServiceType, "serviceType not set for jabber");
                Assert.AreEqual("talib_jabber", jabberIM.Handle);
            }
        }
Пример #19
0
        public void ReadProperty_String_Name_Subproperties_Value()
        {

            // This function tests the parser against a property
            // string with two subproperties.

            vCardStandardReader reader =
                new vCardStandardReader();

            vCardProperty property =
                reader.ReadProperty("NAME;SUB1;SUB2:VALUE");

            Assert.AreEqual(
                "NAME",
                property.Name,
                "The Name is incorrect.");

            Assert.AreEqual(
                2,
                property.Subproperties.Count,
                "The Subproperties collection has an incorrect number of items.");

            Assert.AreEqual(
                "SUB1",
                property.Subproperties[0].Name,
                "The Subproperty[0] value is incorrect.");

            Assert.AreEqual(
                "SUB2",
                property.Subproperties[1].Name,
                "The Subproperty[1] value is incorrect.");

            Assert.AreEqual(
                "VALUE",
                property.Value,
                "The parsed value is incorrect.");

        }
        private static bool TryDeserialize(
            string vcardData,
            out vCard vcard,
            WebResourceName uriOfAddressbookForLogging,
            vCardStandardReader deserializer,
            ILoadEntityLogger logger)
        {
            vcard = null;
            string fixedVcardData  = ContactDataPreprocessor.FixRevisionDate(vcardData);
            string fixedVcardData2 = ContactDataPreprocessor.FixUrlType(fixedVcardData);

            try
            {
                vcard = Deserialize(fixedVcardData2, deserializer);
                return(true);
            }
            catch (Exception x)
            {
                s_logger.Error(string.Format("Could not deserialize vcardData of '{0}':\r\n{1}", uriOfAddressbookForLogging, fixedVcardData2), x);
                logger.LogSkipLoadBecauseOfError(uriOfAddressbookForLogging, x);
                return(false);
            }
        }
        protected override bool TryDeserialize(
            string vcardData,
            out vCard vcard,
            WebResourceName uriOfAddressbookForLogging,
            vCardStandardReader deserializer,
            ILoadEntityLogger logger)
        {
            vcard = null;

            // fix some linebreak issues with Open-Xchange
            string normalizedVcardData = vcardData.Contains("\r\r\n") ? ContactDataPreprocessor.NormalizeLineBreaks(vcardData) : vcardData;

            try
            {
                vcard = Deserialize(normalizedVcardData, deserializer);
                return(true);
            }
            catch (Exception x)
            {
                s_logger.Error(string.Format("Could not deserialize vcardData of '{0}':\r\n{1}", uriOfAddressbookForLogging, normalizedVcardData), x);
                logger.LogSkipLoadBecauseOfError(uriOfAddressbookForLogging, x);
                return(false);
            }
        }
Пример #22
0
        /// <summary>
        /// Convert the byte array to a WinRT Contact.
        /// Matching is not 1:1, but this methods tries to convert as much of the data as possible.
        /// </summary>
        /// <param name="vCardByte">Business card vCard string as a UTF8 encoded byte array.</param>
        private Contact ParseDataToContact(byte[] vCardByte)
        {
            var vcReader = new vCardStandardReader();
            var vc       = vcReader.Read(new StringReader(Encoding.UTF8.GetString(vCardByte, 0, vCardByte.Length)));

            var convertedContact = new Contact
            {
                FirstName           = vc.GivenName,
                LastName            = vc.FamilyName,
                HonorificNamePrefix = vc.NamePrefix,
                HonorificNameSuffix = vc.NameSuffix
            };

            // Phone numbers
            foreach (var phone in vc.Phones)
            {
                convertedContact.Phones.Add(ConvertVcardToPhone(phone));
            }

            // Email
            foreach (var email in vc.EmailAddresses)
            {
                convertedContact.Emails.Add(ConvertVcardToEmail(email));
            }

            // Postal address
            foreach (var address in vc.DeliveryAddresses)
            {
                convertedContact.Addresses.Add(ConvertVcardToAddress(address));
            }

            // Notes
            foreach (var note in vc.Notes)
            {
                if (convertedContact.Notes != null)
                {
                    convertedContact.Notes += "\n" + note.Text;
                }
                else
                {
                    convertedContact.Notes = note.Text;
                }
            }

            // Dates
            if (vc.BirthDate != null)
            {
                var birthDay = (DateTime)vc.BirthDate;
                convertedContact.ImportantDates.Add(new ContactDate
                {
                    Kind  = ContactDateKind.Birthday,
                    Year  = birthDay.Year,
                    Month = (uint?)birthDay.Month,
                    Day   = (uint?)birthDay.Day
                });
            }

            // Websites
            foreach (var website in vc.Websites)
            {
                convertedContact.Websites.Add(ConvertVcardToWebsite(website));
            }

            // Job info
            if (!String.IsNullOrEmpty(vc.Organization) ||
                !String.IsNullOrEmpty(vc.Department) ||
                !String.IsNullOrEmpty(vc.Title))
            {
                var jobInfo = new ContactJobInfo();
                if (!String.IsNullOrEmpty(vc.Organization))
                {
                    jobInfo.CompanyName = vc.Organization;
                }
                if (!String.IsNullOrEmpty(vc.Department))
                {
                    jobInfo.Department = vc.Department;
                }
                if (!String.IsNullOrEmpty(vc.Title))
                {
                    jobInfo.Title = vc.Title;
                }
                convertedContact.JobInfo.Add(jobInfo);
            }
            return(convertedContact);
        }
        public void ReadProperty_String_NullParameter()
        {
            vCardStandardReader reader = new vCardStandardReader();

            reader.ReadProperty((string)null);
        }
Пример #24
0
        public async Task <ActionResult> MailWebhook()
        {
            // Initialize a mandrill client for sending emails
            var    mandrill = new Mandrill.MandrillApi(this.mandrillApiKey);
            string sender   = null;

            try
            {
                // Get the JSON payload
                string validJson = HttpContext.Request.Form["mandrill_events"].Replace("mandrill_events=", string.Empty);

                if (string.IsNullOrWhiteSpace(validJson))
                {
                    return(new HttpStatusCodeResult(400));
                }

                var webhookEvents = JsonConvert.DeserializeObject <List <WebHookEvent> >(validJson);
                if (webhookEvents == null)
                {
                    return(new HttpStatusCodeResult(400));
                }

                var results = new List <string>();

                foreach (var webhookEvent in webhookEvents)
                {
                    sender = webhookEvent.Msg.FromEmail;
                    var attachments = webhookEvent.Msg.Attachments;

                    // Verify the security by checking authorized senders
                    if (webhookEvent.Msg.Spf.Result != "pass" && webhookEvent.Msg.Dkim.Valid != true)
                    {
                        throw new Exception("Sender not authorized: SPF / DKIM Check failed.");
                    }

                    // Create an instance of the CRM service that acts in the name of the sender of the email
                    using (var service = new CrmVcardUpdateService(sender))
                    {
                        // Loop through the attachments
                        foreach (var attachment in attachments)
                        {
                            // Get the VCards
                            var filename = this.DecodeBase64Names(attachment.Key);

                            if ((attachment.Value.Type != "text/vcard" && attachment.Value.Type != "text/x-vcard") || !filename.EndsWith(".vcf"))
                            {
                                results.Add(string.Format("{0}: not imported (mime-type: {1})", filename, attachment.Value.Type));
                                continue;
                            }

                            var bytes        = attachment.Value.Base64 ? Convert.FromBase64String(attachment.Value.Content) : Encoding.UTF8.GetBytes(attachment.Value.Content);
                            var memoryStream = new MemoryStream(bytes);
                            var vcardReader  = new vCardStandardReader();
                            using (var streamreader = new StreamReader(memoryStream))
                            {
                                var vcard = vcardReader.Read(streamreader);

                                // Import the VCards into the CRM
                                var result = service.UpdateContactWithVcard(vcard, filename);
                                results.Add(result);
                            }
                        }
                    }
                }

                // Sends a mail with the results
                var email = new EmailMessage
                {
                    FromEmail = this.emailSendingAddress,
                    To        = new List <EmailAddress> {
                        new EmailAddress(sender ?? this.errorEmailRecipient)
                    },
                    Subject = "VCard import finished",
                    Text    = "Results:\t\n\t\n" + string.Join("\t\n", results),
                };

                await mandrill.SendMessage(new SendMessageRequest(email));

                return(this.View((object)validJson));
            }
            catch (Exception ex)
            {
                // Send a mail with the error
                var email = new EmailMessage
                {
                    FromEmail = this.emailSendingAddress,
                    To        = new List <EmailAddress> {
                        new EmailAddress(sender ?? this.errorEmailRecipient)
                    },
                    Subject = "Error in VCard Import",
                    Text    = JsonConvert.SerializeObject(ex, Formatting.Indented)
                };

                mandrill.SendMessage(new SendMessageRequest(email));

                throw;
            }
        }
Пример #25
0
        /*
         * BEGIN:VLIST
         * UID:4250-58658600-5-45D0678.vlf
         * VERSION:1.0
         * FN:Simpsons
         * CARD;[email protected];FN="Simpson, Homer":5228bf7b-f3a6-4c16-ae3e-90102d86ab43.vcf
         * CARD;[email protected];FN="Simpson, Marge":c520e3ad-3d19-4c2f-b093-3f17736bce8e.vcf
         * END:VLIST
         */

        protected override bool TryDeserialize(string vcardData, out DistributionList vcard, WebResourceName uriOfAddressbookForLogging, int deserializationThreadLocal, ILoadEntityLogger logger)
        {
            var cardReader = new vCardStandardReader();

            vcard = new DistributionList();

            using (var reader = new StringReader(vcardData))
            {
                vCardProperty property;
                do
                {
                    property = cardReader.ReadProperty(reader);
                    if (!string.IsNullOrEmpty(property?.Name))
                    {
                        var propNameToProcess = property.Name.ToUpperInvariant();

                        switch (propNameToProcess)
                        {
                        case "UID":
                            vcard.Uid = property.ToString();
                            break;

                        case "FN":
                            vcard.Name = property.ToString();
                            break;

                        case "DESCRIPTION":
                            vcard.Description = property.ToString();
                            break;

                        case "NICKNAME":
                            vcard.Nickname = property.ToString();
                            break;

                        case "CARD":
                            if (property.Value != null)
                            {
                                var emailAddress = property.Subproperties.GetValue("EMAIL");
                                var displayName  = property.Subproperties.GetValue("FN");
                                vcard.Members.Add(new KnownDistributionListMember(emailAddress, displayName, property.Value.ToString()));
                            }

                            break;

                        case NonAddressBookMemberValueName:
                            if (property.Value != null)
                            {
                                var    displayName  = property.Subproperties.GetValue("CN");
                                string emailAddress = null;
                                var    value        = property.Value.ToString();
                                if (!string.IsNullOrEmpty(value))
                                {
                                    if (value.StartsWith("mailto:", StringComparison.InvariantCultureIgnoreCase))
                                    {
                                        emailAddress = value.Substring(7);     //skip mailto:
                                    }
                                }

                                vcard.NonAddressBookMembers.Add(new DistributionListMember(emailAddress, displayName));
                            }

                            break;
                        }
                    }
                } while (property != null);
            }

            return(true);
        }
Пример #26
0
 private static bool TryDeserialize(string iCalData, out vCard vcard, Uri uriOfCalendarForLogging, vCardStandardReader deserializer)
 {
     vcard = null;
     try
     {
         vcard = Deserialize(iCalData, deserializer);
         return(true);
     }
     catch (Exception x)
     {
         s_logger.Error(string.Format("Could not deserilaize ICalData of '{0}':\r\n{1}", uriOfCalendarForLogging, iCalData), x);
         return(false);
     }
 }
Пример #27
0
 public void ReadProperty_String_NullParameter()
 {
     vCardStandardReader reader = new vCardStandardReader();
     Assert.Throws<ArgumentNullException>(()=>reader.ReadProperty((string)null));
 }
Пример #28
0
        public void SamlevCardReadAndWriteTestWithContentFromWikipedia()
        {
            string text = @"BEGIN:VCARD
VERSION:3.0
N:Gump;Forrest
FN:Forrest Gump
ORG:Bubba Gump Shrimp Co.
TITLE:Shrimp Man
PHOTO;VALUE=URL;TYPE=GIF:http://www.example.com/dir_photos/my_photo.gif
TEL;TYPE=WORK,VOICE:(111) 555-1212
TEL;TYPE=HOME,VOICE:(404) 555-1212
ADR;TYPE=WORK;type=pref:;;100 Waters Edge;Baytown;LA;30314;United States of America
EMAIL;TYPE=PREF,INTERNET:[email protected]
REV:2008-04-24T19:52:43Z
END:VCARD";

            //ADR;TYPE=HOME:;;42 Plantation St.;Baytown;LA;30314;United States of America
//LABEL;TYPE=HOME:42 Plantation St.\nBaytown, LA 30314\nUnited States of America


            vCardStandardReader reader = new vCardStandardReader();

            using (StringReader sr = new StringReader(text))
            {
                vCard cardFromReader = reader.Read(sr);

                Assert.AreEqual(1, cardFromReader.EmailAddresses.Count);

                var email = cardFromReader.EmailAddresses.First();
                Assert.AreEqual(true, email.IsPreferred);
                Assert.AreEqual(ItemType.UNSPECIFIED, email.ItemType);
                Assert.AreEqual(vCardEmailAddressType.Internet, email.EmailType);
                Assert.AreEqual("*****@*****.**", email.Address);


                Assert.AreEqual("Shrimp Man", cardFromReader.Title);
                Assert.AreEqual("Forrest", cardFromReader.GivenName);
                Assert.AreEqual("Gump", cardFromReader.FamilyName);


                Assert.AreEqual(2, cardFromReader.Phones.Count);

                var phone404 = cardFromReader.Phones.FirstOrDefault(x => x.FullNumber == "(404) 555-1212");
                var phone111 = cardFromReader.Phones.FirstOrDefault(x => x.FullNumber == "(111) 555-1212");

                Assert.IsNotNull(phone111);
                Assert.IsNotNull(phone404);

                Assert.IsTrue(phone111.IsWork);
                Assert.IsTrue(phone111.IsVoice);

                Assert.IsTrue(phone404.IsVoice);
                Assert.IsTrue(phone404.IsHome);

                Assert.AreEqual(1, cardFromReader.DeliveryAddresses.Count);
                var address = cardFromReader.DeliveryAddresses.First();
                Assert.IsNotNull(address);
                Assert.IsTrue(address.AddressType.Any(a => a == vCardDeliveryAddressTypes.Work), "work address type not found");
                Assert.IsTrue(address.AddressType.Any(a => a == vCardDeliveryAddressTypes.Preferred), "preferred address type not found");


                vCardStandardWriter standardWriter = new vCardStandardWriter();

                using (StringWriter sw = new StringWriter())
                {
                    standardWriter.Write(cardFromReader, sw);

                    sw.Flush();
                    var tempStrign = sw.ToString();

                    Assert.IsNotNull(tempStrign);
                }
            }



            //need to add social Profile types as property to the vCard object and reader/writer
            //need to try and add a bunch of properties in my ipad NAB and email me a .vcf file
            //then generate via my parser and try and import the VCF into my ipad
            //look at creating nuGet package for deploying the bin / dll
        }
Пример #29
0
        private static void Merge(string inputDir, string outputfile)
        {
            if (!Directory.Exists(inputDir))
            {
                throw new ArgumentException("inputDir");
            }
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            var incoming = new List <vCard>();

            var inputFiles = Directory.GetFiles(inputDir);

            foreach (var file in inputFiles)
            {
                var fi = new FileInfo(file);
                if (fi.Extension != ".vcf")
                {
                    continue;
                }
                var content = File.ReadAllText(fi.FullName);
                var tr      = new StringReader(content);
                var rdr     = new vCardStandardReader();
                var card    = rdr.Read(tr);
                incoming.Add(card);
            }

            var outgoing = new List <VCard>();

            foreach (var inc in incoming)
            {
                var card = new VCard
                {
                    Version          = VCardVersion.V3,
                    UniqueIdentifier = inc.UniqueId,
                    FirstName        = inc.GivenName,
                    LastName         = inc.FamilyName,
                    NickName         = Converter.ToString(inc.Nicknames),
                    Prefix           = inc.NamePrefix,
                    Suffix           = inc.NameSuffix,
                    FormattedName    = inc.DisplayName,
                    Organization     = inc.Organization,
                    Title            = inc.Title,
                    Telephones       = inc.Phones.Select(Converter.ConvertPhone),
                    Addresses        = inc.DeliveryAddresses.Select(Converter.ConvertAddress),
                    Emails           = inc.EmailAddresses.Select(Converter.ConvertEmail),
                    Categories       = Converter.ToArray(inc.Categories),
                    Classification   = Converter.ConvertClass(inc.AccessClassification),
                    Source           = Converter.ConvertSource(inc.Sources),

                    Anniversary           = null,
                    BirthDay              = null,
                    Longitude             = 0,
                    Latitude              = 0,
                    MiddleName            = string.Empty,
                    TimeZone              = null,
                    Photo                 = null,
                    CalendarAddresses     = null,
                    CalendarUserAddresses = null,
                    CustomExtensions      = null,
                    DeliveryAddress       = null,
                    Gender                = Gender.Unknown,
                    Impps                 = null,
                    Key                = string.Empty,
                    Kind               = Kind.Individual,
                    Languages          = null,
                    LastRevision       = null,
                    Logo               = null,
                    Mailer             = string.Empty,
                    Note               = string.Empty,
                    OrganizationalUnit = string.Empty,
                    Relations          = null,
                    Role               = inc.Role,
                    SortString         = string.Empty,
                    Sound              = string.Empty
                };
                outgoing.Add(card);
            }

            var serialized = outgoing.Serialize();

            File.WriteAllText(outputfile, serialized);
        }
Пример #30
0
        /// <summary>
        ///     Loads a new instance of the <see cref="vCard"/> class
        ///     from a text reader.
        /// </summary>
        /// <param name="input">
        ///     An initialized text reader.
        /// </param>
        public vCard(TextReader input)
            : this()
        {

            vCardReader reader = new vCardStandardReader();
            reader.ReadInto(this, input);

        }
Пример #31
0
        /// <summary>
        /// Convert the byte array to a WinRT Contact.
        /// Matching is not 1:1, but this methods tries to convert as much of the data as possible.
        /// </summary>
        /// <param name="vCardByte">Business card vCard string as a UTF8 encoded byte array.</param>
        private Contact ParseDataToContact(byte[] vCardByte)
        {
            var vcReader = new vCardStandardReader();
            var vc = vcReader.Read(new StringReader(Encoding.UTF8.GetString(vCardByte, 0, vCardByte.Length)));

            var convertedContact = new Contact
            {
                FirstName = vc.GivenName, 
                LastName = vc.FamilyName,
                HonorificNamePrefix = vc.NamePrefix,
                HonorificNameSuffix = vc.NameSuffix
            };

            // Phone numbers
            foreach (var phone in vc.Phones)
            {
                convertedContact.Phones.Add(ConvertVcardToPhone(phone));
            }

            // Email
            foreach (var email in vc.EmailAddresses)
            {
                convertedContact.Emails.Add(ConvertVcardToEmail(email));
            }

            // Postal address
            foreach (var address in vc.DeliveryAddresses)
            {
                convertedContact.Addresses.Add(ConvertVcardToAddress(address));
            }

            // Notes
            foreach (var note in vc.Notes)
            {
                if (convertedContact.Notes != null)
                {
                    convertedContact.Notes += "\n" + note.Text;
                }
                else
                {
                    convertedContact.Notes = note.Text;
                }
            }

            // Dates
            if (vc.BirthDate != null)
            {
                var birthDay = (DateTime) vc.BirthDate;
                convertedContact.ImportantDates.Add(new ContactDate
                {
                    Kind = ContactDateKind.Birthday,
                    Year = birthDay.Year,
                    Month = (uint?) birthDay.Month,
                    Day = (uint?) birthDay.Day
                });
            }

            // Websites
            foreach (var website in vc.Websites)
            {
                convertedContact.Websites.Add(ConvertVcardToWebsite(website));
            }

            // Job info
            if (!String.IsNullOrEmpty(vc.Organization) ||
                !String.IsNullOrEmpty(vc.Department) ||
                !String.IsNullOrEmpty(vc.Title))
            {
                var jobInfo = new ContactJobInfo();
                if (!String.IsNullOrEmpty(vc.Organization))
                {
                    jobInfo.CompanyName = vc.Organization;
                }
                if (!String.IsNullOrEmpty(vc.Department))
                {
                    jobInfo.Department = vc.Department;
                }
                if (!String.IsNullOrEmpty(vc.Title))
                {
                    jobInfo.Title = vc.Title;
                }
                convertedContact.JobInfo.Add(jobInfo);
            }
            return convertedContact;
        }
Пример #32
0
        public void ShouldReadvCardWithAllCBFieldsFilledOutFromiPhoneNAB()
        {
            string text = @"BEGIN:VCARD
VERSION:3.0
PRODID:-//Apple Inc.//iOS 6.0.1//EN
N:iOS;Nic;;;
FN:Nic iOS
ORG:Ibm;
TITLE:Sales Guy
item1.EMAIL;type=INTERNET;type=pref:[email protected]
EMAIL;type=INTERNET;type=WORK:[email protected]
EMAIL;type=INTERNET;type=WORK:[email protected]
EMAIL;type=INTERNET;type=HOME:[email protected]
EMAIL;type=INTERNET;type=HOME:[email protected]
TEL;type=CELL;type=VOICE;type=pref:(202) 333-4555
TEL;type=IPHONE;type=CELL;type=VOICE:(202) 333-4444
TEL;type=HOME;type=VOICE:(333) 222-2222
TEL;type=WORK;type=VOICE:(809) 555-6666 x444
TEL;type=MAIN:(609) 888-7777
TEL;type=HOME;type=FAX:(555) 444-4443
TEL;type=WORK;type=FAX:33322222222
item2.TEL:(999) 777-7999
item2.X-ABLabel:personal
item3.ADR;type=HOME;type=pref:;;8230 Boone Blvd;Vinna;VA;22182;United States
item3.X-ABADR:us
item4.URL;type=pref:http://facebook.com/max.solender
item4.X-ABLabel:Profile
item5.URL:www.ibm.com
item5.X-ABLabel:_$!<HomePage>!$_
item6.X-MSN:msnname
item6.X-ABLabel:_$!<Other>!$_
item7.X-AIM:aolname
item7.X-ABLabel:_$!<Other>!$_
item8.X-YAHOO:yahooname
item8.X-ABLabel:_$!<Other>!$_
item9.X-JABBER:jabbername
item9.X-ABLabel:_$!<Other>!$_
IMPP;X-SERVICE-TYPE=Skype;type=HOME;type=pref:skype:skypeusernameee
IMPP;X-SERVICE-TYPE=Skype;type=WORK:skype:worksyokeusername
item10.IMPP;X-SERVICE-TYPE=MSN:msnim:msnname
item10.X-ABLabel:_$!<Other>!$_
item11.IMPP;X-SERVICE-TYPE=AIM:aim:aolname
item11.X-ABLabel:_$!<Other>!$_
item12.IMPP;X-SERVICE-TYPE=GoogleTalk:xmpp:gtalkname
item12.X-ABLabel:_$!<Other>!$_
item13.IMPP;X-SERVICE-TYPE=Yahoo:ymsgr:yahooname
item13.X-ABLabel:_$!<Other>!$_
item14.IMPP;X-SERVICE-TYPE=Facebook:xmpp:fbchatname
item14.X-ABLabel:_$!<Other>!$_
item15.IMPP;X-SERVICE-TYPE=Jabber:xmpp:jabbername
item15.X-ABLabel:_$!<Other>!$_
item16.IMPP;X-SERVICE-TYPE=GaduGadu;type=HOME;type=pref:x-apple:jdgadu
X-SOCIALPROFILE;type=linkedin;x-user=nicatlinkedin:http://www.linkedin.com/in/nicatlinkedin
X-SOCIALPROFILE;type=twitter;x-user=tiffanystone:http://twitter.com/tiffanystone
X-SOCIALPROFILE;type=facebook;x-user=tiffatfacebook:http://www.facebook.com/tiffatfacebook
X-SOCIALPROFILE;type=twitter;x-user=gregabedard:http://twitter.com/gregabedard
PHOTO;TYPE=JPEG;ENCODING=BASE64:
 /9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQY
 GBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYa
 KCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAAR
 CAA3AEgDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAA
 AgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkK
 FhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWG
 h4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl
 5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREA
 AgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYk
 NOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOE
 hYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk
 5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwC3KUf7wwaiFvuPDDHrVh0yaiMeWrarK2pw
 wi2KLeFfvuD9KiuY4SmI1JPris3xHq0ek2jGMq1zjcseCeB3OK4+HxZdy3DPcXKwRkbVVEHX
 8a5f3k1dLQ6Y0ktzt4oBGc7efellkYDl1UflXAf23Pf+dbC/lSR8iOTdgA9gccVys012929t
 ctdyXCttZM96hU5vRs29nHqes3FzbqhaW6jwOD84pkSxzwiWE70PQiuJsYksIrYXcjiSWQKk
 PmEjJOOnSu58ORMbFgfugjH1wM05R5epnKNitNbjHIorUnh5orRSdjFm6RzUNyTHDI64DAEj
 NWShzXK/EKa4h0lI4Nw81yGYdgAa6KkeZ2FRTbsjm3uhe6m6wjzmZtssj8nnPT2r0bwl8PbX
 WkQTJkOcMw4K1434SWeS5crkhWz9TXtWjeNL62RUsbEKYQPnKnBx159awrNqVketQgoxba1J
 L/4GPFqUklpKGhjG4Ajlq8o8Z6i+m6rLDYpCXVArMUyQfTNfTcPxBYaJb382nSyGWQxbIsn5
 sZ544FfKPjW6sLjxNqrQvIiPcu+NucZOcfhVRSlruYT9ptJWK/hQf2lrol1OR55kUvCB8qof
 p3r1bw8mLGQej4/QV5n4Njt/7Zi8mV3cI2QVx2+tepaAP9Fn/wCup/kKjEJKyRzu9ncS5XBo
 pNUYxwyMvUDiiiEbo53ubgIrN8QQefp8oVBIVG7Yeje1Le38VlA007YRRn3P0rzjVviBfS3c
 kNrEkEe7ardWx/Ku2VCc37oUW07ot6FaLaSQ3ESnyZTnawwV7YNev6Jqun2nhq6eWKBJVjOD
 gDJxXik+tui20wybdkCvj+Fh1qGXUDrV59ne5ZbZV+VVPDH3FctWk+bU9mnW5Vdnufwq8S6X
 cm6tbqeNwxDqG6bhnp74r5d8R3sVzr+oz2/+rluJHQexY4r0AJpunaN9os3PmF9nQjBxya8+
 uNEfzA0dxEQ3IzxWtKHIr9DKtUU5PubnwzzLr7Z52wk/yFev6EmLSf8A66n+Qryz4c2Mmn6p
 cTXDJtaMKCpz1I/wr1bQmBs5COhkJrLEatHFOVmylrp227+/FFQeIXOFUHqaK0pR905Wzh9Z
 1P8AtdWmZiVUYxyB9MVw2ptJDqLM2MqR09+9FFe7XSVNWN6as7HU+CZI7u9u7C5BZJcSLnse
 9dLF8OWursHS7sQSMeFcZX/61FFeRXk4zdjqi/dOWuGkhlnspHDCCZ4zjoSDg4/nV/wJNC+t
 xW91Ek0UoZGV1yMjoR+VFFdc4r2TXkYSep2euafZ6ftlsrdY95+YLxnFa+iOY9MUHqSTRRXl
 PWKMZtsyNal3Tge1FFFdtKK5UZM//9k=
END:VCARD";

            vCardStandardReader reader = new vCardStandardReader();

            using (StringReader sr = new StringReader(text))
            {
                vCard c = reader.Read(sr);

                Assert.AreEqual(5, c.EmailAddresses.Count);

                CheckEmail(c.EmailAddresses, "*****@*****.**", ItemType.UNSPECIFIED, vCardEmailAddressType.Internet, true);
                CheckEmail(c.EmailAddresses, "*****@*****.**", ItemType.WORK, vCardEmailAddressType.Internet, false);
                CheckEmail(c.EmailAddresses, "*****@*****.**", ItemType.WORK, vCardEmailAddressType.Internet, false);
                CheckEmail(c.EmailAddresses, "*****@*****.**", ItemType.HOME, vCardEmailAddressType.Internet, false);
                CheckEmail(c.EmailAddresses, "*****@*****.**", ItemType.HOME, vCardEmailAddressType.Internet, false);



                Assert.AreEqual("Sales Guy", c.Title);
                Assert.AreEqual("Ibm", c.Organization);
                Assert.AreEqual("Nic", c.GivenName);
                Assert.AreEqual("iOS", c.FamilyName);



                Assert.AreEqual(8, c.Phones.Count);

                CheckPhone(c.Phones, "(202) 333-4555", vCardPhoneTypes.Preferred | vCardPhoneTypes.Cellular | vCardPhoneTypes.Voice, true);
                CheckPhone(c.Phones, "(202) 333-4444", vCardPhoneTypes.IPhone | vCardPhoneTypes.Cellular | vCardPhoneTypes.Voice, false);
                CheckPhone(c.Phones, "(333) 222-2222", vCardPhoneTypes.Home | vCardPhoneTypes.Voice, false);
                CheckPhone(c.Phones, "(809) 555-6666 x444", vCardPhoneTypes.Work | vCardPhoneTypes.Voice, false);
                CheckPhone(c.Phones, "(609) 888-7777", vCardPhoneTypes.Main, false);
                CheckPhone(c.Phones, "(555) 444-4443", vCardPhoneTypes.Home | vCardPhoneTypes.Fax, false);
                CheckPhone(c.Phones, "33322222222", vCardPhoneTypes.Work | vCardPhoneTypes.Fax, false);
                CheckPhone(c.Phones, "(999) 777-7999", vCardPhoneTypes.Default, false);


                //phones and emails are good
                //need to check the physical address parsing and on down

                CheckAddress(c.DeliveryAddresses, "8230 Boone Blvd", "Vinna", "VA", "22182", "United States", vCardDeliveryAddressTypes.Preferred & vCardDeliveryAddressTypes.Home, true);

                CheckIM(c.IMs, "skypeusernameee", IMServiceType.Skype, ItemType.HOME, true);
                CheckIM(c.IMs, "worksyokeusername", IMServiceType.Skype, ItemType.WORK, false);
                CheckIM(c.IMs, "msnname", IMServiceType.MSN, ItemType.UNSPECIFIED, false);
                CheckIM(c.IMs, "aolname", IMServiceType.AIM, ItemType.UNSPECIFIED, false);
                CheckIM(c.IMs, "gtalkname", IMServiceType.GoogleTalk, ItemType.UNSPECIFIED, false);
                CheckIM(c.IMs, "yahooname", IMServiceType.Yahoo, ItemType.UNSPECIFIED, false);
                CheckIM(c.IMs, "fbchatname", IMServiceType.Facebook, ItemType.UNSPECIFIED, false);
                CheckIM(c.IMs, "jabbername", IMServiceType.Jabber, ItemType.UNSPECIFIED, false);
                CheckIM(c.IMs, "jdgadu", IMServiceType.GaduGadu, ItemType.HOME, true);

                Assert.AreEqual(4, c.SocialProfiles.Count);
                CheckSocialProfile(c.SocialProfiles, "nicatlinkedin", "http://www.linkedin.com/in/nicatlinkedin", SocialProfileServiceType.LinkedIn);
                CheckSocialProfile(c.SocialProfiles, "tiffanystone", "http://twitter.com/tiffanystone", SocialProfileServiceType.Twitter);
                CheckSocialProfile(c.SocialProfiles, "tiffatfacebook", "http://www.facebook.com/tiffatfacebook", SocialProfileServiceType.Facebook);
                CheckSocialProfile(c.SocialProfiles, "gregabedard", "http://twitter.com/gregabedard", SocialProfileServiceType.Twitter);

                Assert.AreEqual(1, c.Photos.Count);
                var photo = c.Photos.First();

                Assert.IsFalse(photo.HasEncodedData, "encoded data should is true");
                var encodedString = photo.EncodedData;

                Assert.IsTrue(string.IsNullOrEmpty(encodedString), "encoded data is empty");

                System.Drawing.Bitmap bitmap = photo.GetBitmap();

                Assert.IsNotNull(bitmap);


                //temp quickly
                vCardStandardWriter writer = new vCardStandardWriter();

                using (StringWriter sw = new StringWriter())
                {
                    writer.Write(c, sw);

                    sw.Flush();
                    text = sw.ToString();
                    sw.Close();
                }


                Assert.IsNotNull(text);
            }
        }