Ejemplo n.º 1
0
        public void SearchCriteriaEqual()
        {
            // Arrange
            var searchCriteria = new SearchCriteriaEqual(FilterField.CampaignName, "abc123");

            // Act
            var result = searchCriteria.ToString();

            // Assert
            result.ShouldNotBeNull();
            result.ShouldBe("campaign_name=\"abc123\"");
        }
Ejemplo n.º 2
0
        public void SearchCriteriaEqual()
        {
            // Arrange
            var searchCriteria = new SearchCriteriaEqual <ContactsFilterField>(ContactsFilterField.LastName, "Smith");

            // Act
            var result = searchCriteria.ToString();

            // Assert
            result.ShouldNotBeNull();
            result.ShouldBe("last_name=\"Smith\"");
        }
Ejemplo n.º 3
0
        public async Task SearchMessages_single_criteria()
        {
            // Arrange
            var limit = 25;

            var mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect(HttpMethod.Get, Utils.GetSendGridApiUri(ENDPOINT) + $"?limit={limit}&query=subject%3D%22thevalue%22").Respond("application/json", ONE_MESSAGE_FOUND);

            var client          = Utils.GetFluentClient(mockHttp);
            var emailActivities = (IEmailActivities) new EmailActivities(client);

            var criteria = new SearchCriteriaEqual(FilterField.Subject, "thevalue");

            // Act
            var result = await emailActivities.SearchAsync(criteria, limit, CancellationToken.None).ConfigureAwait(false);

            // Assert
            mockHttp.VerifyNoOutstandingExpectation();
            mockHttp.VerifyNoOutstandingRequest();
            result.ShouldNotBeNull();
            result.Length.ShouldBe(1);
        }
Ejemplo n.º 4
0
        public async Task RunAsync(IClient client, TextWriter log, CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                return;
            }

            await log.WriteLineAsync("\n***** LISTS AND SEGMENTS *****\n").ConfigureAwait(false);

            // GET LISTS
            var paginatedLists = await client.Lists.GetAllAsync(100, null, cancellationToken).ConfigureAwait(false);

            await log.WriteLineAsync($"Retrieved {paginatedLists.Records.Length} lists").ConfigureAwait(false);

            // GET SEGMENTS
            var segments = await client.Segments.GetAllAsync(null, cancellationToken).ConfigureAwait(false);

            await log.WriteLineAsync($"All segments retrieved. There are {segments.Length} segments").ConfigureAwait(false);

            // CLEANUP PREVIOUS INTEGRATION TESTS THAT MIGHT HAVE BEEN INTERRUPTED BEFORE THEY HAD TIME TO CLEANUP AFTER THEMSELVES
            var cleanUpTasks = paginatedLists.Records
                               .Where(l => l.Name.StartsWith("StrongGrid Integration Testing:"))
                               .Select(async oldList =>
            {
                await client.Lists.DeleteAsync(oldList.Id, false, cancellationToken).ConfigureAwait(false);
                await log.WriteLineAsync($"List {oldList.Id} deleted").ConfigureAwait(false);
                await Task.Delay(250, cancellationToken).ConfigureAwait(false);                            // Brief pause to ensure SendGrid has time to catch up
            })
                               .Union(segments
                                      .Where(s => s.Name.StartsWith("StrongGrid Integration Testing:"))
                                      .Select(async oldSegment =>
            {
                await client.Segments.DeleteAsync(oldSegment.Id, false, cancellationToken).ConfigureAwait(false);
                await log.WriteLineAsync($"Segment {oldSegment.Id} deleted").ConfigureAwait(false);
                await Task.Delay(250, cancellationToken).ConfigureAwait(false);                                    // Brief pause to ensure SendGrid has time to catch up
            }));
            await Task.WhenAll(cleanUpTasks).ConfigureAwait(false);

            // CREATE A LIST
            var list = await client.Lists.CreateAsync("StrongGrid Integration Testing: list #1", cancellationToken).ConfigureAwait(false);

            await log.WriteLineAsync($"List '{list.Name}' created. Id: {list.Id}").ConfigureAwait(false);

            // UPDATE THE LIST
            await client.Lists.UpdateAsync(list.Id, "StrongGrid Integration Testing: new name", cancellationToken).ConfigureAwait(false);

            await log.WriteLineAsync($"List '{list.Id}' updated").ConfigureAwait(false);

            // CREATE 3 CONTACTS AND ADD THEM TO THE TO THE LIST
            var contactId1 = await client.Contacts.UpsertAsync("*****@*****.**", "John", "Doe", listIds : new[] { list.Id }, cancellationToken : cancellationToken).ConfigureAwait(false);

            var contactId2 = await client.Contacts.UpsertAsync("*****@*****.**", "John", "Smith", listIds : new[] { list.Id }, cancellationToken : cancellationToken).ConfigureAwait(false);

            var contactId3 = await client.Contacts.UpsertAsync("*****@*****.**", "Bob", "Smith", listIds : new[] { list.Id }, cancellationToken : cancellationToken).ConfigureAwait(false);

            // CREATE A SEGMENT (one contact matches the criteria)
            var firstNameCriteria = new SearchCriteriaEqual <ContactsFilterField>(ContactsFilterField.FirstName, "John");
            var LastNameCriteria  = new SearchCriteriaEqual <ContactsFilterField>(ContactsFilterField.LastName, "Doe");
            var filterConditions  = new[]
            {
                new KeyValuePair <SearchLogicalOperator, IEnumerable <SearchCriteria <ContactsFilterField> > >(SearchLogicalOperator.And, new[] { firstNameCriteria, LastNameCriteria })
            };
            var segment = await client.Segments.CreateAsync("StrongGrid Integration Testing: First Name is John and last name is Doe", filterConditions, list.Id, cancellationToken).ConfigureAwait(false);

            await log.WriteLineAsync($"Segment '{segment.Name}' created. Id: {segment.Id}").ConfigureAwait(false);

            // UPDATE THE SEGMENT (three contacts match the criteria)
            var hotmailCriteria = new SearchCriteriaLike <ContactsFilterField>(ContactsFilterField.EmailAddress, "%hotmail.com");

            segment = await client.Segments.UpdateAsync(segment.Id, "StrongGrid Integration Testing: Recipients @ Hotmail", hotmailCriteria, cancellationToken).ConfigureAwait(false);

            await log.WriteLineAsync($"Segment {segment.Id} updated. The new name is: '{segment.Name}'").ConfigureAwait(false);

            // GET THE SEGMENT
            segment = await client.Segments.GetAsync(segment.Id, cancellationToken).ConfigureAwait(false);

            await log.WriteLineAsync($"Segment {segment.Id} retrieved.").ConfigureAwait(false);

            // REMOVE THE CONTACTS FROM THE LIST (THEY WILL AUTOMATICALLY BE REMOVED FROM THE HOTMAIL SEGMENT)
            await client.Lists.RemoveContactAsync(list.Id, contactId3, cancellationToken).ConfigureAwait(false);

            await client.Lists.RemoveContactsAsync(list.Id, new[] { contactId1, contactId2 }, cancellationToken).ConfigureAwait(false);

            // DELETE THE CONTACTS
            await client.Contacts.DeleteAsync(contactId2, cancellationToken).ConfigureAwait(false);

            await client.Contacts.DeleteAsync(new[] { contactId1, contactId3 }, cancellationToken).ConfigureAwait(false);

            // DELETE THE SEGMENT
            await client.Segments.DeleteAsync(segment.Id, false, cancellationToken).ConfigureAwait(false);

            await log.WriteLineAsync($"Segment {segment.Id} deleted").ConfigureAwait(false);

            // DELETE THE LIST
            await client.Lists.DeleteAsync(list.Id, false, cancellationToken).ConfigureAwait(false);

            await log.WriteLineAsync($"List {list.Id} deleted").ConfigureAwait(false);
        }
        public async Task RunAsync(IClient client, TextWriter log, CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                return;
            }

            await log.WriteLineAsync("\n***** CONTACTS AND CUSTOM FIELDS *****\n").ConfigureAwait(false);

            // GET ALL FIELDS
            var fields = await client.CustomFields.GetAllAsync(cancellationToken).ConfigureAwait(false);

            await log.WriteLineAsync($"All custom fields retrieved. There are {fields.Length} fields").ConfigureAwait(false);

            // CLEANUP PREVIOUS INTEGRATION TESTS THAT MIGHT HAVE BEEN INTERRUPTED BEFORE THEY HAD TIME TO CLEANUP AFTER THEMSELVES
            var cleanUpTasks = fields
                               .Where(f => f.Name.StartsWith("stronggrid_"))
                               .Select(async oldField =>
            {
                await client.CustomFields.DeleteAsync(oldField.Id, cancellationToken).ConfigureAwait(false);
                await log.WriteLineAsync($"Field {oldField.Name} deleted").ConfigureAwait(false);
                await Task.Delay(250).ConfigureAwait(false);                            // Brief pause to ensure SendGrid has time to catch up
            });
            await Task.WhenAll(cleanUpTasks).ConfigureAwait(false);

            var nicknameField = await client.CustomFields.CreateAsync("stronggrid_nickname", FieldType.Text, cancellationToken).ConfigureAwait(false);

            await log.WriteLineAsync($"Field {nicknameField.Name} created. The Id of this new field is {nicknameField.Id}").ConfigureAwait(false);

            var ageField = await client.CustomFields.CreateAsync("stronggrid_age", FieldType.Number, cancellationToken).ConfigureAwait(false);

            await log.WriteLineAsync($"Field {ageField.Name} created. The Id of this new field is {ageField.Id}").ConfigureAwait(false);

            var customerSinceField = await client.CustomFields.CreateAsync("stronggrid_customer_since", FieldType.Date, cancellationToken).ConfigureAwait(false);

            await log.WriteLineAsync($"Field {customerSinceField.Name} created. The Id of this new field is {customerSinceField.Id}").ConfigureAwait(false);

            //--------------------------------------------------
            // We must wait for the custom fields to be ready.
            // I don't know exactly how long we should wait, but after a lot of trial/error I have settled on 5 seconds.
            // If we don't wait long enough, we get an 'invalid custom field ids supplied' exception when inserting a new contact.
            await Task.Delay(TimeSpan.FromSeconds(5)).ConfigureAwait(false);

            //--------------------------------------------------

            fields = await client.CustomFields.GetAllAsync(cancellationToken).ConfigureAwait(false);

            await log.WriteLineAsync($"All custom fields retrieved. There are {fields.Length} fields").ConfigureAwait(false);

            var email           = "*****@*****.**";
            var firstName       = "John";
            var lastName        = "Doe";
            var addressLine1    = "123 Main Street";
            var addressLine2    = "Suite 123";
            var city            = "Tinytown";
            var stateOrProvince = "Florida";
            var country         = "USA";
            var postalCode      = "12345";
            var alternateEmails = new[] { "*****@*****.**", "*****@*****.**" };
            var customFields    = new Field[]
            {
                new Field <string>(nicknameField.Id, nicknameField.Name, "Joe"),
                new Field <long>(ageField.Id, ageField.Name, 42),
                new Field <DateTime>(customerSinceField.Id, customerSinceField.Name, new DateTime(2015, 2, 5))
            };
            await client.Contacts.UpsertAsync(email, firstName, lastName, addressLine1, addressLine2, city, stateOrProvince, country, postalCode, alternateEmails, customFields, null, cancellationToken).ConfigureAwait(false);

            await log.WriteLineAsync($"Contact {email} created: {firstName} {lastName}").ConfigureAwait(false);

            var(contacts, contactsCount) = await client.Contacts.GetAllAsync(cancellationToken).ConfigureAwait(false);

            await log.WriteLineAsync($"Retrieved the first {contacts.Length} contacts out of a total of {contactsCount}.").ConfigureAwait(false);

            foreach (var record in contacts)
            {
                await log.WriteLineAsync($"\t{record.FirstName} {record.LastName}").ConfigureAwait(false);
            }

            if (contacts.Any())
            {
                var contact = await client.Contacts.GetAsync(contacts.First().Id).ConfigureAwait(false);

                await log.WriteLineAsync($"Retrieved contact {contact.Id}").ConfigureAwait(false);

                await log.WriteLineAsync($"\tEmail: {contact.Email}").ConfigureAwait(false);

                await log.WriteLineAsync($"\tFirst Name: {contact.FirstName}").ConfigureAwait(false);

                await log.WriteLineAsync($"\tLast Name: {contact.LastName}").ConfigureAwait(false);

                await log.WriteLineAsync($"\tCreated On:{contact.CreatedOn}").ConfigureAwait(false);

                await log.WriteLineAsync($"\tModified On: {contact.ModifiedOn}").ConfigureAwait(false);

                foreach (var customField in contact.CustomFields.OfType <Field <string> >())
                {
                    await log.WriteLineAsync($"\t{customField.Name}: {customField.Value}").ConfigureAwait(false);
                }
                foreach (var customField in contact.CustomFields.OfType <Field <long> >())
                {
                    await log.WriteLineAsync($"\t{customField.Name}: {customField.Value}").ConfigureAwait(false);
                }
                foreach (var customField in contact.CustomFields.OfType <Field <DateTime> >())
                {
                    await log.WriteLineAsync($"\t{customField.Name}: {customField.Value}").ConfigureAwait(false);
                }
            }

            var firstNameCriteria = new SearchCriteriaEqual <ContactsFilterField>(ContactsFilterField.FirstName, "John");
            var LastNameCriteria  = new SearchCriteriaEqual <ContactsFilterField>(ContactsFilterField.LastName, "Doe");
            var searchResult      = await client.Contacts.SearchAsync(new[] { firstNameCriteria, LastNameCriteria }, cancellationToken).ConfigureAwait(false);

            await log.WriteLineAsync($"Found {searchResult.Length} contacts named John Doe").ConfigureAwait(false);

            var(totalCount, billableCount) = await client.Contacts.GetCountAsync(cancellationToken).ConfigureAwait(false);

            await log.WriteLineAsync("Record counts").ConfigureAwait(false);

            await log.WriteLineAsync($"\tTotal: {totalCount}").ConfigureAwait(false);

            await log.WriteLineAsync($"\tBillable: {billableCount}").ConfigureAwait(false);

            var exportJobId = await client.Contacts.ExportAsync(FileType.Csv, null, null, default, cancellationToken).ConfigureAwait(false);