private async Task <DatabaseVulnerabilityAssessment> SetPolicy(SqlManagementTestContext context, SqlManagementClient sqlClient, ResourceGroup resourceGroup, ManagedInstance managedInstance, string dbName) { // Modify the policy properties, send and receive and see it its still ok ManagedServerSecurityAlertPolicy updatedManagedServerPolicy = new ManagedServerSecurityAlertPolicy { State = SecurityAlertPolicyState.Enabled, EmailAccountAdmins = true }; //Set security alert policy for server sqlClient.ManagedServerSecurityAlertPolicies.CreateOrUpdate(resourceGroup.Name, managedInstance.Name, updatedManagedServerPolicy); StorageContainerInfo StorageContainerInfo = await CreateStorageContainer(context, resourceGroup); DatabaseVulnerabilityAssessment policy = new DatabaseVulnerabilityAssessment() { StorageContainerPath = StorageContainerInfo.StorageContainerPath.ToString(), StorageContainerSasKey = StorageContainerInfo.StorageAccountSasKey, RecurringScans = new VulnerabilityAssessmentRecurringScansProperties() { IsEnabled = false, Emails = new List <string>() { "*****@*****.**", "*****@*****.**" }, EmailSubscriptionAdmins = true } }; return(sqlClient.ManagedDatabaseVulnerabilityAssessments.CreateOrUpdate(resourceGroup.Name, managedInstance.Name, dbName, policy)); }
/// <summary> /// Set settings with storage access key /// </summary> public VulnerabilityAssessmentSettingsModel SetVulnerabilityAssessmentSettingsWithStorageAccessKey(VulnerabilityAssessmentSettingsModel model, string serverName, string databaseName, ApplyToType applyToType) { var resourceGroupName = AzureCommunicator.GetStorageResourceGroup(model.StorageAccountName); var storageContainerInfo = VulnerabilityAssessmentCommunicator.GetStorageContainerInfo(resourceGroupName, model.StorageAccountName, model.ScanResultsContainerName); DatabaseVulnerabilityAssessment settings = new DatabaseVulnerabilityAssessment { StorageContainerPath = storageContainerInfo.StorageContainerPath, StorageAccountAccessKey = storageContainerInfo.StorageAccountAccessKey, RecurringScans = new VulnerabilityAssessmentRecurringScansProperties() { IsEnabled = model.RecurringScansInterval != RecurringScansInterval.None, EmailSubscriptionAdmins = model.EmailAdmins, Emails = model.NotificationEmail } }; var vulnerabilityAssessmentSettings = (applyToType == ApplyToType.Database) ? VulnerabilityAssessmentCommunicator.SetDatabaseVulnerabilityAssessmentSettings(model.ResourceGroupName, serverName, databaseName, settings) : VulnerabilityAssessmentCommunicator.SetManagedDatabaseVulnerabilityAssessmentSettings(model.ResourceGroupName, serverName, databaseName, settings); return(ConvertSettingsToModel(model.ResourceGroupName, serverName, databaseName, vulnerabilityAssessmentSettings)); }
public async Task <Response <DatabaseVulnerabilityAssessment> > GetAsync(string resourceGroupName, string managedInstanceName, string databaseName, VulnerabilityAssessmentName vulnerabilityAssessmentName, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (managedInstanceName == null) { throw new ArgumentNullException(nameof(managedInstanceName)); } if (databaseName == null) { throw new ArgumentNullException(nameof(databaseName)); } using var message = CreateGetRequest(resourceGroupName, managedInstanceName, databaseName, vulnerabilityAssessmentName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { DatabaseVulnerabilityAssessment value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = DatabaseVulnerabilityAssessment.DeserializeDatabaseVulnerabilityAssessment(document.RootElement); return(Response.FromValue(value, message.Response)); }
public async void TestCreateUpdateGetDatabaseVulnerabilityAssessments() { string testPrefix = "sqlvulnerabilityassessmentcrudtest-"; using (SqlManagementTestContext context = new SqlManagementTestContext(this)) { ResourceGroup resourceGroup = context.CreateResourceGroup(); SqlManagementClient sqlClient = context.GetClient <SqlManagementClient>(); Server server = context.CreateServer(resourceGroup); // Create database // string dbName = SqlManagementTestUtilities.GenerateName(testPrefix); var db1 = sqlClient.Databases.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, new Database() { Location = server.Location, }); Assert.NotNull(db1); // Turn ON database threat detection as a prerequisite to use VA DatabaseSecurityAlertPolicy updatedDatabasePolicy = new DatabaseSecurityAlertPolicy { State = SecurityAlertPolicyState.Enabled, EmailAccountAdmins = SecurityAlertPolicyEmailAccountAdmins.Enabled }; sqlClient.DatabaseThreatDetectionPolicies.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, updatedDatabasePolicy); // Verify Policy is empty to begin with DatabaseVulnerabilityAssessment policyThatWasReceived = sqlClient.DatabaseVulnerabilityAssessments.Get(resourceGroup.Name, server.Name, dbName); Assert.Null(policyThatWasReceived.StorageContainerPath); Assert.Null(policyThatWasReceived.StorageContainerSasKey); Assert.False(policyThatWasReceived.RecurringScans.IsEnabled); // Set policy and then get policy and verify correctness DatabaseVulnerabilityAssessment policyThatWasSet = await SetPolicy(context, sqlClient, resourceGroup, server, dbName); policyThatWasReceived = sqlClient.DatabaseVulnerabilityAssessments.Get(resourceGroup.Name, server.Name, dbName); Assert.Equal(policyThatWasSet.StorageContainerPath, policyThatWasReceived.StorageContainerPath); Assert.Null(policyThatWasSet.StorageContainerSasKey); Assert.Equal(policyThatWasSet.RecurringScans.IsEnabled, policyThatWasReceived.RecurringScans.IsEnabled); SqlManagementTestUtilities.AssertCollection(policyThatWasSet.RecurringScans.Emails, policyThatWasReceived.RecurringScans.Emails); Assert.Equal(policyThatWasSet.RecurringScans.EmailSubscriptionAdmins, policyThatWasReceived.RecurringScans.EmailSubscriptionAdmins); // Delete policy and then get policy and verify correctness sqlClient.DatabaseVulnerabilityAssessments.Delete(resourceGroup.Name, server.Name, dbName); // Get policy after deletion policyThatWasReceived = sqlClient.DatabaseVulnerabilityAssessments.Get(resourceGroup.Name, server.Name, dbName); Assert.Null(policyThatWasReceived.StorageContainerPath); Assert.Null(policyThatWasReceived.StorageContainerSasKey); Assert.False(policyThatWasReceived.RecurringScans.IsEnabled); }; }
public async void TestCreateUpdateGetDatabaseVulnerabilityAssessments() { using (SqlManagementTestContext context = new SqlManagementTestContext(this)) { string testPrefix = "sqlvulnerabilityassessmentcrudtest-"; SqlManagementClient sqlClient = context.GetClient <SqlManagementClient>(); var resourceGroup = context.CreateResourceGroup(); var managedInstance = context.CreateManagedInstance(resourceGroup); // Create managed database // string dbName = SqlManagementTestUtilities.GenerateName(testPrefix); var db1 = sqlClient.ManagedDatabases.CreateOrUpdate(resourceGroup.Name, managedInstance.Name, dbName, new ManagedDatabase() { Location = managedInstance.Location, }); Assert.NotNull(db1); // Verify Policy is empty to begin with DatabaseVulnerabilityAssessment policyThatWasReceived = sqlClient.ManagedDatabaseVulnerabilityAssessments.Get(resourceGroup.Name, managedInstance.Name, dbName); Assert.Null(policyThatWasReceived.StorageContainerPath); Assert.Null(policyThatWasReceived.StorageContainerSasKey); Assert.False(policyThatWasReceived.RecurringScans.IsEnabled); // Set policy and then get policy and verify correctness DatabaseVulnerabilityAssessment policyThatWasSet = await SetPolicy(context, sqlClient, resourceGroup, managedInstance, dbName); policyThatWasReceived = sqlClient.ManagedDatabaseVulnerabilityAssessments.Get(resourceGroup.Name, managedInstance.Name, dbName); Assert.Equal(policyThatWasSet.StorageContainerPath, policyThatWasReceived.StorageContainerPath); Assert.Null(policyThatWasSet.StorageContainerSasKey); Assert.Equal(policyThatWasSet.RecurringScans.IsEnabled, policyThatWasReceived.RecurringScans.IsEnabled); SqlManagementTestUtilities.AssertCollection(policyThatWasSet.RecurringScans.Emails, policyThatWasReceived.RecurringScans.Emails); Assert.Equal(policyThatWasSet.RecurringScans.EmailSubscriptionAdmins, policyThatWasReceived.RecurringScans.EmailSubscriptionAdmins); // Delete policy and then get policy and verify correctness sqlClient.ManagedDatabaseVulnerabilityAssessments.Delete(resourceGroup.Name, managedInstance.Name, dbName); // Get policy after deletion policyThatWasReceived = sqlClient.ManagedDatabaseVulnerabilityAssessments.Get(resourceGroup.Name, managedInstance.Name, dbName); Assert.Null(policyThatWasReceived.StorageContainerPath); Assert.Null(policyThatWasReceived.StorageContainerSasKey); Assert.False(policyThatWasReceived.RecurringScans.IsEnabled); } }
/// <summary> /// Transforms the given model to its endpoints acceptable structure and sends it to the endpoint /// </summary> public DatabaseVulnerabilityAssessmentSettingsModel SetDatabaseVulnerabilityAssessmentSettings(DatabaseVulnerabilityAssessmentSettingsModel model, string storageContainerPath, string storageAccountSasKey) { DatabaseVulnerabilityAssessment settings = new DatabaseVulnerabilityAssessment { StorageContainerPath = storageContainerPath, StorageContainerSasKey = storageAccountSasKey, RecurringScans = new VulnerabilityAssessmentRecurringScansProperties() { IsEnabled = model.RecurringScansInterval != RecurringScansInterval.None, EmailSubscriptionAdmins = model.EmailAdmins, Emails = model.NotificationEmail } }; var vulnerabilityAssessmentSettings = VulnerabilityAssessmentCommunicator.SetDatabaseVulnerabilityAssessmentSettings(model.ResourceGroupName, model.ServerName, model.DatabaseName, settings); return(ConvertSettingsToModel(model.ResourceGroupName, model.ServerName, model.DatabaseName, vulnerabilityAssessmentSettings)); }
private async Task <DatabaseVulnerabilityAssessment> SetPolicy(SqlManagementTestContext context, SqlManagementClient sqlClient, ResourceGroup resourceGroup, Server server, string dbName) { StorageContainerInfo StorageContainerInfo = await CreateStorageContainer(context, resourceGroup); DatabaseVulnerabilityAssessment policy = new DatabaseVulnerabilityAssessment() { StorageContainerPath = StorageContainerInfo.StorageContainerPath.ToString(), StorageContainerSasKey = StorageContainerInfo.StorageAccountSasKey, RecurringScans = new VulnerabilityAssessmentRecurringScansProperties() { IsEnabled = false, Emails = new List <string>() { "*****@*****.**", "*****@*****.**" }, EmailSubscriptionAdmins = true } }; return(sqlClient.DatabaseVulnerabilityAssessments.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, policy)); }
public virtual async Task <Response <DatabaseVulnerabilityAssessment> > CreateOrUpdateAsync(string resourceGroupName, string managedInstanceName, string databaseName, VulnerabilityAssessmentName vulnerabilityAssessmentName, DatabaseVulnerabilityAssessment parameters, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("ManagedDatabaseVulnerabilityAssessmentsOperations.CreateOrUpdate"); scope.Start(); try { return(await RestClient.CreateOrUpdateAsync(resourceGroupName, managedInstanceName, databaseName, vulnerabilityAssessmentName, parameters, cancellationToken).ConfigureAwait(false)); } catch (Exception e) { scope.Failed(e); throw; } }
/// <summary> /// Creates or updates the database's vulnerability assessment. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='managedInstanceName'> /// The name of the managed instance. /// </param> /// <param name='databaseName'> /// The name of the database for which the vulnerability assessment is defined. /// </param> /// <param name='parameters'> /// The requested resource. /// </param> public static DatabaseVulnerabilityAssessment CreateOrUpdate(this IManagedDatabaseVulnerabilityAssessmentsOperations operations, string resourceGroupName, string managedInstanceName, string databaseName, DatabaseVulnerabilityAssessment parameters) { return(operations.CreateOrUpdateAsync(resourceGroupName, managedInstanceName, databaseName, parameters).GetAwaiter().GetResult()); }
/// <summary> /// Creates or updates the database's vulnerability assessment. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='managedInstanceName'> /// The name of the managed instance. /// </param> /// <param name='databaseName'> /// The name of the database for which the vulnerability assessment is defined. /// </param> /// <param name='parameters'> /// The requested resource. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task <DatabaseVulnerabilityAssessment> CreateOrUpdateAsync(this IManagedDatabaseVulnerabilityAssessmentsOperations operations, string resourceGroupName, string managedInstanceName, string databaseName, DatabaseVulnerabilityAssessment parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, managedInstanceName, databaseName, parameters, null, cancellationToken).ConfigureAwait(false)) { return(_result.Body); } }
/// <summary> /// Calls the set Vulnerability Assessment APIs for the managed database Vulnerability Assessment Settings for the given managed database in the given managed instance in the given resource group /// </summary> public DatabaseVulnerabilityAssessment SetManagedDatabaseVulnerabilityAssessmentSettings(string resourceGroupName, string managedInstanceName, string databaseName, DatabaseVulnerabilityAssessment parameters) { return(GetCurrentSqlClient().ManagedDatabaseVulnerabilityAssessments.CreateOrUpdate(resourceGroupName, managedInstanceName, databaseName, parameters)); }
/// <summary> /// Provides a Vulnerability Assessment settings model for the given database /// </summary> public VulnerabilityAssessmentSettingsModel ConvertSettingsToModel(string resourceGroup, string serverName, string databaseName, DatabaseVulnerabilityAssessment settings) { if (settings.RecurringScans == null) { // This should never happen settings.RecurringScans = new VulnerabilityAssessmentRecurringScansProperties { IsEnabled = false, EmailSubscriptionAdmins = true, Emails = null }; } // Getting storage info from StorageContainerPath var storageAccountName = string.Empty; var storageBlobContainerName = string.Empty; if (!string.IsNullOrEmpty(settings.StorageContainerPath)) { // StorageContainerPath is in the format of : "https://va1storage.blob.core.windows.net/vulnerability-assessment" var storageAccountNamePart = settings.StorageContainerPath.Split(new[] { "https://" }, StringSplitOptions.RemoveEmptyEntries)[0]; if (!string.IsNullOrEmpty(storageAccountNamePart)) { storageAccountName = storageAccountNamePart.Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries)[0]; } storageBlobContainerName = settings.StorageContainerPath.Split(new[] { "/" }, StringSplitOptions.RemoveEmptyEntries).LastOrDefault(); } var vulnerabilityAssessmentSettingsModel = new VulnerabilityAssessmentSettingsModel { ResourceGroupName = resourceGroup, StorageAccountName = storageAccountName, ScanResultsContainerName = storageBlobContainerName, RecurringScansInterval = settings.RecurringScans.IsEnabled.Value ? RecurringScansInterval.Weekly : RecurringScansInterval.None, EmailAdmins = settings.RecurringScans.EmailSubscriptionAdmins.Value, NotificationEmail = settings.RecurringScans.Emails?.ToArray() }; return(vulnerabilityAssessmentSettingsModel); }
/// <summary> /// Provides a database Vulnerability Assessment settings model for the given database /// </summary> public DatabaseVulnerabilityAssessmentSettingsModel ConvertSettingsToModel(string resourceGroup, string serverName, string databaseName, DatabaseVulnerabilityAssessment settings) { if (settings.RecurringScans == null) { // This should never happen settings.RecurringScans = new VulnerabilityAssessmentRecurringScansProperties() { IsEnabled = false, EmailSubscriptionAdmins = true, Emails = null }; } // Getting storage info from StorageContainerPath string storageAccountName = string.Empty; string storageBlobContainerName = string.Empty; if (!string.IsNullOrEmpty(settings.StorageContainerPath)) { string storageAccountNamePart = settings.StorageContainerPath.Split(new string[] { "https://" }, StringSplitOptions.RemoveEmptyEntries)[0]; if (!string.IsNullOrEmpty(storageAccountNamePart)) { storageAccountName = storageAccountNamePart.Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries)[0]; } #if !NETSTANDARD CloudBlob cloudBlob = new CloudBlob(new Uri(settings.StorageContainerPath)); storageBlobContainerName = cloudBlob.Container.Name; #endif } var databaseVulnerabilityAssessmentSettingsModel = new DatabaseVulnerabilityAssessmentSettingsModel { ResourceGroupName = resourceGroup, ServerName = serverName, DatabaseName = databaseName, StorageAccountName = storageAccountName, ScanResultsContainerName = storageBlobContainerName, RecurringScansInterval = settings.RecurringScans.IsEnabled.Value ? RecurringScansInterval.Weekly : RecurringScansInterval.None, EmailAdmins = settings.RecurringScans.EmailSubscriptionAdmins.Value, NotificationEmail = settings.RecurringScans.Emails?.ToArray() }; return(databaseVulnerabilityAssessmentSettingsModel); }
public virtual Response <DatabaseVulnerabilityAssessment> CreateOrUpdate(string resourceGroupName, string serverName, string databaseName, VulnerabilityAssessmentName vulnerabilityAssessmentName, DatabaseVulnerabilityAssessment parameters, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("DatabaseVulnerabilityAssessmentsOperations.CreateOrUpdate"); scope.Start(); try { return(RestClient.CreateOrUpdate(resourceGroupName, serverName, databaseName, vulnerabilityAssessmentName, parameters, cancellationToken)); } catch (Exception e) { scope.Failed(e); throw; } }
/// <summary> /// Calls the set Vulnerability Assessment APIs for the database Vulnerability Assessment Settings for the given database in the given database server in the given resource group /// </summary> public DatabaseVulnerabilityAssessment SetDatabaseVulnerabilityAssessmentSettings(string resourceGroupName, string serverName, string databaseName, DatabaseVulnerabilityAssessment parameters) { return(GetCurrentSqlClient().DatabaseVulnerabilityAssessments.CreateOrUpdate(resourceGroupName, serverName, databaseName, parameters)); }
/// <summary> /// Creates or updates the database's vulnerability assessment. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='managedInstanceName'> /// The name of the managed instance. /// </param> /// <param name='databaseName'> /// The name of the database for which the vulnerability assessment is defined. /// </param> /// <param name='parameters'> /// The requested resource. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationResponse <DatabaseVulnerabilityAssessment> > CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string managedInstanceName, string databaseName, DatabaseVulnerabilityAssessment parameters, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (managedInstanceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "managedInstanceName"); } if (databaseName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "databaseName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string vulnerabilityAssessmentName = "default"; string apiVersion = "2017-10-01-preview"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("managedInstanceName", managedInstanceName); tracingParameters.Add("databaseName", databaseName); tracingParameters.Add("vulnerabilityAssessmentName", vulnerabilityAssessmentName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/databases/{databaseName}/vulnerabilityAssessments/{vulnerabilityAssessmentName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{managedInstanceName}", System.Uri.EscapeDataString(managedInstanceName)); _url = _url.Replace("{databaseName}", System.Uri.EscapeDataString(databaseName)); _url = _url.Replace("{vulnerabilityAssessmentName}", System.Uri.EscapeDataString(vulnerabilityAssessmentName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List <string> _queryParameters = new List <string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if (parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse <DatabaseVulnerabilityAssessment>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <DatabaseVulnerabilityAssessment>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <DatabaseVulnerabilityAssessment>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
/// <summary> /// Set settings with storage SAS key /// </summary> public VulnerabilityAssessmentSettingsModel SetVulnerabilityAssessmentSettingsWithStorageSasKey(VulnerabilityAssessmentSettingsModel model, string storageContainerPath, string storageAccountSasKey, string serverName, string databaseName, ApplyToType applyToType) { switch (applyToType) { case ApplyToType.Database: DatabaseVulnerabilityAssessment vaDbSettings = new DatabaseVulnerabilityAssessment { StorageContainerPath = storageContainerPath, StorageContainerSasKey = storageAccountSasKey, RecurringScans = new VulnerabilityAssessmentRecurringScansProperties() { IsEnabled = model.RecurringScansInterval != RecurringScansInterval.None, EmailSubscriptionAdmins = model.EmailAdmins, Emails = model.NotificationEmail } }; vaDbSettings = VulnerabilityAssessmentCommunicator.SetDatabaseVulnerabilityAssessmentSettings(model.ResourceGroupName, serverName, databaseName, vaDbSettings); return(ConvertSettingsToModel(model.ResourceGroupName, vaDbSettings.RecurringScans, vaDbSettings.StorageContainerPath)); case ApplyToType.ManagedDatabase: DatabaseVulnerabilityAssessment vaManagedDbSettings = new DatabaseVulnerabilityAssessment { StorageContainerPath = storageContainerPath, StorageContainerSasKey = storageAccountSasKey, RecurringScans = new VulnerabilityAssessmentRecurringScansProperties() { IsEnabled = model.RecurringScansInterval != RecurringScansInterval.None, EmailSubscriptionAdmins = model.EmailAdmins, Emails = model.NotificationEmail } }; vaManagedDbSettings = VulnerabilityAssessmentCommunicator.SetManagedDatabaseVulnerabilityAssessmentSettings(model.ResourceGroupName, serverName, databaseName, vaManagedDbSettings); return(ConvertSettingsToModel(model.ResourceGroupName, vaManagedDbSettings.RecurringScans, vaManagedDbSettings.StorageContainerPath)); case ApplyToType.Server: ServerVulnerabilityAssessment vaServerSettings = new ServerVulnerabilityAssessment { StorageContainerPath = storageContainerPath, StorageContainerSasKey = storageAccountSasKey, RecurringScans = new VulnerabilityAssessmentRecurringScansProperties() { IsEnabled = model.RecurringScansInterval != RecurringScansInterval.None, EmailSubscriptionAdmins = model.EmailAdmins, Emails = model.NotificationEmail } }; vaServerSettings = VulnerabilityAssessmentCommunicator.SetServerVulnerabilityAssessmentSettings(model.ResourceGroupName, serverName, vaServerSettings); return(ConvertSettingsToModel(model.ResourceGroupName, vaServerSettings.RecurringScans, vaServerSettings.StorageContainerPath)); case ApplyToType.ManagedInstance: ManagedInstanceVulnerabilityAssessment vaManagedInstanceSettings = new ManagedInstanceVulnerabilityAssessment { StorageContainerPath = storageContainerPath, StorageContainerSasKey = storageAccountSasKey, RecurringScans = new VulnerabilityAssessmentRecurringScansProperties() { IsEnabled = model.RecurringScansInterval != RecurringScansInterval.None, EmailSubscriptionAdmins = model.EmailAdmins, Emails = model.NotificationEmail } }; vaManagedInstanceSettings = VulnerabilityAssessmentCommunicator.SetManagedInstanceVulnerabilityAssessmentSettings(model.ResourceGroupName, serverName, vaManagedInstanceSettings); return(ConvertSettingsToModel(model.ResourceGroupName, vaManagedInstanceSettings.RecurringScans, vaManagedInstanceSettings.StorageContainerPath)); default: throw new ArgumentOutOfRangeException(nameof(applyToType), applyToType, null); } }