コード例 #1
0
        public async Task <IHttpActionResult> PutAccessManagement(int id, AccessManagement accessManagement)
        {
            if (id != accessManagement.AMID)
            {
                return(null);
            }

            db.Entry(accessManagement).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!AccessManagementExists(id))
                {
                    return(null);
                }
                else
                {
                    throw;
                }
            }

            return(null);
        }
コード例 #2
0
        public async Task <IHttpActionResult> PutAccessManagement(int id, AccessManagement accessManagement)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != accessManagement.AMID)
            {
                return(BadRequest());
            }

            db.Entry(accessManagement).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!AccessManagementExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
コード例 #3
0
ファイル: Client.cs プロジェクト: xhanix/StrongGrid
        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);
        }
コード例 #4
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);
        }
コード例 #5
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);
        }
コード例 #6
0
        public async Task <IHttpActionResult> GetAccessManagement(int id)
        {
            AccessManagement accessManagement = await db.AccessManagements.FindAsync(id);

            if (accessManagement == null)
            {
                return(NotFound());
            }

            return(Ok(accessManagement));
        }
コード例 #7
0
        public async Task <IHttpActionResult> PostAccessManagement(AccessManagement accessManagement)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            db.AccessManagements.Add(accessManagement);
            await db.SaveChangesAsync();

            return(CreatedAtRoute("DefaultApi", new { id = accessManagement.AMID }, accessManagement));
        }
コード例 #8
0
        public async Task <IHttpActionResult> PostAccessManagement(AccessManagement accessManagement)
        {
            if (!ModelState.IsValid)
            {
                return(null);
            }

            var ob = db.AccessManagements.Add(accessManagement);
            await db.SaveChangesAsync();

            return(Ok(ob));
        }
コード例 #9
0
        public async Task <IHttpActionResult> DeleteAccessManagement(int id)
        {
            AccessManagement accessManagement = await db.AccessManagements.FindAsync(id);

            if (accessManagement == null)
            {
                return(NotFound());
            }

            db.AccessManagements.Remove(accessManagement);
            await db.SaveChangesAsync();

            return(Ok(accessManagement));
        }
コード例 #10
0
        private IEnumerable <AccessManagement> ReadAccessManagements(IResourceGroup resourceGroup)
        {
            var accessManagement  = new AccessManagement(resourceGroup);
            var accessManagements = new List <AccessManagement> {
                accessManagement
            };
            var azureAccessManagement = _azure.AccessManagement;

            // Microsoft.Azure.Management.Graph.RBAC.Fluent.Models.GraphErrorException
            // Operation returned an invalid status code 'Forbidden'
            foreach (var activeDirectoryGroup in azureAccessManagement.ActiveDirectoryGroups.List())
            {
                var group = new ActiveDirectoryGroup(activeDirectoryGroup.Name);
                accessManagement.ActiveDirectoryGroups.Add(group);
            }

            foreach (var activeDirectoryApplication in azureAccessManagement.ActiveDirectoryApplications.List())
            {
                var application = new ActiveDirectoryApplication(activeDirectoryApplication.Name);
                accessManagement.ActiveDirectoryApplications.Add(application);
            }

            foreach (var activeDirectoryUser in azureAccessManagement.ActiveDirectoryUsers.List())
            {
                var user = new ActiveDirectoryUser(activeDirectoryUser.Name);
                accessManagement.ActiveDirectoryUsers.Add(user);
            }

            ////foreach (var roleAssignment in azureAccessManagement.RoleAssignments.ListByScope())
            ////{
            ////    var assignment = new RoleAssignment(roleAssignment.Name);
            ////    accessManagement.RoleAssignments.Add(assignment);
            ////}

            ////foreach (var roleDefinition in azureAccessManagement.RoleDefinitions.ListByScope())
            ////{
            ////    var definition = new ActiveDirectoryUser(roleDefinition.Name);
            ////    accessManagement.RoleDefinitions.Add(definition);
            ////}

            foreach (var servicePrincipal in azureAccessManagement.ServicePrincipals.List())
            {
                var principal = new ServicePrincipal(servicePrincipal.Name);
                accessManagement.ServicePrincipals.Add(principal);
            }

            return(accessManagements);
        }
コード例 #11
0
        public async Task GetWhitelistedIpAddresses()
        {
            // Arrange
            var mockHttp = new MockHttpMessageHandler();

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

            var client           = Utils.GetFluentClient(mockHttp);
            var accessManagement = new AccessManagement(client);

            // Act
            var result = await accessManagement.GetWhitelistedIpAddressesAsync(null, CancellationToken.None).ConfigureAwait(false);

            // Assert
            mockHttp.VerifyNoOutstandingExpectation();
            mockHttp.VerifyNoOutstandingRequest();
            result.ShouldNotBeNull();
            result.Length.ShouldBe(2);
        }
コード例 #12
0
        public void RemoveIpAddressFromWhitelistAsync()
        {
            // Arrange
            var id = 1111;

            var mockHttp = new MockHttpMessageHandler();

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

            var client           = Utils.GetFluentClient(mockHttp);
            var accessManagement = new AccessManagement(client);

            // Act
            accessManagement.RemoveIpAddressFromWhitelistAsync(id, CancellationToken.None).Wait(CancellationToken.None);

            // Assert
            mockHttp.VerifyNoOutstandingExpectation();
            mockHttp.VerifyNoOutstandingRequest();
        }
コード例 #13
0
        public void GetAccessHistory()
        {
            // Arrange
            var mockHttp = new MockHttpMessageHandler();

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

            var client           = Utils.GetFluentClient(mockHttp);
            var accessManagement = new AccessManagement(client);

            // Act
            var result = accessManagement.GetAccessHistoryAsync(20, CancellationToken.None).Result;

            // Assert
            mockHttp.VerifyNoOutstandingExpectation();
            mockHttp.VerifyNoOutstandingRequest();
            result.ShouldNotBeNull();
            result.Length.ShouldBe(2);
        }
コード例 #14
0
        public async Task RemoveIpAddressesFromWhitelistAsync()
        {
            // Arrange
            var ids = new long[] { 1111, 2222, 3333 };

            var mockHttp = new MockHttpMessageHandler();

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

            var client           = Utils.GetFluentClient(mockHttp);
            var accessManagement = new AccessManagement(client);

            // Act
            await accessManagement.RemoveIpAddressesFromWhitelistAsync(ids, null, CancellationToken.None).ConfigureAwait(false);

            // Assert
            mockHttp.VerifyNoOutstandingExpectation();
            mockHttp.VerifyNoOutstandingRequest();
        }
コード例 #15
0
        public async Task AddIpAddressToWhitelist()
        {
            // Arrange
            var ip = "1.1.1.1";

            var mockHttp = new MockHttpMessageHandler();

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

            var client           = Utils.GetFluentClient(mockHttp);
            var accessManagement = new AccessManagement(client);

            // Act
            var result = await accessManagement.AddIpAddressToWhitelistAsync(ip, null, CancellationToken.None).ConfigureAwait(false);

            // Assert
            mockHttp.VerifyNoOutstandingExpectation();
            mockHttp.VerifyNoOutstandingRequest();
            result.ShouldNotBeNull();
        }
コード例 #16
0
        public void AddIpAddressesToWhitelist()
        {
            // Arrange
            var ips = new[] { "1.1.1.1", "1.2.3.4", "5.6.7.8" };

            var mockHttp = new MockHttpMessageHandler();

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

            var client           = Utils.GetFluentClient(mockHttp);
            var accessManagement = new AccessManagement(client);

            // Act
            var result = accessManagement.AddIpAddressesToWhitelistAsync(ips, CancellationToken.None).Result;

            // Assert
            mockHttp.VerifyNoOutstandingExpectation();
            mockHttp.VerifyNoOutstandingRequest();
            result.ShouldNotBeNull();
            result.Length.ShouldBe(3);
        }
コード例 #17
0
        public async Task GetWhitelistedIpAddressAsync()
        {
            // Arrange
            var id = 1111;

            var apiResponse = "{'result':" + SINGLE_WHITELISTED_IP_JSON + "}";

            var mockHttp = new MockHttpMessageHandler();

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

            var client           = Utils.GetFluentClient(mockHttp);
            var accessManagement = new AccessManagement(client);

            // Act
            var result = await accessManagement.GetWhitelistedIpAddressAsync(id, null, CancellationToken.None).ConfigureAwait(false);

            // Assert
            mockHttp.VerifyNoOutstandingExpectation();
            mockHttp.VerifyNoOutstandingRequest();
            result.ShouldNotBeNull();
        }
コード例 #18
0
ファイル: Program.cs プロジェクト: EdiCarlos/MyPractices
 static void Main(string[] args)
 {
     AccessManagement ass = new AccessManagement();
     ass.GetUserInfo();
 }
コード例 #19
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);
        }