public void LogProfiles_PutTest() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(string.Empty), }; var handler = new RecordedDelegatingHandler(response); InsightsManagementClient customClient = this.GetInsightsManagementClient(handler); var parameters = new ServiceDiagnosticSettingsPutParameters { Properties = CreateDiagnosticSettings() }; customClient.ServiceDiagnosticSettingsOperations.Put(ResourceUri, parameters); var actualResponse = JsonExtensions.FromJson <ServiceDiagnosticSettingsPutParameters>(handler.Request); AreEqual(parameters.Properties, actualResponse.Properties); }
static void Main(string[] args) { string resourceGroupName = "<YOUR AZURE RESOURCE GROUP NAME>"; string streamAnalyticsJobName = "<YOUR STREAM ANALYTICS JOB NAME>"; // Get authentication token TokenCloudCredentials aadTokenCredentials = new TokenCloudCredentials( ConfigurationManager.AppSettings["SubscriptionId"], GetAuthorizationHeader()); Uri resourceManagerUri = new Uri(ConfigurationManager.AppSettings["ResourceManagerEndpoint"]); // Create Stream Analytics and Insights management client StreamAnalyticsManagementClient streamAnalyticsClient = new StreamAnalyticsManagementClient(aadTokenCredentials, resourceManagerUri); InsightsManagementClient insightsClient = new InsightsManagementClient(aadTokenCredentials, resourceManagerUri); // Get an existing Stream Analytics job JobGetParameters jobGetParameters = new JobGetParameters() { PropertiesToExpand = "inputs,transformation,outputs" }; JobGetResponse jobGetResponse = streamAnalyticsClient.StreamingJobs.Get(resourceGroupName, streamAnalyticsJobName, jobGetParameters); // Enable monitoring ServiceDiagnosticSettingsPutParameters insightPutParameters = new ServiceDiagnosticSettingsPutParameters() { Properties = new ServiceDiagnosticSettings() { StorageAccountName = "<YOUR STORAGE ACCOUNT NAME>" } }; InsightsClient.ServiceDiagnosticSettingsOperations.Put(jobGetResponse.Job.Id, insightPutParameters); }
protected override void ProcessRecordInternal() { var putParameters = new ServiceDiagnosticSettingsPutParameters(); ServiceDiagnosticSettingsGetResponse getResponse = this.InsightsManagementClient.ServiceDiagnosticSettingsOperations.GetAsync(this.ResourceId, CancellationToken.None).Result; ServiceDiagnosticSettings properties = getResponse.Properties; if (this.Enabled && string.IsNullOrWhiteSpace(this.StorageAccountId)) { throw new ArgumentException("StorageAccountId can't be null when enabling"); } if (!string.IsNullOrWhiteSpace(this.StorageAccountId)) { properties.StorageAccountId = this.StorageAccountId; } if (this.Categories == null && this.Timegrains == null) { foreach (var log in properties.Logs) { log.Enabled = this.Enabled; } foreach (var metric in properties.Metrics) { metric.Enabled = this.Enabled; } } else { if (this.Categories != null) { foreach (string category in this.Categories) { LogSettings logSettings = properties.Logs.FirstOrDefault(x => string.Equals(x.Category, category, StringComparison.OrdinalIgnoreCase)); if (logSettings == null) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Log category '{0}' is not available for '{1}'", category, this.StorageAccountId)); } logSettings.Enabled = this.Enabled; } } if (this.Timegrains != null) { foreach (string timegrainString in this.Timegrains) { TimeSpan timegrain = XmlConvert.ToTimeSpan(timegrainString); MetricSettings metricSettings = properties.Metrics.FirstOrDefault(x => TimeSpan.Equals(x.TimeGrain, timegrain)); if (metricSettings == null) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Metric timegrain '{0}' is not available for '{1}'", timegrainString, this.StorageAccountId)); } metricSettings.Enabled = this.Enabled; } } } putParameters.Properties = properties; this.InsightsManagementClient.ServiceDiagnosticSettingsOperations.PutAsync(this.ResourceId, putParameters, CancellationToken.None).Wait(); PSServiceDiagnosticSettings psResult = new PSServiceDiagnosticSettings(putParameters.Properties); WriteObject(psResult); }
/// <summary> /// Create or update new diagnostic settings for the specified /// resource. This operation is long running. Use GetStatus to check /// the status of this operation. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Insights.IServiceDiagnosticSettingsOperations. /// </param> /// <param name='resourceUri'> /// Required. The resource identifier of the configuration. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the operation. /// </param> /// <returns> /// Generic empty response. We only pass it to ensure json error /// handling /// </returns> public static Task <EmptyResponse> PutAsync(this IServiceDiagnosticSettingsOperations operations, string resourceUri, ServiceDiagnosticSettingsPutParameters parameters) { return(operations.PutAsync(resourceUri, parameters, CancellationToken.None)); }
/// <summary> /// Create or update new diagnostic settings for the specified /// resource. This operation is long running. Use GetStatus to check /// the status of this operation. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Insights.IServiceDiagnosticSettingsOperations. /// </param> /// <param name='resourceUri'> /// Required. The resource identifier of the configuration. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the operation. /// </param> /// <returns> /// Generic empty response. We only pass it to ensure json error /// handling /// </returns> public static EmptyResponse Put(this IServiceDiagnosticSettingsOperations operations, string resourceUri, ServiceDiagnosticSettingsPutParameters parameters) { return(Task.Factory.StartNew((object s) => { return ((IServiceDiagnosticSettingsOperations)s).PutAsync(resourceUri, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult()); }
/// <summary> /// Create or update new diagnostic settings for the specified /// resource. This operation is long running. Use GetStatus to check /// the status of this operation. /// </summary> /// <param name='resourceUri'> /// Required. The resource identifier of the configuration. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Generic empty response. We only pass it to ensure json error /// handling /// </returns> public async Task <EmptyResponse> PutAsync(string resourceUri, ServiceDiagnosticSettingsPutParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceUri == null) { throw new ArgumentNullException("resourceUri"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("resourceUri", resourceUri); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "PutAsync", tracingParameters); } // Construct URL string url = "/" + Uri.EscapeDataString(resourceUri) + "/diagnosticSettings/service?"; url = url + "api-version=2014-04-01"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject serviceDiagnosticSettingsPutParametersValue = new JObject(); requestDoc = serviceDiagnosticSettingsPutParametersValue; if (parameters.Properties != null) { JObject propertiesValue = new JObject(); serviceDiagnosticSettingsPutParametersValue["properties"] = propertiesValue; if (parameters.Properties.StorageAccountName != null) { propertiesValue["storageAccountName"] = parameters.Properties.StorageAccountName; } propertiesValue["status"] = parameters.Properties.Status.ToString(); } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result EmptyResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created || statusCode == HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new EmptyResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }
public SetDiagnosticSettingCommandTests() { insightsDiagnosticsOperationsMock = new Mock <IServiceDiagnosticSettingsOperations>(); insightsManagementClientMock = new Mock <InsightsManagementClient>(); commandRuntimeMock = new Mock <ICommandRuntime>(); cmdlet = new SetAzureRmDiagnosticSettingCommand() { CommandRuntime = commandRuntimeMock.Object, InsightsManagementClient = insightsManagementClientMock.Object }; response = new ServiceDiagnosticSettingsGetResponse { RequestId = Guid.NewGuid().ToString(), StatusCode = HttpStatusCode.OK, Properties = new ServiceDiagnosticSettings { StorageAccountId = storageAccountId, Logs = new List <LogSettings> { new LogSettings { Category = "TestCategory1", Enabled = true }, new LogSettings { Category = "TestCategory2", Enabled = false } }, Metrics = new List <MetricSettings> { new MetricSettings { TimeGrain = TimeSpan.FromMinutes(1), Enabled = false }, new MetricSettings { TimeGrain = TimeSpan.FromHours(1), Enabled = true } } } }; insightsDiagnosticsOperationsMock.Setup(f => f.GetAsync(It.IsAny <string>())) .Returns(Task.FromResult <ServiceDiagnosticSettingsGetResponse>(response)) .Callback((string resourceId) => { this.calledResourceId = resourceId; }); insightsDiagnosticsOperationsMock.Setup(f => f.PutAsync(It.IsAny <string>(), It.IsAny <ServiceDiagnosticSettingsPutParameters>())) .Returns(Task.FromResult <EmptyResponse>(new EmptyResponse())) .Callback((string resourceId, ServiceDiagnosticSettingsPutParameters putParameters) => { this.calledResourceId = resourceId; this.calledPutParameters = putParameters; }); insightsManagementClientMock.SetupGet(f => f.ServiceDiagnosticSettingsOperations).Returns(this.insightsDiagnosticsOperationsMock.Object); }
/// <summary> /// Create or update new diagnostic settings for the specified /// resource. This operation is long running. Use GetStatus to check /// the status of this operation. /// </summary> /// <param name='resourceUri'> /// Required. The resource identifier of the configuration. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Generic empty response. We only pass it to ensure json error /// handling /// </returns> public async Task <EmptyResponse> PutAsync(string resourceUri, ServiceDiagnosticSettingsPutParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceUri == null) { throw new ArgumentNullException("resourceUri"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("resourceUri", resourceUri); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "PutAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; url = url + Uri.EscapeDataString(resourceUri); url = url + "/providers/microsoft.insights/diagnosticSettings/service"; List <string> queryParameters = new List <string>(); queryParameters.Add("api-version=2015-07-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject serviceDiagnosticSettingsPutParametersValue = new JObject(); requestDoc = serviceDiagnosticSettingsPutParametersValue; if (parameters.Properties != null) { JObject propertiesValue = new JObject(); serviceDiagnosticSettingsPutParametersValue["properties"] = propertiesValue; if (parameters.Properties.StorageAccountId != null) { propertiesValue["storageAccountId"] = parameters.Properties.StorageAccountId; } if (parameters.Properties.ServiceBusRuleId != null) { propertiesValue["serviceBusRuleId"] = parameters.Properties.ServiceBusRuleId; } if (parameters.Properties.StorageAccountName != null) { propertiesValue["storageAccountName"] = parameters.Properties.StorageAccountName; } if (parameters.Properties.Metrics != null) { if (parameters.Properties.Metrics is ILazyCollection == false || ((ILazyCollection)parameters.Properties.Metrics).IsInitialized) { JArray metricsArray = new JArray(); foreach (MetricSettings metricsItem in parameters.Properties.Metrics) { JObject metricSettingsValue = new JObject(); metricsArray.Add(metricSettingsValue); metricSettingsValue["timeGrain"] = XmlConvert.ToString(metricsItem.TimeGrain); metricSettingsValue["enabled"] = metricsItem.Enabled; if (metricsItem.RetentionPolicy != null) { JObject retentionPolicyValue = new JObject(); metricSettingsValue["retentionPolicy"] = retentionPolicyValue; retentionPolicyValue["enabled"] = metricsItem.RetentionPolicy.Enabled; retentionPolicyValue["days"] = metricsItem.RetentionPolicy.Days; } } propertiesValue["metrics"] = metricsArray; } } if (parameters.Properties.Logs != null) { if (parameters.Properties.Logs is ILazyCollection == false || ((ILazyCollection)parameters.Properties.Logs).IsInitialized) { JArray logsArray = new JArray(); foreach (LogSettings logsItem in parameters.Properties.Logs) { JObject logSettingsValue = new JObject(); logsArray.Add(logSettingsValue); if (logsItem.Category != null) { logSettingsValue["category"] = logsItem.Category; } logSettingsValue["enabled"] = logsItem.Enabled; if (logsItem.RetentionPolicy != null) { JObject retentionPolicyValue2 = new JObject(); logSettingsValue["retentionPolicy"] = retentionPolicyValue2; retentionPolicyValue2["enabled"] = logsItem.RetentionPolicy.Enabled; retentionPolicyValue2["days"] = logsItem.RetentionPolicy.Days; } } propertiesValue["logs"] = logsArray; } } } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result EmptyResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created || statusCode == HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new EmptyResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }