public static AutoscaleSettingData GetBasicAutoscaleSettingData(AzureLocation location)
        {
            var fixDate  = new TimeWindow("UTC", DateTime.Parse("2014-04-15T21:06:11.7882792Z"), DateTime.Parse("2014-04-15T21:06:11.7882792Z"));
            var Schedule = new RecurrentSchedule("UTC-11", new List <string> {
                "Monday"
            }, new List <int> {
                0
            }, new List <int> {
                10
            });
            var               recurrence    = new MonitorRecurrence(RecurrenceFrequency.Week, Schedule);
            ScaleCapacity     scaleCapacity = new ScaleCapacity("1", "1", "1");
            var               metricTtigger = new MetricTrigger("AbandonMessage", "microsoft.servicebus/namespaces", "/subscriptions/db1ab6f0-4769-4b27-930e-01e2ef9c123c/resourceGroups/testservicebusRG-9432/providers/Microsoft.ServiceBus/namespaces/testnamespacemgmt7892", "Eest US 2", TimeSpan.FromMinutes(1), MetricStatisticType.Average, TimeSpan.FromMinutes(10), TimeAggregationType.Average, ComparisonOperationType.GreaterThan, 70, new ChangeTrackingList <ScaleRuleMetricDimension>(), false);
            IList <ScaleRule> rules         = new List <ScaleRule>()
            {
                new ScaleRule(metricTtigger, new ScaleAction(ScaleDirection.Increase, ScaleType.ServiceAllowedNextValue, "1", TimeSpan.FromMinutes(5)))
            };
            IEnumerable <AutoscaleProfile> profiles = new List <AutoscaleProfile>()
            {
                //new AutoscaleProfile("Profiles2", scaleCapacity, rules)
                new AutoscaleProfile("Profiles2", scaleCapacity, rules, fixDate, null),
                new AutoscaleProfile("Profiles3", scaleCapacity, rules, null, recurrence),
            };
            var data = new AutoscaleSettingData(location, profiles)
            {
                Enabled = true,
                TargetResourceLocation = location,
                TargetResourceId       = "/subscriptions/db1ab6f0-4769-4b27-930e-01e2ef9c123c/resourceGroups/testservicebusRG-9432/providers/Microsoft.ServiceBus/namespaces/testnamespacemgmt7892",

                /*Notifications =
                 * {
                 *  new AutoscaleNotification()
                 *  {
                 *      Operation = "Scale",
                 *      Email = new EmailNotification()
                 *      {
                 *          SendToSubscriptionAdministrator = true,
                 *          SendToSubscriptionCoAdministrators = true,
                 *          CustomEmails =
                 *          {
                 *              "*****@*****.**",
                 *              "*****@*****.**"
                 *          }
                 *      },
                 *      Webhooks =
                 *      {
                 *          new WebhookNotification()
                 *          {
                 *              ServiceUri = "http://myservice.com",
                 *              Properties = {}
                 *          }
                 *      }
                 *  },
                 * },*/
                Tags = {},
            };

            return(data);
        }
 private static void AreEqual(MetricTrigger exp, MetricTrigger act)
 {
     if (exp != null)
     {
         Assert.Equal(exp.MetricName, act.MetricName);
         Assert.Equal(exp.MetricResourceUri, act.MetricResourceUri);
         Assert.Equal(exp.Statistic, act.Statistic);
         Assert.Equal(exp.Threshold, act.Threshold);
         Assert.Equal(exp.TimeAggregation, act.TimeAggregation);
         Assert.Equal(exp.TimeGrain, act.TimeGrain);
         Assert.Equal(exp.TimeWindow, act.TimeWindow);
     }
 }
        /// <summary>
        /// A string representation of the MetricTrigger including indentation
        /// </summary>
        /// <param name="metricTrigger">The metricTrigger object</param>
        /// <param name="indentationTabs">The number of tabs to insert in front of each member</param>
        /// <returns>A string representation of the MetricTrigger including indentation</returns>
        public static string ToString(this MetricTrigger metricTrigger, int indentationTabs)
        {
            StringBuilder output = new StringBuilder();

            if (metricTrigger != null)
            {
                output.AppendLine();
                output.AddSpacesInFront(indentationTabs).AppendLine("MetricName        : " + metricTrigger.MetricName);
                output.AddSpacesInFront(indentationTabs).AppendLine("MetricResourceUri : " + metricTrigger.MetricResourceUri);
                output.AddSpacesInFront(indentationTabs).AppendLine("Operator          : " + metricTrigger.Operator);
                output.AddSpacesInFront(indentationTabs).AppendLine("Statistic         : " + metricTrigger.Statistic);
                output.AddSpacesInFront(indentationTabs).AppendLine("Threshold         : " + metricTrigger.Threshold);
                output.AddSpacesInFront(indentationTabs).AppendLine("TimeAggregation   : " + metricTrigger.TimeAggregation);
                output.AddSpacesInFront(indentationTabs).AppendLine("TimeGrain         : " + metricTrigger.TimeGrain);
                output.AddSpacesInFront(indentationTabs).Append("TimeWindow        : " + metricTrigger.TimeWindow);
            }

            return(output.ToString());
        }
Beispiel #4
0
        static public MetricTrigger ConvertNamespace(Management.Monitor.Management.Models.MetricTrigger metricTrigger)
        {
            if (metricTrigger == null)
            {
                return(null);
            }

            MetricTrigger trigger = new MetricTrigger(
                metricName: metricTrigger.MetricName,
                metricResourceUri: metricTrigger.MetricResourceUri,
                timeGrain: metricTrigger.TimeGrain,
                statistic: ConvertNamespace(metricTrigger.Statistic),
                timeWindow: metricTrigger.TimeWindow,
                timeAggregation: ConvertNamespace(metricTrigger.TimeAggregation),
                operatorProperty: ConvertNamespace(metricTrigger.OperatorProperty),
                threshold: metricTrigger.Threshold);

            return(trigger);
        }
Beispiel #5
0
        /// <summary>
        /// Create an Autoscale setting rule based on the properties of the object
        /// </summary>
        /// <returns>A ScaleRule created based on the properties of the object</returns>
        public ScaleRule CreateSettingRule()
        {
            if (this.TimeWindow != default(TimeSpan) && this.TimeWindow < MinimumTimeWindow)
            {
                throw new ArgumentOutOfRangeException("TimeWindow", this.TimeWindow, ResourcesForAutoscaleCmdlets.MinimumTimeWindow5min);
            }

            if (this.TimeGrain < MinimumTimeGrain)
            {
                throw new ArgumentOutOfRangeException("TimeGrain", this.TimeGrain, ResourcesForAutoscaleCmdlets.MinimumTimeGrain1min);
            }

            MetricTrigger trigger = new MetricTrigger()
            {
                MetricName        = this.MetricName,
                MetricResourceUri = this.MetricResourceId,
                OperatorProperty  = this.Operator,
                Statistic         = this.MetricStatistic,
                Threshold         = this.Threshold,
                TimeAggregation   = this.TimeAggregationOperator,
                TimeGrain         = this.TimeGrain,
                TimeWindow        = this.TimeWindow == default(TimeSpan) ? MinimumTimeWindow : this.TimeWindow,
            };

            // Notice ChangeCount is (ScaleType)0, so this is the default in this version. It was the only value in the previous version.
            ScaleAction action = new ScaleAction()
            {
                Cooldown  = this.ScaleActionCooldown,
                Direction = this.ScaleActionDirection,
                Value     = this.ScaleActionValue,
                Type      = this.ScaleActionScaleType
            };

            return(new ScaleRule()
            {
                MetricTrigger = trigger,
                ScaleAction = action,
            });
        }
Beispiel #6
0
        /// <param name='resourceId'>
        /// Required. The resource ID.
        /// </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 <Microsoft.WindowsAzure.Management.Monitoring.Autoscale.Models.AutoscaleSettingGetResponse> GetAsync(string resourceId, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceId == null)
            {
                throw new ArgumentNullException("resourceId");
            }

            // 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("resourceId", resourceId);
                Tracing.Enter(invocationId, this, "GetAsync", tracingParameters);
            }

            // Construct URL
            string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/monitoring/autoscalesettings?";

            url = url + "resourceId=" + Uri.EscapeDataString(resourceId.Trim());
            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.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));
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

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

                    result = new AutoscaleSettingGetResponse();
                    JToken responseDoc = null;
                    if (string.IsNullOrEmpty(responseContent) == false)
                    {
                        responseDoc = JToken.Parse(responseContent);
                    }

                    if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                    {
                        AutoscaleSetting settingInstance = new AutoscaleSetting();
                        result.Setting = settingInstance;

                        JToken profilesArray = responseDoc["Profiles"];
                        if (profilesArray != null && profilesArray.Type != JTokenType.Null)
                        {
                            foreach (JToken profilesValue in ((JArray)profilesArray))
                            {
                                AutoscaleProfile autoscaleProfileInstance = new AutoscaleProfile();
                                settingInstance.Profiles.Add(autoscaleProfileInstance);

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

                                JToken capacityValue = profilesValue["Capacity"];
                                if (capacityValue != null && capacityValue.Type != JTokenType.Null)
                                {
                                    ScaleCapacity capacityInstance = new ScaleCapacity();
                                    autoscaleProfileInstance.Capacity = capacityInstance;

                                    JToken minimumValue = capacityValue["Minimum"];
                                    if (minimumValue != null && minimumValue.Type != JTokenType.Null)
                                    {
                                        string minimumInstance = ((string)minimumValue);
                                        capacityInstance.Minimum = minimumInstance;
                                    }

                                    JToken maximumValue = capacityValue["Maximum"];
                                    if (maximumValue != null && maximumValue.Type != JTokenType.Null)
                                    {
                                        string maximumInstance = ((string)maximumValue);
                                        capacityInstance.Maximum = maximumInstance;
                                    }

                                    JToken defaultValue = capacityValue["Default"];
                                    if (defaultValue != null && defaultValue.Type != JTokenType.Null)
                                    {
                                        string defaultInstance = ((string)defaultValue);
                                        capacityInstance.Default = defaultInstance;
                                    }
                                }

                                JToken rulesArray = profilesValue["Rules"];
                                if (rulesArray != null && rulesArray.Type != JTokenType.Null)
                                {
                                    foreach (JToken rulesValue in ((JArray)rulesArray))
                                    {
                                        ScaleRule scaleRuleInstance = new ScaleRule();
                                        autoscaleProfileInstance.Rules.Add(scaleRuleInstance);

                                        JToken metricTriggerValue = rulesValue["MetricTrigger"];
                                        if (metricTriggerValue != null && metricTriggerValue.Type != JTokenType.Null)
                                        {
                                            MetricTrigger metricTriggerInstance = new MetricTrigger();
                                            scaleRuleInstance.MetricTrigger = metricTriggerInstance;

                                            JToken metricNameValue = metricTriggerValue["MetricName"];
                                            if (metricNameValue != null && metricNameValue.Type != JTokenType.Null)
                                            {
                                                string metricNameInstance = ((string)metricNameValue);
                                                metricTriggerInstance.MetricName = metricNameInstance;
                                            }

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

                                            JToken metricSourceValue = metricTriggerValue["MetricSource"];
                                            if (metricSourceValue != null && metricSourceValue.Type != JTokenType.Null)
                                            {
                                                string metricSourceInstance = ((string)metricSourceValue);
                                                metricTriggerInstance.MetricSource = metricSourceInstance;
                                            }

                                            JToken timeGrainValue = metricTriggerValue["TimeGrain"];
                                            if (timeGrainValue != null && timeGrainValue.Type != JTokenType.Null)
                                            {
                                                TimeSpan timeGrainInstance = TypeConversion.From8601TimeSpan(((string)timeGrainValue));
                                                metricTriggerInstance.TimeGrain = timeGrainInstance;
                                            }

                                            JToken statisticValue = metricTriggerValue["Statistic"];
                                            if (statisticValue != null && statisticValue.Type != JTokenType.Null)
                                            {
                                                MetricStatisticType statisticInstance = ((MetricStatisticType)Enum.Parse(typeof(MetricStatisticType), ((string)statisticValue), true));
                                                metricTriggerInstance.Statistic = statisticInstance;
                                            }

                                            JToken timeWindowValue = metricTriggerValue["TimeWindow"];
                                            if (timeWindowValue != null && timeWindowValue.Type != JTokenType.Null)
                                            {
                                                TimeSpan timeWindowInstance = TypeConversion.From8601TimeSpan(((string)timeWindowValue));
                                                metricTriggerInstance.TimeWindow = timeWindowInstance;
                                            }

                                            JToken timeAggregationValue = metricTriggerValue["TimeAggregation"];
                                            if (timeAggregationValue != null && timeAggregationValue.Type != JTokenType.Null)
                                            {
                                                TimeAggregationType timeAggregationInstance = ((TimeAggregationType)Enum.Parse(typeof(TimeAggregationType), ((string)timeAggregationValue), true));
                                                metricTriggerInstance.TimeAggregation = timeAggregationInstance;
                                            }

                                            JToken operatorValue = metricTriggerValue["Operator"];
                                            if (operatorValue != null && operatorValue.Type != JTokenType.Null)
                                            {
                                                ComparisonOperationType operatorInstance = ((ComparisonOperationType)Enum.Parse(typeof(ComparisonOperationType), ((string)operatorValue), true));
                                                metricTriggerInstance.Operator = operatorInstance;
                                            }

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

                                        JToken scaleActionValue = rulesValue["ScaleAction"];
                                        if (scaleActionValue != null && scaleActionValue.Type != JTokenType.Null)
                                        {
                                            ScaleAction scaleActionInstance = new ScaleAction();
                                            scaleRuleInstance.ScaleAction = scaleActionInstance;

                                            JToken directionValue = scaleActionValue["Direction"];
                                            if (directionValue != null && directionValue.Type != JTokenType.Null)
                                            {
                                                ScaleDirection directionInstance = ((ScaleDirection)Enum.Parse(typeof(ScaleDirection), ((string)directionValue), true));
                                                scaleActionInstance.Direction = directionInstance;
                                            }

                                            JToken typeValue = scaleActionValue["Type"];
                                            if (typeValue != null && typeValue.Type != JTokenType.Null)
                                            {
                                                ScaleType typeInstance = ((ScaleType)Enum.Parse(typeof(ScaleType), ((string)typeValue), true));
                                                scaleActionInstance.Type = typeInstance;
                                            }

                                            JToken valueValue = scaleActionValue["Value"];
                                            if (valueValue != null && valueValue.Type != JTokenType.Null)
                                            {
                                                string valueInstance = ((string)valueValue);
                                                scaleActionInstance.Value = valueInstance;
                                            }

                                            JToken cooldownValue = scaleActionValue["Cooldown"];
                                            if (cooldownValue != null && cooldownValue.Type != JTokenType.Null)
                                            {
                                                TimeSpan cooldownInstance = TypeConversion.From8601TimeSpan(((string)cooldownValue));
                                                scaleActionInstance.Cooldown = cooldownInstance;
                                            }
                                        }
                                    }
                                }

                                JToken fixedDateValue = profilesValue["FixedDate"];
                                if (fixedDateValue != null && fixedDateValue.Type != JTokenType.Null)
                                {
                                    TimeWindow fixedDateInstance = new TimeWindow();
                                    autoscaleProfileInstance.FixedDate = fixedDateInstance;

                                    JToken timeZoneValue = fixedDateValue["TimeZone"];
                                    if (timeZoneValue != null && timeZoneValue.Type != JTokenType.Null)
                                    {
                                        string timeZoneInstance = ((string)timeZoneValue);
                                        fixedDateInstance.TimeZone = timeZoneInstance;
                                    }

                                    JToken startValue = fixedDateValue["Start"];
                                    if (startValue != null && startValue.Type != JTokenType.Null)
                                    {
                                        DateTime startInstance = ((DateTime)startValue);
                                        fixedDateInstance.Start = startInstance;
                                    }

                                    JToken endValue = fixedDateValue["End"];
                                    if (endValue != null && endValue.Type != JTokenType.Null)
                                    {
                                        DateTime endInstance = ((DateTime)endValue);
                                        fixedDateInstance.End = endInstance;
                                    }
                                }

                                JToken recurrenceValue = profilesValue["Recurrence"];
                                if (recurrenceValue != null && recurrenceValue.Type != JTokenType.Null)
                                {
                                    Recurrence recurrenceInstance = new Recurrence();
                                    autoscaleProfileInstance.Recurrence = recurrenceInstance;

                                    JToken frequencyValue = recurrenceValue["Frequency"];
                                    if (frequencyValue != null && frequencyValue.Type != JTokenType.Null)
                                    {
                                        RecurrenceFrequency frequencyInstance = ((RecurrenceFrequency)Enum.Parse(typeof(RecurrenceFrequency), ((string)frequencyValue), true));
                                        recurrenceInstance.Frequency = frequencyInstance;
                                    }

                                    JToken scheduleValue = recurrenceValue["Schedule"];
                                    if (scheduleValue != null && scheduleValue.Type != JTokenType.Null)
                                    {
                                        RecurrentSchedule scheduleInstance = new RecurrentSchedule();
                                        recurrenceInstance.Schedule = scheduleInstance;

                                        JToken timeZoneValue2 = scheduleValue["TimeZone"];
                                        if (timeZoneValue2 != null && timeZoneValue2.Type != JTokenType.Null)
                                        {
                                            string timeZoneInstance2 = ((string)timeZoneValue2);
                                            scheduleInstance.TimeZone = timeZoneInstance2;
                                        }

                                        JToken daysArray = scheduleValue["Days"];
                                        if (daysArray != null && daysArray.Type != JTokenType.Null)
                                        {
                                            foreach (JToken daysValue in ((JArray)daysArray))
                                            {
                                                scheduleInstance.Days.Add(((string)daysValue));
                                            }
                                        }

                                        JToken hoursArray = scheduleValue["Hours"];
                                        if (hoursArray != null && hoursArray.Type != JTokenType.Null)
                                        {
                                            foreach (JToken hoursValue in ((JArray)hoursArray))
                                            {
                                                scheduleInstance.Hours.Add(((int)hoursValue));
                                            }
                                        }

                                        JToken minutesArray = scheduleValue["Minutes"];
                                        if (minutesArray != null && minutesArray.Type != JTokenType.Null)
                                        {
                                            foreach (JToken minutesValue in ((JArray)minutesArray))
                                            {
                                                scheduleInstance.Minutes.Add(((int)minutesValue));
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        JToken enabledValue = responseDoc["Enabled"];
                        if (enabledValue != null && enabledValue.Type != JTokenType.Null)
                        {
                            bool enabledInstance = ((bool)enabledValue);
                            settingInstance.Enabled = enabledInstance;
                        }
                    }

                    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();
                }
            }
        }