/// <summary>
        /// A string representation of the RuleMetricDataSource including indentation
        /// </summary>
        /// <param name="actions">The RuleAction objects</param>
        /// <param name="indentationTabs">The number of tabs to insert in front of each member</param>
        /// <returns>A string representation of the list of RuleAction objects including indentation</returns>
        public static string ToString(this IList <RuleAction> actions, int indentationTabs)
        {
            StringBuilder output = new StringBuilder();

            if (actions != null)
            {
                foreach (var action in actions)
                {
                    output.AppendLine();
                    RuleEmailAction eMailAction = action as RuleEmailAction;
                    if (eMailAction != null)
                    {
                        output.AddSpacesInFront(indentationTabs).AppendLine("SendToServiceOwners : " + eMailAction.SendToServiceOwners);
                        output.AddSpacesInFront(indentationTabs).Append("E-mails             : " + eMailAction.CustomEmails.ToString(indentationTabs: indentationTabs + 1));
                    }
                    else
                    {
                        RuleWebhookAction webhookAction = action as RuleWebhookAction;
                        if (webhookAction != null)
                        {
                            output.AddSpacesInFront(indentationTabs).AppendLine("ServiceUri : " + webhookAction.ServiceUri);
                            output.AddSpacesInFront(indentationTabs).Append("Properties : " + webhookAction.Properties.ToString(indentationTabs: indentationTabs + 1));
                        }
                        else
                        {
                            output.AddSpacesInFront(indentationTabs).AppendLine(string.Format("Unsupported rule type <{0}>", action));
                        }
                    }
                }
            }

            return(output.ToString());
        }
Пример #2
0
        /// <summary>
        /// Execute the cmdlet
        /// </summary>
        public override void ExecuteCmdlet()
        {
            if (!this.SendToServiceOwners && (this.CustomEmails == null || this.CustomEmails.Length < 1))
            {
                throw new ArgumentException("Either SendToServiceOwners must be set or at least one custom email must be present");
            }

            var action = new RuleEmailAction
            {
                CustomEmails        = this.CustomEmails,
                SendToServiceOwners = this.SendToServiceOwners
            };

            WriteObject(action);
        }
        /// <summary>
        /// Execute the cmdlet
        /// </summary>
        public override void ExecuteCmdlet()
        {
            this.WriteIdentifiedWarning(
                cmdletName: "New-AzureRmAlertRuleEmail",
                topic: "Parameter name change",
                message: "The parameter plural names for the parameters will be deprecated in a future breaking change release in favor of the singular versions of the same names.");
            if (!this.SendToServiceOwner && (this.CustomEmail == null || this.CustomEmail.Length < 1))
            {
                throw new ArgumentException("Either SendToServiceOwners must be set or at least one custom email must be present");
            }

            var action = new RuleEmailAction
            {
                CustomEmails        = this.CustomEmail,
                SendToServiceOwners = this.SendToServiceOwner
            };

            WriteObject(action);
        }
Пример #4
0
        private static Task <OperationResponse> CreateAzureAlert(string resourceId, AlertsClient alertsClient)
        {
            var rule = new Rule
            {
                Name        = "CPU Alert",
                Id          = Guid.NewGuid().ToString(),
                Description = "If CPU usage is greater than twenty percent then alert",
                IsEnabled   = true,
                Condition   = new ThresholdRuleCondition
                {
                    Operator   = ConditionOperator.GreaterThan,
                    Threshold  = 10,
                    WindowSize = TimeSpan.FromMinutes(15), //new TimeSpan(0,0,5,0),
                    DataSource = new RuleMetricDataSource
                    {
                        MetricName      = "Percentage CPU",
                        ResourceId      = resourceId,
                        MetricNamespace = string.Empty //"WindowsAzure.Availability"
                    }
                }
            };

            RuleAction action = new RuleEmailAction
            {
                SendToServiceOwners = true
            };

            ((RuleEmailAction)action).CustomEmails.Add(_alertEmailAddress);
            rule.Actions.Add(action);
            rule.LastUpdatedTime = DateTime.UtcNow;

            var response = alertsClient.Rules.CreateOrUpdateAsync(new RuleCreateOrUpdateParameters
            {
                Rule = rule
            }, CancellationToken.None);

            return(response);
        }
Пример #5
0
        public void AddAzureRmWebtestAlertRuleCommandParametersProcessing()
        {
            // Test null actions
            cmdlet.Name                = Utilities.Name;
            cmdlet.Location            = "East US";
            cmdlet.ResourceGroup       = Utilities.ResourceGroup;
            cmdlet.FailedLocationCount = 10;
            cmdlet.Actions             = null;
            cmdlet.WindowSize          = TimeSpan.FromMinutes(15);

            cmdlet.ExecuteCmdlet();

            this.AssertResults(
                location: "East US",
                tagsKey: "hidden-link:",
                isEnabled: true,
                actionsNull: true,
                actionsCount: 0,
                failedLocationCount: 10,
                totalMinutes: 15);

            // Test null actions and disabled
            cmdlet.DisableRule = true;

            cmdlet.ExecuteCmdlet();

            this.AssertResults(
                location: "East US",
                tagsKey: "hidden-link:",
                isEnabled: false,
                actionsNull: true,
                actionsCount: 0,
                failedLocationCount: 10,
                totalMinutes: 15);

            // Test empty actions
            cmdlet.DisableRule = false;
            cmdlet.Actions     = new List <RuleAction>();

            cmdlet.ExecuteCmdlet();

            this.AssertResults(
                location: "East US",
                tagsKey: "hidden-link:",
                isEnabled: true,
                actionsNull: false,
                actionsCount: 0,
                failedLocationCount: 10,
                totalMinutes: 15);

            // Test non-empty actions (one action)
            List <string> eMails = new List <string>();

            eMails.Add("*****@*****.**");
            RuleAction ruleAction = new RuleEmailAction
            {
                SendToServiceOwners = true,
                CustomEmails        = eMails
            };

            cmdlet.Actions.Add(ruleAction);

            cmdlet.ExecuteCmdlet();

            this.AssertResults(
                location: "East US",
                tagsKey: "hidden-link:",
                isEnabled: true,
                actionsNull: false,
                actionsCount: 1,
                failedLocationCount: 10,
                totalMinutes: 15);

            // Test non-empty actions (two actions)
            var properties = new Dictionary <string, string>();

            properties.Add("hello", "goodbye");
            ruleAction = new RuleWebhookAction
            {
                ServiceUri = "http://bueno.net",
                Properties = properties
            };

            cmdlet.Actions.Add(ruleAction);

            cmdlet.ExecuteCmdlet();

            this.AssertResults(
                location: "East US",
                tagsKey: "hidden-link:",
                isEnabled: true,
                actionsNull: false,
                actionsCount: 2,
                failedLocationCount: 10,
                totalMinutes: 15);

            // Test non-empty actions (two actions) and non-default window size
            cmdlet.WindowSize = TimeSpan.FromMinutes(300);

            cmdlet.ExecuteCmdlet();

            this.AssertResults(
                location: "East US",
                tagsKey: "hidden-link:",
                isEnabled: true,
                actionsNull: false,
                actionsCount: 2,
                failedLocationCount: 10,
                totalMinutes: 300);
        }
Пример #6
0
        /// <param name='parameters'>
        /// The rule to create or update.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// A standard service response including an HTTP status code and
        /// request ID.
        /// </returns>
        public async System.Threading.Tasks.Task <OperationResponse> CreateOrUpdateAsync(RuleCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
        {
            // Validate
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = Tracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("parameters", parameters);
                Tracing.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
            }

            // Construct URL
            string url = new Uri(this.Client.BaseUri, "/").AbsoluteUri + this.Client.Credentials.SubscriptionId + "/services/monitoring/alertrules/" + parameters.Rule.Id;

            // 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");
                httpRequest.Headers.Add("x-ms-version", "2013-10-01");

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Serialize Request
                string requestContent = null;
                JToken requestDoc     = null;

                if (parameters.Rule != null)
                {
                    JObject ruleValue = new JObject();
                    requestDoc = ruleValue;

                    if (parameters.Rule.Id != null)
                    {
                        ruleValue["Id"] = parameters.Rule.Id;
                    }

                    if (parameters.Rule.Name != null)
                    {
                        ruleValue["Name"] = parameters.Rule.Name;
                    }

                    if (parameters.Rule.Description != null)
                    {
                        ruleValue["Description"] = parameters.Rule.Description;
                    }

                    ruleValue["IsEnabled"] = parameters.Rule.IsEnabled;

                    if (parameters.Rule.Condition != null)
                    {
                        JObject conditionValue = new JObject();
                        ruleValue["Condition"]       = conditionValue;
                        conditionValue["odata.type"] = parameters.Rule.Condition.GetType().FullName;
                        if (parameters.Rule.Condition is ThresholdRuleCondition)
                        {
                            ThresholdRuleCondition derived = (ThresholdRuleCondition)parameters.Rule.Condition;

                            if (derived.DataSource != null)
                            {
                                JObject dataSourceValue = new JObject();
                                conditionValue["DataSource"]  = dataSourceValue;
                                dataSourceValue["odata.type"] = derived.DataSource.GetType().FullName;
                                if (derived.DataSource is RuleMetricDataSource)
                                {
                                    RuleMetricDataSource derived2 = (RuleMetricDataSource)derived.DataSource;

                                    if (derived2.ResourceId != null)
                                    {
                                        dataSourceValue["ResourceId"] = derived2.ResourceId;
                                    }

                                    if (derived2.MetricNamespace != null)
                                    {
                                        dataSourceValue["MetricNamespace"] = derived2.MetricNamespace;
                                    }

                                    if (derived2.MetricName != null)
                                    {
                                        dataSourceValue["MetricName"] = derived2.MetricName;
                                    }
                                }
                            }

                            conditionValue["Operator"] = derived.Operator.ToString();

                            conditionValue["Threshold"] = derived.Threshold;

                            conditionValue["WindowSize"] = TypeConversion.To8601String(derived.WindowSize);
                        }
                    }

                    if (parameters.Rule.Actions != null)
                    {
                        JArray actionsArray = new JArray();
                        foreach (RuleAction actionsItem in parameters.Rule.Actions)
                        {
                            JObject ruleActionValue = new JObject();
                            actionsArray.Add(ruleActionValue);
                            ruleActionValue["odata.type"] = actionsItem.GetType().FullName;
                            if (actionsItem is RuleEmailAction)
                            {
                                RuleEmailAction derived3 = (RuleEmailAction)actionsItem;

                                ruleActionValue["SendToServiceOwners"] = derived3.SendToServiceOwners;

                                if (derived3.CustomEmails != null)
                                {
                                    JArray customEmailsArray = new JArray();
                                    foreach (string customEmailsItem in derived3.CustomEmails)
                                    {
                                        customEmailsArray.Add(customEmailsItem);
                                    }
                                    ruleActionValue["CustomEmails"] = customEmailsArray;
                                }
                            }
                        }
                        ruleValue["Actions"] = actionsArray;
                    }

                    ruleValue["LastUpdatedTime"] = parameters.Rule.LastUpdatedTime;
                }

                requestContent      = requestDoc.ToString(Formatting.Indented);
                httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
                httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        Tracing.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        Tracing.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Json);
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    OperationResponse result = null;
                    result            = new OperationResponse();
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        Tracing.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
Пример #7
0
        /// <summary>
        /// List the alert rules within a subscription.
        /// </summary>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The List Rules operation response.
        /// </returns>
        public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.RuleListResponse> ListAsync(CancellationToken cancellationToken)
        {
            // Validate

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = Tracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                Tracing.Enter(invocationId, this, "ListAsync", tracingParameters);
            }

            // Construct URL
            string url = new Uri(this.Client.BaseUri, "/").AbsoluteUri + this.Client.Credentials.SubscriptionId + "/services/monitoring/alertrules";

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

            try
            {
                httpRequest            = new HttpRequestMessage();
                httpRequest.Method     = HttpMethod.Get;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers
                httpRequest.Headers.Add("Accept", "application/json");
                httpRequest.Headers.Add("x-ms-version", "2013-10-01");

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        Tracing.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        Tracing.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Json);
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    RuleListResponse result = null;
                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    result = new RuleListResponse();
                    JToken responseDoc = JToken.Parse(responseContent);

                    if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                    {
                        JToken valueArray = responseDoc["Value"];
                        if (valueArray != null && valueArray.Type != JTokenType.Null)
                        {
                            foreach (JToken valueValue in (JArray)valueArray)
                            {
                                Rule ruleInstance = new Rule();
                                result.Value.Add(ruleInstance);

                                JToken idValue = valueValue["Id"];
                                if (idValue != null && idValue.Type != JTokenType.Null)
                                {
                                    string idInstance = (string)idValue;
                                    ruleInstance.Id = idInstance;
                                }

                                JToken nameValue = valueValue["Name"];
                                if (nameValue != null && nameValue.Type != JTokenType.Null)
                                {
                                    string nameInstance = (string)nameValue;
                                    ruleInstance.Name = nameInstance;
                                }

                                JToken descriptionValue = valueValue["Description"];
                                if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
                                {
                                    string descriptionInstance = (string)descriptionValue;
                                    ruleInstance.Description = descriptionInstance;
                                }

                                JToken isEnabledValue = valueValue["IsEnabled"];
                                if (isEnabledValue != null && isEnabledValue.Type != JTokenType.Null)
                                {
                                    bool isEnabledInstance = (bool)isEnabledValue;
                                    ruleInstance.IsEnabled = isEnabledInstance;
                                }

                                JToken conditionValue = valueValue["Condition"];
                                if (conditionValue != null && conditionValue.Type != JTokenType.Null)
                                {
                                    string typeName = (string)conditionValue["odata.type"];
                                    if (typeName == "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.ThresholdRuleCondition")
                                    {
                                        ThresholdRuleCondition thresholdRuleConditionInstance = new ThresholdRuleCondition();

                                        JToken dataSourceValue = conditionValue["DataSource"];
                                        if (dataSourceValue != null && dataSourceValue.Type != JTokenType.Null)
                                        {
                                            string typeName2 = (string)dataSourceValue["odata.type"];
                                            if (typeName2 == "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.RuleMetricDataSource")
                                            {
                                                RuleMetricDataSource ruleMetricDataSourceInstance = new RuleMetricDataSource();

                                                JToken resourceIdValue = dataSourceValue["ResourceId"];
                                                if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null)
                                                {
                                                    string resourceIdInstance = (string)resourceIdValue;
                                                    ruleMetricDataSourceInstance.ResourceId = resourceIdInstance;
                                                }

                                                JToken metricNamespaceValue = dataSourceValue["MetricNamespace"];
                                                if (metricNamespaceValue != null && metricNamespaceValue.Type != JTokenType.Null)
                                                {
                                                    string metricNamespaceInstance = (string)metricNamespaceValue;
                                                    ruleMetricDataSourceInstance.MetricNamespace = metricNamespaceInstance;
                                                }

                                                JToken metricNameValue = dataSourceValue["MetricName"];
                                                if (metricNameValue != null && metricNameValue.Type != JTokenType.Null)
                                                {
                                                    string metricNameInstance = (string)metricNameValue;
                                                    ruleMetricDataSourceInstance.MetricName = metricNameInstance;
                                                }
                                                thresholdRuleConditionInstance.DataSource = ruleMetricDataSourceInstance;
                                            }
                                        }

                                        JToken operatorValue = conditionValue["Operator"];
                                        if (operatorValue != null && operatorValue.Type != JTokenType.Null)
                                        {
                                            ConditionOperator operatorInstance = (ConditionOperator)Enum.Parse(typeof(ConditionOperator), (string)operatorValue, false);
                                            thresholdRuleConditionInstance.Operator = operatorInstance;
                                        }

                                        JToken thresholdValue = conditionValue["Threshold"];
                                        if (thresholdValue != null && thresholdValue.Type != JTokenType.Null)
                                        {
                                            double thresholdInstance = (double)thresholdValue;
                                            thresholdRuleConditionInstance.Threshold = thresholdInstance;
                                        }

                                        JToken windowSizeValue = conditionValue["WindowSize"];
                                        if (windowSizeValue != null && windowSizeValue.Type != JTokenType.Null)
                                        {
                                            TimeSpan windowSizeInstance = TypeConversion.From8601TimeSpan((string)windowSizeValue);
                                            thresholdRuleConditionInstance.WindowSize = windowSizeInstance;
                                        }
                                        ruleInstance.Condition = thresholdRuleConditionInstance;
                                    }
                                }

                                JToken actionsArray = valueValue["Actions"];
                                if (actionsArray != null && actionsArray.Type != JTokenType.Null)
                                {
                                    foreach (JToken actionsValue in (JArray)actionsArray)
                                    {
                                        string typeName3 = (string)actionsValue["odata.type"];
                                        if (typeName3 == "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.RuleEmailAction")
                                        {
                                            RuleEmailAction ruleEmailActionInstance = new RuleEmailAction();

                                            JToken sendToServiceOwnersValue = actionsValue["SendToServiceOwners"];
                                            if (sendToServiceOwnersValue != null && sendToServiceOwnersValue.Type != JTokenType.Null)
                                            {
                                                bool sendToServiceOwnersInstance = (bool)sendToServiceOwnersValue;
                                                ruleEmailActionInstance.SendToServiceOwners = sendToServiceOwnersInstance;
                                            }

                                            JToken customEmailsArray = actionsValue["CustomEmails"];
                                            if (customEmailsArray != null && customEmailsArray.Type != JTokenType.Null)
                                            {
                                                foreach (JToken customEmailsValue in (JArray)customEmailsArray)
                                                {
                                                    ruleEmailActionInstance.CustomEmails.Add((string)customEmailsValue);
                                                }
                                            }
                                            ruleInstance.Actions.Add(ruleEmailActionInstance);
                                        }
                                    }
                                }

                                JToken lastUpdatedTimeValue = valueValue["LastUpdatedTime"];
                                if (lastUpdatedTimeValue != null && lastUpdatedTimeValue.Type != JTokenType.Null)
                                {
                                    DateTime lastUpdatedTimeInstance = (DateTime)lastUpdatedTimeValue;
                                    ruleInstance.LastUpdatedTime = lastUpdatedTimeInstance;
                                }
                            }
                        }
                    }

                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        Tracing.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
Пример #8
0
        /// <summary>
        /// Adds properties for web test alert.
        /// </summary>
        /// <param name="parameters"><see cref="RuleCreateOrUpdateParameters"/> instance.</param>
        /// <param name="name">Name of web test.</param>
        /// <param name="element"><see cref="WebTestElement"/> instance from App.config/Web.config.</param>
        /// <param name="webTest"><see cref="ResourceBaseExtended"/> instance representing web test resource.</param>
        /// <param name="insights"><see cref="ResourceBaseExtended"/> instance representing Application Insights resource.</param>
        /// <returns>Returns the <see cref="RuleCreateOrUpdateParameters"/> instance with properties added.</returns>
        public static RuleCreateOrUpdateParameters AddProperties(this RuleCreateOrUpdateParameters parameters, string name, WebTestElement element, ResourceBaseExtended webTest, ResourceBaseExtended insights)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentNullException(nameof(name));
            }

            if (element == null)
            {
                throw new ArgumentNullException(nameof(element));
            }

            if (webTest == null)
            {
                throw new ArgumentNullException(nameof(webTest));
            }

            if (insights == null)
            {
                throw new ArgumentNullException(nameof(insights));
            }

            var alertName = $"{name}-{insights.Name}-alert".ToLowerInvariant();

            var action = new RuleEmailAction()
            {
                SendToServiceOwners = element.Alerts.SendAlertToAdmin
            };

            if (!element.Alerts.Recipients.IsNullOrEmpty())
            {
                action.CustomEmails = element.Alerts.Recipients;
            }

            var source = new RuleMetricDataSource()
            {
                MetricName = AlertMetricName, ResourceUri = webTest.Id
            };
            var condition = new LocationThresholdRuleCondition()
            {
                DataSource          = source,
                FailedLocationCount = element.Alerts.AlertLocationThreshold,
                WindowSize          = TimeSpan.FromMinutes((int)element.Alerts.TestAlertFailureTimeWindow),
            };
            var rule = new Rule()
            {
                Name            = alertName,
                Description     = string.Empty,
                IsEnabled       = element.Alerts.IsEnabled,
                LastUpdatedTime = DateTime.UtcNow,
                Actions         = { action },
                Condition       = condition,
            };

            parameters.Properties = rule;

            return(parameters);
        }
        public void AddAzureRmMetricAlertRuleCommandParametersProcessing()
        {
            // Test null actions
            cmdlet.Name                    = Utilities.Name;
            cmdlet.Location                = "East US";
            cmdlet.ResourceGroup           = Utilities.ResourceGroup;
            cmdlet.Operator                = ConditionOperator.GreaterThan;
            cmdlet.Threshold               = 1;
            cmdlet.TargetResourceId        = "/subscriptions/a93fb07c-6c93-40be-bf3b-4f0deba10f4b/resourceGroups/Default-Web-EastUS/providers/microsoft.web/sites/misitiooeltuyo";
            cmdlet.MetricName              = "Requests";
            cmdlet.TimeAggregationOperator = TimeAggregationOperator.Total;
            cmdlet.Actions                 = null;
            cmdlet.WindowSize              = TimeSpan.FromMinutes(10);

            cmdlet.ExecuteCmdlet();

            this.AssertResult(
                location: "East US",
                tagsKey: "hidden-link:/subscriptions/a93fb07c-6c93-40be-bf3b-4f0deba10f4b/resourceGroups/Default-Web-EastUS/providers/microsoft.web/sites/misitiooeltuyo",
                isEnabled: true,
                actionsNull: true,
                actionsCount: 0,
                threshold: 1,
                conditionOperator: ConditionOperator.GreaterThan,
                totalMinutes: 10,
                timeAggregationOperator: TimeAggregationOperator.Total,
                metricName: "Requests",
                resourceUri: "/subscriptions/a93fb07c-6c93-40be-bf3b-4f0deba10f4b/resourceGroups/Default-Web-EastUS/providers/microsoft.web/sites/misitiooeltuyo");

            // Test null actions and disabled
            cmdlet.DisableRule = true;

            cmdlet.ExecuteCmdlet();

            this.AssertResult(
                location: "East US",
                tagsKey: "hidden-link:/subscriptions/a93fb07c-6c93-40be-bf3b-4f0deba10f4b/resourceGroups/Default-Web-EastUS/providers/microsoft.web/sites/misitiooeltuyo",
                isEnabled: false,
                actionsNull: true,
                actionsCount: 0,
                threshold: 1,
                conditionOperator: ConditionOperator.GreaterThan,
                totalMinutes: 10,
                timeAggregationOperator: TimeAggregationOperator.Total,
                metricName: "Requests",
                resourceUri: "/subscriptions/a93fb07c-6c93-40be-bf3b-4f0deba10f4b/resourceGroups/Default-Web-EastUS/providers/microsoft.web/sites/misitiooeltuyo");

            // Test empty actions
            cmdlet.DisableRule = false;
            cmdlet.Actions     = new List <RuleAction>();

            cmdlet.ExecuteCmdlet();

            this.AssertResult(
                location: "East US",
                tagsKey: "hidden-link:/subscriptions/a93fb07c-6c93-40be-bf3b-4f0deba10f4b/resourceGroups/Default-Web-EastUS/providers/microsoft.web/sites/misitiooeltuyo",
                isEnabled: true,
                actionsNull: false,
                actionsCount: 0,
                threshold: 1,
                conditionOperator: ConditionOperator.GreaterThan,
                totalMinutes: 10,
                timeAggregationOperator: TimeAggregationOperator.Total,
                metricName: "Requests",
                resourceUri: "/subscriptions/a93fb07c-6c93-40be-bf3b-4f0deba10f4b/resourceGroups/Default-Web-EastUS/providers/microsoft.web/sites/misitiooeltuyo");

            // Test non-empty actions (one action)
            List <string> eMails = new List <string>();

            eMails.Add("*****@*****.**");
            RuleAction ruleAction = new RuleEmailAction
            {
                SendToServiceOwners = true,
                CustomEmails        = eMails
            };

            cmdlet.Actions.Add(ruleAction);

            cmdlet.ExecuteCmdlet();

            this.AssertResult(
                location: "East US",
                tagsKey: "hidden-link:/subscriptions/a93fb07c-6c93-40be-bf3b-4f0deba10f4b/resourceGroups/Default-Web-EastUS/providers/microsoft.web/sites/misitiooeltuyo",
                isEnabled: true,
                actionsNull: false,
                actionsCount: 1,
                threshold: 1,
                conditionOperator: ConditionOperator.GreaterThan,
                totalMinutes: 10,
                timeAggregationOperator: TimeAggregationOperator.Total,
                metricName: "Requests",
                resourceUri: "/subscriptions/a93fb07c-6c93-40be-bf3b-4f0deba10f4b/resourceGroups/Default-Web-EastUS/providers/microsoft.web/sites/misitiooeltuyo");

            // Test non-empty actions (two actions)
            var properties = new Dictionary <string, string>();

            properties.Add("hello", "goodbye");
            ruleAction = new RuleWebhookAction
            {
                ServiceUri = "http://bueno.net",
                Properties = properties
            };

            cmdlet.Actions.Add(ruleAction);

            cmdlet.ExecuteCmdlet();

            this.AssertResult(
                location: "East US",
                tagsKey: "hidden-link:/subscriptions/a93fb07c-6c93-40be-bf3b-4f0deba10f4b/resourceGroups/Default-Web-EastUS/providers/microsoft.web/sites/misitiooeltuyo",
                isEnabled: true,
                actionsNull: false,
                actionsCount: 2,
                threshold: 1,
                conditionOperator: ConditionOperator.GreaterThan,
                totalMinutes: 10,
                timeAggregationOperator: TimeAggregationOperator.Total,
                metricName: "Requests",
                resourceUri: "/subscriptions/a93fb07c-6c93-40be-bf3b-4f0deba10f4b/resourceGroups/Default-Web-EastUS/providers/microsoft.web/sites/misitiooeltuyo");

            // Test non-empty actions (two actions) and non-default window size
            cmdlet.WindowSize = TimeSpan.FromMinutes(300);

            cmdlet.ExecuteCmdlet();

            this.AssertResult(
                location: "East US",
                tagsKey: "hidden-link:/subscriptions/a93fb07c-6c93-40be-bf3b-4f0deba10f4b/resourceGroups/Default-Web-EastUS/providers/microsoft.web/sites/misitiooeltuyo",
                isEnabled: true,
                actionsNull: false,
                actionsCount: 2,
                threshold: 1,
                conditionOperator: ConditionOperator.GreaterThan,
                totalMinutes: 300,
                timeAggregationOperator: TimeAggregationOperator.Total,
                metricName: "Requests",
                resourceUri: "/subscriptions/a93fb07c-6c93-40be-bf3b-4f0deba10f4b/resourceGroups/Default-Web-EastUS/providers/microsoft.web/sites/misitiooeltuyo");
        }
        public void AddAlertRuleCommandParametersProcessing()
        {
            // Null actions
            cmdlet.Name             = Utilities.Name;
            cmdlet.Location         = "East US";
            cmdlet.ResourceGroup    = Utilities.ResourceGroup;
            cmdlet.TargetResourceId = "/subscriptions/a93fb07c-6c93-40be-bf3b-4f0deba10f4b/resourceGroups/Default-Web-EastUS/providers/microsoft.web/sites/misitiooeltuyo";
            cmdlet.Actions          = null;

            cmdlet.ExecuteCmdlet();

            this.AssertResult(
                location: "East US",
                tagsKey: "hidden-link:/subscriptions/a93fb07c-6c93-40be-bf3b-4f0deba10f4b/resourceGroups/Default-Web-EastUS/providers/microsoft.web/sites/misitiooeltuyo",
                isEnabled: true,
                actionsNull: true,
                actionsCount: 0);

            // Null actions and disabled
            cmdlet.DisableRule = true;

            cmdlet.ExecuteCmdlet();

            this.AssertResult(
                location: "East US",
                tagsKey: "hidden-link:/subscriptions/a93fb07c-6c93-40be-bf3b-4f0deba10f4b/resourceGroups/Default-Web-EastUS/providers/microsoft.web/sites/misitiooeltuyo",
                isEnabled: false,
                actionsNull: true,
                actionsCount: 0);

            // Empty actions
            cmdlet.DisableRule = false;
            cmdlet.Actions     = new List <RuleAction>();

            cmdlet.ExecuteCmdlet();

            this.AssertResult(
                location: "East US",
                tagsKey: "hidden-link:/subscriptions/a93fb07c-6c93-40be-bf3b-4f0deba10f4b/resourceGroups/Default-Web-EastUS/providers/microsoft.web/sites/misitiooeltuyo",
                isEnabled: true,
                actionsNull: false,
                actionsCount: 0);

            // Non-empty actions (one action)
            List <string> eMails = new List <string>();

            eMails.Add("*****@*****.**");
            RuleAction ruleAction = new RuleEmailAction
            {
                SendToServiceOwners = true,
                CustomEmails        = eMails
            };

            cmdlet.Actions.Add(ruleAction);

            cmdlet.ExecuteCmdlet();

            this.AssertResult(
                location: "East US",
                tagsKey: "hidden-link:/subscriptions/a93fb07c-6c93-40be-bf3b-4f0deba10f4b/resourceGroups/Default-Web-EastUS/providers/microsoft.web/sites/misitiooeltuyo",
                isEnabled: true,
                actionsNull: false,
                actionsCount: 1);

            // Non-empty actions (two actions)
            var properties = new Dictionary <string, string>();

            properties.Add("hello", "goodbye");
            ruleAction = new RuleWebhookAction
            {
                ServiceUri = "http://bueno.net",
                Properties = properties
            };

            cmdlet.Actions.Add(ruleAction);

            cmdlet.ExecuteCmdlet();

            this.AssertResult(
                location: "East US",
                tagsKey: "hidden-link:/subscriptions/a93fb07c-6c93-40be-bf3b-4f0deba10f4b/resourceGroups/Default-Web-EastUS/providers/microsoft.web/sites/misitiooeltuyo",
                isEnabled: true,
                actionsNull: false,
                actionsCount: 2);
        }