Exemple #1
0
        public async Task AddAsync()
        {
            // Arrange
            var emails      = new[] { "*****@*****.**", "*****@*****.**" };
            var apiResponse = @"{
				""recipient_emails"": [
					""*****@*****.**"",
					""*****@*****.**""
				]
			}"            ;

            var mockHttp = new MockHttpMessageHandler();

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

            var client             = Utils.GetFluentClient(mockHttp);
            var globalSuppressions = new GlobalSuppressions(client);

            // Act
            await globalSuppressions.AddAsync(emails, null, CancellationToken.None).ConfigureAwait(false);

            // Assert
            mockHttp.VerifyNoOutstandingExpectation();
            mockHttp.VerifyNoOutstandingRequest();
        }
Exemple #2
0
        public Settings(
            IEnumerable <KeyValuePair <string, bool> > refactorings = null,
            IEnumerable <KeyValuePair <string, bool> > codeFixes    = null,
            IEnumerable <string> globalSuppressions  = null,
            bool prefixFieldIdentifierWithUnderscore = true)
        {
            Initialize(Refactorings, refactorings);
            Initialize(CodeFixes, codeFixes);

            if (globalSuppressions != null)
            {
                foreach (string kvp in globalSuppressions)
                {
                    GlobalSuppressions.Add(kvp);
                }
            }

            PrefixFieldIdentifierWithUnderscore = prefixFieldIdentifierWithUnderscore;

            void Initialize <T>(Dictionary <T, bool> dic, IEnumerable <KeyValuePair <T, bool> > values)
            {
                if (values != null)
                {
                    foreach (KeyValuePair <T, bool> kvp in values)
                    {
                        dic.Add(kvp.Key, kvp.Value);
                    }
                }
            }
        }
Exemple #3
0
        public void Add()
        {
            // Arrange
            var emails      = new[] { "*****@*****.**", "*****@*****.**" };
            var apiResponse = @"{
				'recipient_emails': [
					'*****@*****.**',
					'*****@*****.**'
				]
			}"            ;

            var mockClient = new Mock <IClient>(MockBehavior.Strict);

            mockClient.Setup(c => c.PostAsync(ENDPOINT, It.Is <JObject>(o => o["recipient_emails"].ToObject <JArray>().Count == emails.Length), It.IsAny <CancellationToken>()))
            .ReturnsAsync(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(apiResponse)
            });

            var globalSuppressions = new GlobalSuppressions(mockClient.Object);

            // Act
            globalSuppressions.AddAsync(emails, CancellationToken.None).Wait();

            // Assert
        }
Exemple #4
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);
        }
Exemple #5
0
        public void IsUnsubscribed_true()
        {
            // Arrange
            var email = "*****@*****.**";

            var apiResponse = @"{
				'recipient_email': '*****@*****.**'
			}"            ;

            var mockRepository = new MockRepository(MockBehavior.Strict);
            var mockClient     = mockRepository.Create <IClient>();

            mockClient
            .Setup(c => c.GetAsync($"{ENDPOINT}/{email}", It.IsAny <CancellationToken>()))
            .ReturnsAsync(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(apiResponse)
            })
            .Verifiable();

            var globalSuppressions = new GlobalSuppressions(mockClient.Object, ENDPOINT);

            // Act
            var result = globalSuppressions.IsUnsubscribedAsync(email, CancellationToken.None).Result;

            // Assert
            result.ShouldBeTrue();
        }
Exemple #6
0
        /// <summary>
        ///     Create a client that connects to the SendGrid Web API
        /// </summary>
        /// <param name="apiKey">Your SendGrid API Key</param>
        /// <param name="baseUri">Base SendGrid API Uri</param>
        public Client(string apiKey, string baseUri = "https://api.sendgrid.com", string apiVersion = "v3", HttpClient httpClient = null)
        {
            _baseUri = new Uri(string.Format("{0}/{1}", baseUri, apiVersion));
            _apiKey  = apiKey;

            Alerts             = new Alerts(this);
            ApiKeys            = new ApiKeys(this);
            Blocks             = new Blocks(this);
            Campaigns          = new Campaigns(this);
            Categories         = new Categories(this);
            Contacts           = new Contacts(this);
            CustomFields       = new CustomFields(this);
            GlobalSuppressions = new GlobalSuppressions(this);
            Lists             = new Lists(this);
            Mail              = new Mail(this);
            Segments          = new Segments(this);
            SenderIdentities  = new SenderIdentities(this);
            Settings          = new Settings(this);
            Statistics        = new Statistics(this);
            Suppressions      = new Suppressions(this);
            Templates         = new Templates(this);
            UnsubscribeGroups = new UnsubscribeGroups(this);
            User              = new User(this);
            Version           = typeof(Client).GetTypeInfo().Assembly.GetName().Version.ToString();

            _mustDisposeHttpClient  = (httpClient == null);
            _httpClient             = httpClient ?? new HttpClient();
            _httpClient.BaseAddress = _baseUri;
            _httpClient.DefaultRequestHeaders.Accept.Clear();
            _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(MEDIA_TYPE));
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _apiKey);
            _httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", string.Format("StrongGrid/{0}", Version));
        }
Exemple #7
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);
        }
Exemple #8
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);
        }
Exemple #9
0
 /// <summary>
 ///     Create a client that connects to the SendGrid Web API
 /// </summary>
 /// <param name="apiKey">Your SendGrid API Key</param>
 /// <param name="baseUri">Base SendGrid API Uri</param>
 public Client(string apiKey, string baseUri = "https://api.sendgrid.com/")
 {
     _baseUri           = new Uri(baseUri);
     _apiKey            = apiKey;
     Version            = "Josh";//Assembly.GetExecutingAssembly().GetName().Version.ToString();
     ApiKeys            = new APIKeys(this);
     UnsubscribeGroups  = new UnsubscribeGroups(this);
     Suppressions       = new Suppressions(this);
     GlobalSuppressions = new GlobalSuppressions(this);
     GlobalStats        = new GlobalStats(this);
 }
Exemple #10
0
 private void Initialize()
 {
     Version            = Assembly.GetExecutingAssembly().GetName().Version.ToString();
     ApiKeys            = new APIKeys(this);
     UnsubscribeGroups  = new UnsubscribeGroups(this);
     Suppressions       = new Suppressions(this);
     GlobalSuppressions = new GlobalSuppressions(this);
     GlobalStats        = new GlobalStats(this);
     Templates          = new Templates(this);
     Versions           = new Versions(this);
     Batches            = new Batches(this);
 }
Exemple #11
0
        public void Save(string path)
        {
            var settings = new XElement("Settings",
                                        new XElement("General",
                                                     new XElement("PrefixFieldIdentifierWithUnderscore", PrefixFieldIdentifierWithUnderscore)));

            if (Refactorings.Any(f => !f.Value))
            {
                settings.Add(
                    new XElement("Refactorings",
                                 Refactorings
                                 .Where(f => !f.Value)
                                 .OrderBy(f => f.Key)
                                 .Select(f => new XElement("Refactoring", new XAttribute("Id", f.Key), new XAttribute("IsEnabled", f.Value)))
                                 ));
            }

            if (CodeFixes.Any(f => !f.Value))
            {
                settings.Add(
                    new XElement("CodeFixes",
                                 CodeFixes
                                 .Where(f => !f.Value)
                                 .OrderBy(f => f.Key)
                                 .Select(f => new XElement("CodeFix", new XAttribute("Id", f.Key), new XAttribute("IsEnabled", f.Value)))
                                 ));
            }

            if (GlobalSuppressions.Count > 0)
            {
                settings.Add(
                    new XElement("GlobalSuppressions",
                                 GlobalSuppressions
                                 .OrderBy(f => f)
                                 .Select(f => new XElement("GlobalSuppression", new XAttribute("Id", f)))));
            }

            var doc = new XDocument(new XElement("Roslynator", settings));

            var xmlWriterSettings = new XmlWriterSettings()
            {
                OmitXmlDeclaration = false,
                NewLineChars       = Environment.NewLine,
                IndentChars        = "  ",
                Indent             = true,
            };

            using (var fileStream = new FileStream(path, FileMode.Create))
                using (var streamWriter = new StreamWriter(fileStream, Encoding.UTF8))
                    using (XmlWriter xmlWriter = XmlWriter.Create(streamWriter, xmlWriterSettings))
                        doc.WriteTo(xmlWriter);
        }
Exemple #12
0
        private void DecodeGlobalSuppressMessageAttributes()
        {
            if (this.lazyGlobalSuppressions == null)
            {
                var suppressions = new GlobalSuppressions();
                DecodeGlobalSuppressMessageAttributes(this.compilation, compilation.Assembly, this.SuppressMessageAttribute, suppressions);

                foreach (var module in this.compilation.Assembly.Modules)
                {
                    DecodeGlobalSuppressMessageAttributes(this.compilation, module, this.SuppressMessageAttribute, suppressions);
                }

                Interlocked.CompareExchange(ref this.lazyGlobalSuppressions, suppressions, null);
            }
        }
Exemple #13
0
        private void DecodeGlobalSuppressMessageAttributes()
        {
            if (_lazyGlobalSuppressions == null)
            {
                GlobalSuppressions suppressions = new GlobalSuppressions();
                DecodeGlobalSuppressMessageAttributes(_compilation, _compilation.Assembly, suppressions);

                foreach (IModuleSymbol module in _compilation.Assembly.Modules)
                {
                    DecodeGlobalSuppressMessageAttributes(_compilation, module, suppressions);
                }

                Interlocked.CompareExchange(ref _lazyGlobalSuppressions, suppressions, null);
            }
        }
Exemple #14
0
        private void DecodeGlobalSuppressMessageAttributes(
            Compilation compilation,
            ISymbol symbol,
            GlobalSuppressions globalSuppressions
            )
        {
            Debug.Assert(symbol is IAssemblySymbol || symbol is IModuleSymbol);

            var attributes = symbol.GetAttributes().Where(a => IsSuppressionAttribute(a));

            DecodeGlobalSuppressMessageAttributes(
                compilation,
                symbol,
                globalSuppressions,
                attributes
                );
        }
Exemple #15
0
        public void Delete()
        {
            // Arrange
            var email = "*****@*****.**";

            var mockClient = new Mock <IClient>(MockBehavior.Strict);

            mockClient.Setup(c => c.DeleteAsync($"{ENDPOINT}/{email}", It.IsAny <CancellationToken>()))
            .ReturnsAsync(new HttpResponseMessage(HttpStatusCode.NoContent));

            var globalSuppressions = new GlobalSuppressions(mockClient.Object);

            // Act
            globalSuppressions.RemoveAsync(email, CancellationToken.None).Wait();

            // Assert
        }
Exemple #16
0
        private static void DecodeGlobalSuppressMessageAttributes(
            Compilation compilation,
            ISymbol symbol,
            GlobalSuppressions globalSuppressions,
            IEnumerable <AttributeData> attributes
            )
        {
            foreach (var instance in attributes)
            {
                SuppressMessageInfo info;
                if (!TryDecodeSuppressMessageAttributeData(instance, out info))
                {
                    continue;
                }

                if (TryGetTargetScope(info, out TargetScope scope))
                {
                    if (
                        (scope == TargetScope.Module || scope == TargetScope.None) &&
                        info.Target == null
                        )
                    {
                        // This suppression is applies to the entire compilation
                        globalSuppressions.AddCompilationWideSuppression(info);
                        continue;
                    }
                }
                else
                {
                    // Invalid value for scope
                    continue;
                }

                // Decode Target
                if (info.Target == null)
                {
                    continue;
                }

                foreach (var target in ResolveTargetSymbols(compilation, info.Target, scope))
                {
                    globalSuppressions.AddGlobalSymbolSuppression(target, info);
                }
            }
        }
Exemple #17
0
        private Client(string apiKey, string username, string password, string baseUri, string apiVersion, HttpClient httpClient, IRetryStrategy retryStrategy)
        {
            _baseUri       = new Uri(string.Format("{0}/{1}", baseUri, apiVersion));
            _retryStrategy = retryStrategy ?? new SendGridRetryStrategy();

            Alerts             = new Alerts(this);
            ApiKeys            = new ApiKeys(this);
            Batches            = new Batches(this);
            Blocks             = new Blocks(this);
            Campaigns          = new Campaigns(this);
            Categories         = new Categories(this);
            Contacts           = new Contacts(this);
            CustomFields       = new CustomFields(this);
            GlobalSuppressions = new GlobalSuppressions(this);
            InvalidEmails      = new InvalidEmails(this);
            Lists             = new Lists(this);
            Mail              = new Mail(this);
            Segments          = new Segments(this);
            SenderIdentities  = new SenderIdentities(this);
            Settings          = new Settings(this);
            SpamReports       = new SpamReports(this);
            Statistics        = new Statistics(this);
            Suppressions      = new Suppressions(this);
            Templates         = new Templates(this);
            UnsubscribeGroups = new UnsubscribeGroups(this);
            User              = new User(this);
            Version           = typeof(Client).GetTypeInfo().Assembly.GetName().Version.ToString();
            Whitelabel        = new Whitelabel(this);

            _mustDisposeHttpClient  = httpClient == null;
            _httpClient             = httpClient ?? new HttpClient();
            _httpClient.BaseAddress = _baseUri;
            _httpClient.DefaultRequestHeaders.Accept.Clear();
            _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(MEDIA_TYPE));
            if (!string.IsNullOrEmpty(apiKey))
            {
                _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
            }
            if (!string.IsNullOrEmpty(username))
            {
                _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Concat(username, ":", password))));
            }
            _httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", string.Format("StrongGrid/{0}", Version));
        }
Exemple #18
0
        public async Task GetAll()
        {
            // Arrange
            var mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect(HttpMethod.Get, Utils.GetSendGridApiUri("suppression/unsubscribes")).Respond("application/json", GLOBALLY_UNSUBSCRIBED);

            var client             = Utils.GetFluentClient(mockHttp);
            var globalSuppressions = new GlobalSuppressions(client);

            // Act
            var result = await globalSuppressions.GetAllAsync(null, null, null, 50, 0, null, CancellationToken.None).ConfigureAwait(false);

            // Assert
            mockHttp.VerifyNoOutstandingExpectation();
            mockHttp.VerifyNoOutstandingRequest();
            result.ShouldNotBeNull();
            result.Length.ShouldBe(3);
        }
Exemple #19
0
        public async Task RemoveAsync()
        {
            // Arrange
            var email = "*****@*****.**";

            var mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect(HttpMethod.Delete, Utils.GetSendGridApiUri(ENDPOINT, email)).Respond(HttpStatusCode.NoContent);

            var client             = Utils.GetFluentClient(mockHttp);
            var globalSuppressions = new GlobalSuppressions(client);

            // Act
            await globalSuppressions.RemoveAsync(email, null, CancellationToken.None).ConfigureAwait(false);

            // Assert
            mockHttp.VerifyNoOutstandingExpectation();
            mockHttp.VerifyNoOutstandingRequest();
        }
Exemple #20
0
        public async Task IsUnsubscribedAsync_false()
        {
            // Arrange
            var email = "*****@*****.**";

            var apiResponse = @"{
			}"            ;

            var mockHttp = new MockHttpMessageHandler();

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

            var client             = Utils.GetFluentClient(mockHttp);
            var globalSuppressions = new GlobalSuppressions(client);

            // Act
            var result = await globalSuppressions.IsUnsubscribedAsync(email, null, CancellationToken.None).ConfigureAwait(false);

            // Assert
            mockHttp.VerifyNoOutstandingExpectation();
            mockHttp.VerifyNoOutstandingRequest();
            result.ShouldBeFalse();
        }
Exemple #21
0
        public void IsUnsubscribed_false()
        {
            // Arrange
            var email = "*****@*****.**";

            var apiResponse = @"{
			}"            ;
            var mockClient  = new Mock <IClient>(MockBehavior.Strict);

            mockClient.Setup(c => c.GetAsync($"{ENDPOINT}/{email}", It.IsAny <CancellationToken>()))
            .ReturnsAsync(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(apiResponse)
            });

            var globalSuppressions = new GlobalSuppressions(mockClient.Object);

            // Act
            var result = globalSuppressions.IsUnsubscribedAsync(email, CancellationToken.None).Result;

            // Assert
            Assert.IsFalse(result);
        }
        public void IsUnsubscribed_true()
        {
            // Arrange
            var email = "*****@*****.**";

            var apiResponse = @"{
				'recipient_email': '*****@*****.**'
			}"            ;

            var mockHttp = new MockHttpMessageHandler();

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

            var client             = Utils.GetFluentClient(mockHttp);
            var globalSuppressions = new GlobalSuppressions(client);

            // Act
            var result = globalSuppressions.IsUnsubscribedAsync(email, CancellationToken.None).Result;

            // Assert
            mockHttp.VerifyNoOutstandingExpectation();
            mockHttp.VerifyNoOutstandingRequest();
            result.ShouldBeTrue();
        }
Exemple #23
0
        private static void DecodeGlobalSuppressMessageAttributes(Compilation compilation, ISymbol symbol, ISymbol suppressMessageAttribute, GlobalSuppressions globalSuppressions)
        {
            Debug.Assert(symbol is IAssemblySymbol || symbol is IModuleSymbol);

            var attributeInstances = symbol.GetAttributes().Where(a => a.AttributeClass == suppressMessageAttribute);

            foreach (var instance in attributeInstances)
            {
                SuppressMessageInfo info;
                if (!TryDecodeSuppressMessageAttributeData(instance, out info))
                {
                    continue;
                }

                string scopeString = info.Scope != null?info.Scope.ToLowerInvariant() : null;

                TargetScope scope;

                if (SuppressMessageScopeTypes.TryGetValue(scopeString, out scope))
                {
                    if ((scope == TargetScope.Module || scope == TargetScope.None) && info.Target == null)
                    {
                        // This suppression is applies to the entire compilation
                        globalSuppressions.AddCompilationWideSuppression(info.Id);
                        continue;
                    }
                }
                else
                {
                    // Invalid value for scope
                    continue;
                }

                // Decode Target
                if (info.Target == null)
                {
                    continue;
                }

                foreach (var target in ResolveTargetSymbols(compilation, info.Target, scope))
                {
                    globalSuppressions.AddGlobalSymbolSuppression(target, info.Id);
                }
            }
        }
        private void DecodeGlobalSuppressMessageAttributes()
        {
            if (this.lazyGlobalSuppressions == null)
            {
                var suppressions = new GlobalSuppressions();
                DecodeGlobalSuppressMessageAttributes(this.compilation, compilation.Assembly, this.SuppressMessageAttribute, suppressions);

                foreach (var module in this.compilation.Assembly.Modules)
                {
                    DecodeGlobalSuppressMessageAttributes(this.compilation, module, this.SuppressMessageAttribute, suppressions);
                }

                Interlocked.CompareExchange(ref this.lazyGlobalSuppressions, suppressions, null);
            }
        }
        private static void DecodeGlobalSuppressMessageAttributes(Compilation compilation, ISymbol symbol, ISymbol suppressMessageAttribute, GlobalSuppressions globalSuppressions)
        {
            Debug.Assert(symbol is IAssemblySymbol || symbol is IModuleSymbol);

            var attributeInstances = symbol.GetAttributes().Where(a => a.AttributeClass == suppressMessageAttribute);

            foreach (var instance in attributeInstances)
            {
                SuppressMessageInfo info;
                if (!TryDecodeSuppressMessageAttributeData(instance, out info))
                {
                    continue;
                }

                string scopeString = info.Scope != null ? info.Scope.ToLowerInvariant() : null;
                TargetScope scope;

                if (SuppressMessageScopeTypes.TryGetValue(scopeString, out scope))
                {
                    if ((scope == TargetScope.Module || scope == TargetScope.None) && info.Target == null)
                    {
                        // This suppression is applies to the entire compilation
                        globalSuppressions.AddCompilationWideSuppression(info.Id);
                        continue;
                    }
                }
                else
                {
                    // Invalid value for scope
                    continue;
                }

                // Decode Target
                if (info.Target == null)
                {
                    continue;
                }

                foreach (var target in ResolveTargetSymbols(compilation, info.Target, scope))
                {
                    globalSuppressions.AddGlobalSymbolSuppression(target, info.Id);
                }
            }
        }
        private static void DecodeGlobalSuppressMessageAttributes(Compilation compilation, ISymbol symbol, GlobalSuppressions globalSuppressions, IEnumerable<AttributeData> attributes)
        {
            foreach (var instance in attributes)
            {
                SuppressMessageInfo info;
                if (!TryDecodeSuppressMessageAttributeData(instance, out info))
                {
                    continue;
                }

                string scopeString = info.Scope != null ? info.Scope.ToLowerInvariant() : null;
                TargetScope scope;

                if (s_suppressMessageScopeTypes.TryGetValue(scopeString, out scope))
                {
                    if ((scope == TargetScope.Module || scope == TargetScope.None) && info.Target == null)
                    {
                        // This suppression is applies to the entire compilation
                        globalSuppressions.AddCompilationWideSuppression(info);
                        continue;
                    }
                }
                else
                {
                    // Invalid value for scope
                    continue;
                }

                // Decode Target
                if (info.Target == null)
                {
                    continue;
                }

                foreach (var target in ResolveTargetSymbols(compilation, info.Target, scope))
                {
                    globalSuppressions.AddGlobalSymbolSuppression(target, info);
                }
            }
        }
        private void DecodeGlobalSuppressMessageAttributes(Compilation compilation, ISymbol symbol, GlobalSuppressions globalSuppressions)
        {
            Debug.Assert(symbol is IAssemblySymbol || symbol is IModuleSymbol);

            var attributes = symbol.GetAttributes().Where(a => a.AttributeClass == this.SuppressMessageAttribute);
            DecodeGlobalSuppressMessageAttributes(compilation, symbol, globalSuppressions, attributes);
        }
Exemple #28
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);
        }
Exemple #29
0
        private void DecodeGlobalSuppressMessageAttributes(Compilation compilation, ISymbol symbol, GlobalSuppressions globalSuppressions)
        {
            Debug.Assert(symbol is IAssemblySymbol || symbol is IModuleSymbol);

            IEnumerable <AttributeData> attributes = symbol.GetAttributes().Where(a => a.AttributeClass == this.SuppressMessageAttribute);

            DecodeGlobalSuppressMessageAttributes(compilation, symbol, globalSuppressions, attributes);
        }
Exemple #30
0
        private static void DecodeGlobalSuppressMessageAttributes(Compilation compilation, ISymbol symbol, GlobalSuppressions globalSuppressions, IEnumerable <AttributeData> attributes)
        {
            foreach (AttributeData instance in attributes)
            {
                if (!TryDecodeSuppressMessageAttributeData(instance, out SuppressMessageInfo info))
                {
                    continue;
                }

                string scopeString = info.Scope != null?info.Scope.ToLowerInvariant() : null;

                if (s_suppressMessageScopeTypes.TryGetValue(scopeString, out TargetScope scope))
                {
                    if ((scope == TargetScope.Module || scope == TargetScope.None) && info.Target == null)
                    {
                        // This suppression is applies to the entire compilation
                        globalSuppressions.AddCompilationWideSuppression(info);
                        continue;
                    }
                }
                else
                {
                    // Invalid value for scope
                    continue;
                }

                // Decode Target
                if (info.Target == null)
                {
                    continue;
                }

                foreach (ISymbol target in ResolveTargetSymbols(compilation, info.Target, scope))
                {
                    globalSuppressions.AddGlobalSymbolSuppression(target, info);
                }
            }
        }