Example #1
0
        private Client(string apiKey, string username, string password, HttpClient httpClient, bool disposeClient, StrongGridClientOptions options)
        {
            _mustDisposeHttpClient = disposeClient;
            _httpClient            = httpClient;
            _options = options ?? GetDefaultOptions();

            _fluentClient = new FluentClient(new Uri(SENDGRID_V3_BASE_URI), httpClient)
                            .SetUserAgent(Client.UserAgent)
                            .SetRequestCoordinator(new SendGridRetryStrategy());

            _fluentClient.Filters.Remove <DefaultErrorFilter>();

            // Order is important: DiagnosticHandler must be first.
            // Also, the list of filters must be kept in sync with the filters in Utils.GetFluentClient in the unit testing project.
            _fluentClient.Filters.Add(new DiagnosticHandler(_options.LogLevelSuccessfulCalls, _options.LogLevelFailedCalls));
            _fluentClient.Filters.Add(new SendGridErrorHandler());

            if (!string.IsNullOrEmpty(apiKey))
            {
                _fluentClient.SetBearerAuthentication(apiKey);
            }
            if (!string.IsNullOrEmpty(username))
            {
                _fluentClient.SetBasicAuthentication(username, password);
            }

            AccessManagement   = new AccessManagement(_fluentClient);
            Alerts             = new Alerts(_fluentClient);
            ApiKeys            = new ApiKeys(_fluentClient);
            Batches            = new Batches(_fluentClient);
            Blocks             = new Blocks(_fluentClient);
            Bounces            = new Bounces(_fluentClient);
            Campaigns          = new Campaigns(_fluentClient);
            Categories         = new Categories(_fluentClient);
            Contacts           = new Contacts(_fluentClient);
            CustomFields       = new CustomFields(_fluentClient);
            Designs            = new Designs(_fluentClient);
            EmailActivities    = new EmailActivities(_fluentClient);
            EmailValidation    = new EmailValidation(_fluentClient);
            GlobalSuppressions = new GlobalSuppressions(_fluentClient);
            InvalidEmails      = new InvalidEmails(_fluentClient);
            IpAddresses        = new IpAddresses(_fluentClient);
            IpPools            = new IpPools(_fluentClient);
            Lists                = new Lists(_fluentClient);
            Mail                 = new Mail(_fluentClient);
            Segments             = new Segments(_fluentClient);
            SenderIdentities     = new SenderIdentities(_fluentClient);
            Settings             = new Settings(_fluentClient);
            SpamReports          = new SpamReports(_fluentClient);
            Statistics           = new Statistics(_fluentClient);
            Subusers             = new Subusers(_fluentClient);
            Suppressions         = new Suppressions(_fluentClient);
            Teammates            = new Teammates(_fluentClient);
            Templates            = new Templates(_fluentClient);
            UnsubscribeGroups    = new UnsubscribeGroups(_fluentClient);
            User                 = new User(_fluentClient);
            WebhookSettings      = new WebhookSettings(_fluentClient);
            WebhookStats         = new WebhookStats(_fluentClient);
            SenderAuthentication = new SenderAuthentication(_fluentClient);
        }
Example #2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BaseClient" /> class.
        /// </summary>
        /// <param name="apiKey">Your api key.</param>
        /// <param name="httpClient">Allows you to inject your own HttpClient. This is useful, for example, to setup the HtppClient with a proxy.</param>
        /// <param name="disposeClient">Indicates if the http client should be dispose when this instance of BaseClient is disposed.</param>
        /// <param name="options">Options for the SendGrid client.</param>
        /// <param name="logger">Logger.</param>
        public BaseClient(string apiKey, HttpClient httpClient, bool disposeClient, StrongGridClientOptions options, ILogger logger = null)
        {
            _mustDisposeHttpClient = disposeClient;
            _httpClient            = httpClient;
            _options = options;
            _logger  = logger ?? NullLogger.Instance;

            _fluentClient = new FluentClient(new Uri(SENDGRID_V3_BASE_URI), httpClient)
                            .SetUserAgent($"StrongGrid/{Version} (+https://github.com/Jericho/StrongGrid)")
                            .SetRequestCoordinator(new SendGridRetryStrategy());

            _fluentClient.Filters.Remove <DefaultErrorFilter>();

            // Remove all the built-in formatters and replace them with our custom JSON formatter
            _fluentClient.Formatters.Clear();
            _fluentClient.Formatters.Add(new JsonFormatter());

            // Order is important: DiagnosticHandler must be first.
            // Also, the list of filters must be kept in sync with the filters in Utils.GetFluentClient in the unit testing project.
            _fluentClient.Filters.Add(new DiagnosticHandler(_options.LogLevelSuccessfulCalls, _options.LogLevelFailedCalls, _logger));
            _fluentClient.Filters.Add(new SendGridErrorHandler());

            if (string.IsNullOrEmpty(apiKey))
            {
                throw new ArgumentNullException(apiKey);
            }
            _fluentClient.SetBearerAuthentication(apiKey);

            AccessManagement   = new AccessManagement(FluentClient);
            Alerts             = new Alerts(FluentClient);
            ApiKeys            = new ApiKeys(FluentClient);
            Batches            = new Batches(FluentClient);
            Blocks             = new Blocks(FluentClient);
            Bounces            = new Bounces(FluentClient);
            Designs            = new Designs(FluentClient);
            EmailActivities    = new EmailActivities(FluentClient);
            EmailValidation    = new EmailValidation(FluentClient);
            GlobalSuppressions = new GlobalSuppressions(FluentClient);
            InvalidEmails      = new InvalidEmails(FluentClient);
            IpAddresses        = new IpAddresses(FluentClient);
            IpPools            = new IpPools(FluentClient);
            Mail                 = new Mail(FluentClient);
            Settings             = new Settings(FluentClient);
            SpamReports          = new SpamReports(FluentClient);
            Statistics           = new Statistics(FluentClient);
            Subusers             = new Subusers(FluentClient);
            Suppressions         = new Suppressions(FluentClient);
            Teammates            = new Teammates(FluentClient);
            Templates            = new Templates(FluentClient);
            UnsubscribeGroups    = new UnsubscribeGroups(FluentClient);
            User                 = new User(FluentClient);
            WebhookSettings      = new WebhookSettings(FluentClient);
            WebhookStats         = new WebhookStats(FluentClient);
            SenderAuthentication = new SenderAuthentication(FluentClient);
        }
Example #3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Client"/> class.
 /// </summary>
 /// <param name="username">Your username.</param>
 /// <param name="password">Your password.</param>
 /// <param name="proxy">Allows you to specify a proxy.</param>
 /// <param name="options">Options for the SendGrid client.</param>
 public Client(string username, string password, IWebProxy proxy, StrongGridClientOptions options = null)
     : this(username, password, new HttpClientHandler {
     Proxy = proxy, UseProxy = proxy != null
 }, options)
 {
 }
Example #4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Client" /> class with a specific http client.
 /// </summary>
 /// <param name="apiKey">Your SendGrid API Key.</param>
 /// <param name="httpClient">Allows you to inject your own HttpClient. This is useful, for example, to setup the HtppClient with a proxy.</param>
 /// <param name="options">Options for the SendGrid client.</param>
 public Client(string apiKey, HttpClient httpClient, StrongGridClientOptions options = null)
     : this(apiKey, null, null, httpClient, false, options)
 {
 }
Example #5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Client"/> class with a specific handler.
 /// </summary>
 /// <param name="apiKey">Your SendGrid API Key.</param>
 /// <param name="handler">TThe HTTP handler stack to use for sending requests.</param>
 /// <param name="options">Options for the SendGrid client.</param>
 public Client(string apiKey, HttpMessageHandler handler, StrongGridClientOptions options = null)
     : this(apiKey, null, null, new HttpClient(handler), true, options)
 {
 }
Example #6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Client"/> class with a specific proxy.
 /// </summary>
 /// <param name="apiKey">Your SendGrid API Key.</param>
 /// <param name="proxy">Allows you to specify a proxy.</param>
 /// <param name="options">Options for the SendGrid client.</param>
 public Client(string apiKey, IWebProxy proxy, StrongGridClientOptions options = null)
     : this(apiKey, new HttpClientHandler {
     Proxy = proxy, UseProxy = proxy != null
 }, options)
 {
 }
Example #7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Client"/> class.
 /// </summary>
 /// <param name="apiKey">Your SendGrid API Key.</param>
 /// <param name="options">Options for the SendGrid client.</param>
 /// <param name="logger">Logger.</param>
 public Client(string apiKey, StrongGridClientOptions options = null, ILogger logger = null)
     : base(apiKey, null, false, options ?? _defaultOptions, logger)
 {
     Init();
 }
Example #8
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Client"/> class with a specific handler.
 /// </summary>
 /// <param name="apiKey">Your SendGrid API Key.</param>
 /// <param name="handler">TThe HTTP handler stack to use for sending requests.</param>
 /// <param name="options">Options for the SendGrid client.</param>
 /// <param name="logger">Logger.</param>
 public Client(string apiKey, HttpMessageHandler handler, StrongGridClientOptions options = null, ILogger logger = null)
     : base(apiKey, new HttpClient(handler), true, options ?? _defaultOptions, logger)
 {
     Init();
 }
Example #9
0
        public async Task <int> RunAsync()
        {
            // -----------------------------------------------------------------------------
            // Do you want to proxy requests through Fiddler? Can be useful for debugging.
            var useFiddler = false;

            // Logging options.
            var options = new StrongGridClientOptions()
            {
                LogLevelFailedCalls     = StrongGrid.Logging.LogLevel.Error,
                LogLevelSuccessfulCalls = StrongGrid.Logging.LogLevel.Debug
            };
            // -----------------------------------------------------------------------------

            // Configure StrongGrid client
            var apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY");
            var proxy  = useFiddler ? new WebProxy("http://localhost:8888") : null;
            var client = new Client(apiKey, proxy, options);

            // Configure Console
            var source = new CancellationTokenSource();

            Console.CancelKeyPress += (s, e) =>
            {
                e.Cancel = true;
                source.Cancel();
            };

            // Ensure the Console is tall enough and centered on the screen
            Console.WindowHeight = Math.Min(60, Console.LargestWindowHeight);
            Utils.CenterConsole();

            // These are the integration tests that we will execute
            var integrationTests = new Type[]
            {
                typeof(AccessManagement),
                typeof(Alerts),
                typeof(ApiKeys),
                typeof(Batches),
                typeof(Blocks),
                typeof(Bounces),
                typeof(CampaignsAndSenderIdentities),
                typeof(Categories),
                typeof(ContactsAndCustomFields),
                typeof(Designs),
                typeof(EmailActivities),
                typeof(EmailValidation),
                typeof(GlobalSuppressions),
                typeof(InvalidEmails),
                typeof(IpAddresses),
                typeof(IpPools),
                typeof(ListsAndSegments),
                typeof(Mail),
                typeof(SenderAuthentication),
                typeof(Settings),
                typeof(SpamReports),
                typeof(Statistics),
                typeof(Subusers),
                typeof(UnsubscribeGroupsAndSuppressions),
                typeof(Teammates),
                typeof(Templates),
                typeof(User),
                typeof(WebhookSettings),
                typeof(WebhookStats)
            };

            // Execute the async tests in parallel (with max degree of parallelism)
            var results = await integrationTests.ForEachAsync(
                async testType =>
            {
                var log = new StringWriter();

                try
                {
                    var integrationTest = (IIntegrationTest)Activator.CreateInstance(testType);
                    await integrationTest.RunAsync(client, log, source.Token).ConfigureAwait(false);
                    return(TestName : testType.Name, ResultCode : ResultCodes.Success, Message : string.Empty);
                }
                catch (OperationCanceledException)
                {
                    await log.WriteLineAsync($"-----> TASK CANCELLED").ConfigureAwait(false);
                    return(TestName : testType.Name, ResultCode : ResultCodes.Cancelled, Message : "Task cancelled");
                }
                catch (Exception e)
                {
                    var exceptionMessage = e.GetBaseException().Message;
                    await log.WriteLineAsync($"-----> AN EXCEPTION OCCURRED: {exceptionMessage}").ConfigureAwait(false);
                    return(TestName : testType.Name, ResultCode : ResultCodes.Exception, Message : exceptionMessage);
                }
                finally
                {
                    await Console.Out.WriteLineAsync(log.ToString()).ConfigureAwait(false);
                }
            }, MAX_SENDGRID_API_CONCURRENCY)
                          .ConfigureAwait(false);

            // Display summary
            var summary = new StringWriter();
            await summary.WriteLineAsync("\n\n**************************************************").ConfigureAwait(false);

            await summary.WriteLineAsync("******************** SUMMARY *********************").ConfigureAwait(false);

            await summary.WriteLineAsync("**************************************************").ConfigureAwait(false);

            var resultsWithMessage = results
                                     .Where(r => !string.IsNullOrEmpty(r.Message))
                                     .ToArray();

            if (resultsWithMessage.Any())
            {
                foreach (var(TestName, ResultCode, Message) in resultsWithMessage)
                {
                    const int TEST_NAME_MAX_LENGTH = 25;
                    var       name = TestName.Length <= TEST_NAME_MAX_LENGTH ? TestName : TestName.Substring(0, TEST_NAME_MAX_LENGTH - 3) + "...";
                    await summary.WriteLineAsync($"{name.PadRight(TEST_NAME_MAX_LENGTH, ' ')} : {Message}").ConfigureAwait(false);
                }
            }
            else
            {
                await summary.WriteLineAsync("All tests completed succesfully").ConfigureAwait(false);
            }

            await summary.WriteLineAsync("**************************************************").ConfigureAwait(false);

            await Console.Out.WriteLineAsync(summary.ToString()).ConfigureAwait(false);

            // Prompt user to press a key in order to allow reading the log in the console
            var promptLog = new StringWriter();
            await promptLog.WriteLineAsync("\n\n**************************************************").ConfigureAwait(false);

            await promptLog.WriteLineAsync("Press any key to exit").ConfigureAwait(false);

            Utils.Prompt(promptLog.ToString());

            // Return code indicating success/failure
            var resultCode = (int)ResultCodes.Success;

            if (results.Any(result => result.ResultCode != ResultCodes.Success))
            {
                if (results.Any(result => result.ResultCode == ResultCodes.Exception))
                {
                    resultCode = (int)ResultCodes.Exception;
                }
                else if (results.Any(result => result.ResultCode == ResultCodes.Cancelled))
                {
                    resultCode = (int)ResultCodes.Cancelled;
                }
                else
                {
                    resultCode = (int)results.First(result => result.ResultCode != ResultCodes.Success).ResultCode;
                }
            }

            return(await Task.FromResult(resultCode));
        }
Example #10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LegacyClient" /> class.
 /// </summary>
 /// <param name="username">Your username.</param>
 /// <param name="password">Your password.</param>
 /// <param name="httpClient">Allows you to inject your own HttpClient. This is useful, for example, to setup the HtppClient with a proxy.</param>
 /// <param name="options">Options for the SendGrid client.</param>
 /// <param name="logger">Logger.</param>
 public LegacyClient(string username, string password, HttpClient httpClient, StrongGridClientOptions options = null, ILogger logger = null)
     : base(default, username, password, httpClient, false, options, logger)
 {
     Init();
 }
Example #11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LegacyClient"/> class.
 /// </summary>
 /// <param name="username">Your username.</param>
 /// <param name="password">Your password.</param>
 /// <param name="handler">TThe HTTP handler stack to use for sending requests.</param>
 /// <param name="options">Options for the SendGrid client.</param>
 /// <param name="logger">Logger.</param>
 public LegacyClient(string username, string password, HttpMessageHandler handler, StrongGridClientOptions options = null, ILogger logger = null)
     : base(default, username, password, new HttpClient(handler), true, options, logger)
 {
     Init();
 }
Example #12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LegacyClient"/> class.
 /// </summary>
 /// <param name="username">Your username.</param>
 /// <param name="password">Your password.</param>
 /// <param name="proxy">Allows you to specify a proxy.</param>
 /// <param name="options">Options for the SendGrid client.</param>
 /// <param name="logger">Logger.</param>
 public LegacyClient(string username, string password, IWebProxy proxy, StrongGridClientOptions options = null, ILogger logger = null)
     : base(default, username, password, new HttpClient(new HttpClientHandler { Proxy = proxy, UseProxy = proxy != null }), true, options, logger)
 {
     Init();
 }
Example #13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LegacyClient" /> class with a specific http client.
 /// </summary>
 /// <param name="apiKey">Your SendGrid API Key.</param>
 /// <param name="httpClient">Allows you to inject your own HttpClient. This is useful, for example, to setup the HtppClient with a proxy.</param>
 /// <param name="options">Options for the SendGrid client.</param>
 /// <param name="logger">Logger.</param>
 public LegacyClient(string apiKey, HttpClient httpClient, StrongGridClientOptions options = null, ILogger logger = null)
     : base(apiKey, default, default, httpClient, false, options, logger)
 {
     Init();
 }
Example #14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BaseClient" /> class.
        /// </summary>
        /// <param name="apiKey">Your api key.</param>
        /// <param name="username">Your username. Ignored if the api key is specified.</param>
        /// <param name="password">Your password. Ignored if the api key is specified.</param>
        /// <param name="httpClient">Allows you to inject your own HttpClient. This is useful, for example, to setup the HtppClient with a proxy.</param>
        /// <param name="disposeClient">Indicates if the http client should be dispose when this instance of BaseClient is disposed.</param>
        /// <param name="options">Options for the SendGrid client.</param>
        /// <param name="logger">Logger.</param>
        public BaseClient(Parameter <string> apiKey, Parameter <string> username, Parameter <string> password, HttpClient httpClient, bool disposeClient, StrongGridClientOptions options, ILogger logger = null)
        {
            _mustDisposeHttpClient = disposeClient;
            _httpClient            = httpClient;
            _options = options ?? GetDefaultOptions();
            _logger  = logger ?? NullLogger.Instance;

            _fluentClient = new FluentClient(new Uri(SENDGRID_V3_BASE_URI), httpClient)
                            .SetUserAgent($"StrongGrid/{Version} (+https://github.com/Jericho/StrongGrid)")
                            .SetRequestCoordinator(new SendGridRetryStrategy());

            _fluentClient.Filters.Remove <DefaultErrorFilter>();

            // Order is important: DiagnosticHandler must be first.
            // Also, the list of filters must be kept in sync with the filters in Utils.GetFluentClient in the unit testing project.
            _fluentClient.Filters.Add(new DiagnosticHandler(_options.LogLevelSuccessfulCalls, _options.LogLevelFailedCalls, _logger));
            _fluentClient.Filters.Add(new SendGridErrorHandler());

            if (apiKey.HasValue)
            {
                if (string.IsNullOrEmpty(apiKey))
                {
                    throw new ArgumentNullException(apiKey);
                }
                else
                {
                    _fluentClient.SetBearerAuthentication(apiKey);
                }
            }
            else if (username.HasValue)
            {
                if (string.IsNullOrEmpty(username))
                {
                    throw new ArgumentNullException(username);
                }
                else
                {
                    _fluentClient.SetBasicAuthentication(username, password);
                }
            }
            else
            {
                throw new ArgumentException("You must provide either an API key or a username and a password.");
            }

            AccessManagement   = new AccessManagement(FluentClient);
            Alerts             = new Alerts(FluentClient);
            ApiKeys            = new ApiKeys(FluentClient);
            Batches            = new Batches(FluentClient);
            Blocks             = new Blocks(FluentClient);
            Bounces            = new Bounces(FluentClient);
            Designs            = new Designs(FluentClient);
            EmailActivities    = new EmailActivities(FluentClient);
            EmailValidation    = new EmailValidation(FluentClient);
            GlobalSuppressions = new GlobalSuppressions(FluentClient);
            InvalidEmails      = new InvalidEmails(FluentClient);
            IpAddresses        = new IpAddresses(FluentClient);
            IpPools            = new IpPools(FluentClient);
            Mail                 = new Mail(FluentClient);
            Settings             = new Settings(FluentClient);
            SpamReports          = new SpamReports(FluentClient);
            Statistics           = new Statistics(FluentClient);
            Subusers             = new Subusers(FluentClient);
            Suppressions         = new Suppressions(FluentClient);
            Teammates            = new Teammates(FluentClient);
            Templates            = new Templates(FluentClient);
            UnsubscribeGroups    = new UnsubscribeGroups(FluentClient);
            User                 = new User(FluentClient);
            WebhookSettings      = new WebhookSettings(FluentClient);
            WebhookStats         = new WebhookStats(FluentClient);
            SenderAuthentication = new SenderAuthentication(FluentClient);
        }
Example #15
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Client"/> class.
 /// </summary>
 /// <param name="username">Your username.</param>
 /// <param name="password">Your password.</param>
 /// <param name="handler">TThe HTTP handler stack to use for sending requests.</param>
 /// <param name="options">Options for the SendGrid client.</param>
 public Client(string username, string password, HttpMessageHandler handler, StrongGridClientOptions options = null)
     : this(null, username, password, new HttpClient(handler), true, options)
 {
 }
Example #16
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Client" /> class.
 /// </summary>
 /// <param name="username">Your username.</param>
 /// <param name="password">Your password.</param>
 /// <param name="httpClient">Allows you to inject your own HttpClient. This is useful, for example, to setup the HtppClient with a proxy.</param>
 /// <param name="options">Options for the SendGrid client.</param>
 public Client(string username, string password, HttpClient httpClient, StrongGridClientOptions options = null)
     : this(null, username, password, httpClient, false, options)
 {
 }
Example #17
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Client"/> class with a specific proxy.
 /// </summary>
 /// <param name="apiKey">Your SendGrid API Key.</param>
 /// <param name="proxy">Allows you to specify a proxy.</param>
 /// <param name="options">Options for the SendGrid client.</param>
 /// <param name="logger">Logger.</param>
 public Client(string apiKey, IWebProxy proxy, StrongGridClientOptions options = null, ILogger logger = null)
     : base(apiKey, new HttpClient(new HttpClientHandler { Proxy = proxy, UseProxy = proxy != null }), true, options ?? _defaultOptions, logger)
 {
     Init();
 }