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
        private Client(string apiKey, string username, string password, string baseUri, string apiVersion, HttpClient httpClient)
        {
            _mustDisposeHttpClient = httpClient == null;
            _httpClient            = httpClient;

#if DEBUG
            Version = "DEBUG";
#else
            var assemblyVersion = typeof(Client).GetTypeInfo().Assembly.GetName().Version;
            Version = $"{assemblyVersion.Major}.{assemblyVersion.Minor}.{assemblyVersion.Build}";
#endif

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

            _fluentClient.Filters.Remove <DefaultErrorFilter>();
            _fluentClient.Filters.Add(new DiagnosticHandler());
            _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);
            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);
            Whitelabel        = new Whitelabel(_fluentClient);
        }
Example #3
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 #4
0
        public async Task DeleteMonitorSettingsAsync()
        {
            // Arrange
            var username = "******";

            var mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect(HttpMethod.Delete, Utils.GetSendGridApiUri(ENDPOINT, username, "monitor")).Respond(HttpStatusCode.OK);

            var client   = Utils.GetFluentClient(mockHttp);
            var subusers = new Subusers(client);

            // Act
            await subusers.DeleteMonitorSettingsAsync(username, CancellationToken.None).ConfigureAwait(false);

            // Assert
            mockHttp.VerifyNoOutstandingExpectation();
            mockHttp.VerifyNoOutstandingRequest();
        }
Example #5
0
        public async Task GetAllAsync()
        {
            // Arrange
            var mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect(HttpMethod.Get, Utils.GetSendGridApiUri(ENDPOINT)).Respond("application/json", MULTIPLE_SUBUSER_JSON);

            var client   = Utils.GetFluentClient(mockHttp);
            var subusers = new Subusers(client);

            // Act
            var result = await subusers.GetAllAsync(10, 0, CancellationToken.None).ConfigureAwait(false);

            // Assert
            mockHttp.VerifyNoOutstandingExpectation();
            mockHttp.VerifyNoOutstandingRequest();
            result.ShouldNotBeNull();
            result.Length.ShouldBe(2);
        }
Example #6
0
        public void Delete()
        {
            // Arrange
            var keyId = "xxxxxxxx";

            var mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect(HttpMethod.Delete, Utils.GetSendGridApiUri(ENDPOINT, keyId)).Respond(HttpStatusCode.OK);

            var client   = Utils.GetFluentClient(mockHttp);
            var subusers = new Subusers(client);

            // Act
            subusers.DeleteAsync(keyId, CancellationToken.None).Wait(CancellationToken.None);

            // Assert
            mockHttp.VerifyNoOutstandingExpectation();
            mockHttp.VerifyNoOutstandingRequest();
        }
Example #7
0
        public async Task GetMonitorSettingsAsync()
        {
            // Arrange
            var username = "******";

            var mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect(HttpMethod.Get, Utils.GetSendGridApiUri(ENDPOINT, username, "monitor")).Respond("application/json", MONITOR_SETTINGS_JSON);

            var client   = Utils.GetFluentClient(mockHttp);
            var subusers = new Subusers(client);

            // Act
            var result = await subusers.GetMonitorSettingsAsync(username, CancellationToken.None).ConfigureAwait(false);

            // Assert
            mockHttp.VerifyNoOutstandingExpectation();
            mockHttp.VerifyNoOutstandingRequest();
            result.ShouldNotBeNull();
        }
Example #8
0
        public void Get()
        {
            // Arrange
            var username = "******";

            var mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect(HttpMethod.Get, Utils.GetSendGridApiUri(ENDPOINT, username)).Respond("application/json", SINGLE_SUBUSER_JSON);

            var client   = Utils.GetFluentClient(mockHttp);
            var subusers = new Subusers(client);

            // Act
            var result = subusers.GetAsync(username, CancellationToken.None).Result;

            // Assert
            mockHttp.VerifyNoOutstandingExpectation();
            mockHttp.VerifyNoOutstandingRequest();
            result.ShouldNotBeNull();
        }
Example #9
0
        public async Task UpdateAsync_ips()
        {
            // Arrange
            var username = "******";
            var disabled = default(Parameter <bool>);
            var ips      = new[] { "1.1.1.1", "2.2.2.2" };

            var mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect(new HttpMethod("PUT"), Utils.GetSendGridApiUri(ENDPOINT, username, "ips")).Respond("application/json", MULTIPLE_IPS_JSON);

            var client   = Utils.GetFluentClient(mockHttp);
            var subusers = new Subusers(client);

            // Act
            await subusers.UpdateAsync(username, disabled, ips, CancellationToken.None).ConfigureAwait(false);

            // Assert
            mockHttp.VerifyNoOutstandingExpectation();
            mockHttp.VerifyNoOutstandingRequest();
        }
Example #10
0
        public async Task UpdateAsync_disabled()
        {
            // Arrange
            var username = "******";
            var disabled = true;
            var ips      = default(Parameter <IEnumerable <string> >);

            var mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect(new HttpMethod("PATCH"), Utils.GetSendGridApiUri(ENDPOINT, username)).Respond(HttpStatusCode.NoContent);

            var client   = Utils.GetFluentClient(mockHttp);
            var subusers = new Subusers(client);

            // Act
            await subusers.UpdateAsync(username, disabled, ips, CancellationToken.None).ConfigureAwait(false);

            // Assert
            mockHttp.VerifyNoOutstandingExpectation();
            mockHttp.VerifyNoOutstandingRequest();
        }
Example #11
0
        public async Task GetSenderReputationsAsync()
        {
            //Arrange
            var usernames = new[] { "example_subuser", "example_subuser2" };

            var mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect(HttpMethod.Get, Utils.GetSendGridApiUri(ENDPOINT, "reputations")).Respond("application/json", MULTIPLE_REPUTATIONS_JSON);

            var client   = Utils.GetFluentClient(mockHttp);
            var subusers = new Subusers(client);

            // Act
            var result = await subusers.GetSenderReputationsAsync(usernames, CancellationToken.None).ConfigureAwait(false);

            // Assert
            mockHttp.VerifyNoOutstandingExpectation();
            mockHttp.VerifyNoOutstandingRequest();
            result.ShouldNotBeNull();
            result.Length.ShouldBe(2);
        }
Example #12
0
        public void UpdateMonitorSettings_frequency()
        {
            // Arrange
            var username  = "******";
            var email     = default(Parameter <string>);
            var frequency = 500;

            var mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect(HttpMethod.Put, Utils.GetSendGridApiUri(ENDPOINT, username, "monitor")).Respond("application/json", MONITOR_SETTINGS_JSON);

            var client   = Utils.GetFluentClient(mockHttp);
            var subusers = new Subusers(client);

            // Act
            var result = subusers.UpdateMonitorSettingsAsync(username, email, frequency, CancellationToken.None).Result;

            // Assert
            mockHttp.VerifyNoOutstandingExpectation();
            mockHttp.VerifyNoOutstandingRequest();
            result.ShouldNotBeNull();
        }
Example #13
0
        public async Task CreateAsync()
        {
            // Arrange
            var username = "******";
            var password = "******";
            var email    = "*****@*****.**";
            var ips      = new[] { "1.1.1.1", "2.2.2.2" };

            var mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect(HttpMethod.Post, Utils.GetSendGridApiUri(ENDPOINT)).Respond("application/json", SINGLE_SUBUSER_JSON);

            var client   = Utils.GetFluentClient(mockHttp);
            var subusers = new Subusers(client);

            // Act
            var result = await subusers.CreateAsync(username, email, password, ips, CancellationToken.None).ConfigureAwait(false);

            // Assert
            mockHttp.VerifyNoOutstandingExpectation();
            mockHttp.VerifyNoOutstandingRequest();
            result.ShouldNotBeNull();
        }
Example #14
0
        /// <summary>
        /// POST METHOD TO RECEIVE AN OBJECT WITH USER NAME AND EMAIL ADDRESS,
        /// AND TO SEND A CONFIRMATION EMAIL TO THE EMAIL ADDRESS
        /// </summary>
        /// <param name="subusers"></param>
        /// <returns> STRING TO THE AJAX CALL </returns>
        public async Task <JsonResult> SubmitDetails(Subusers subusers)
        {
            //if the email address is null then return NA else continue
            if (subusers.Uemail == null)
            {
                return(Json("NA"));
            }

            //check for the email address in the context
            var useremail    = subusers.Uemail;
            var existingUser = _context.Subusers.Any(x => x.Uemail.Equals(useremail));

            //if email address exists then return Y else continue
            if (existingUser)
            {
                return(Json("Y"));
            }

            //create an object to insert the values in the context
            Subusers UD = new Subusers();

            UD.Uname  = subusers.Uname;
            UD.Uemail = subusers.Uemail;

            //add to the dataset
            _context.Subusers.Add(UD);

            //create an instance of smtpclient
            SmtpClient smtpClient = new SmtpClient
            {
                Host = "smtp.gmail.com",
                //Host = "smtp-mail.outlook.com",
                Port        = 587,
                EnableSsl   = true,
                Credentials = new NetworkCredential("*****@*****.**", "Sandbox_test")
            };

            try
            {
                //prepare the email message
                using (var message = new MailMessage("*****@*****.**", useremail)
                {
                    Subject = "Subscription successful",
                    Body = "Dear " + subusers.Uname + ", \n \n \t Thank you For Subscribing \n \n - AlgoDepth. \n \n \n PLEASE DO NOT RESPOND TO THIS EMAIL, this account is not monitored!"
                })

                    //send the messsage
                    await smtpClient.SendMailAsync(message);
                //save the changes in the database
                await _context.SaveChangesAsync();
            }

            //catch exception if any
            catch (Exception e)
            {
                return(Json(e));
            }

            //return N - indicating new user is added
            return(Json("N"));
        }
Example #15
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);
        }