/// <summary>
        /// Creates or updates an Azure SQL Database Server Firewall rule.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. The name of the Resource Group to which the server
        /// belongs.
        /// </param>
        /// <param name='serverName'>
        /// Required. The name of the Azure SQL Database Server on which the
        /// database is hosted.
        /// </param>
        /// <param name='firewallRule'>
        /// Required. The name of the Azure SQL Database Server Firewall Rule.
        /// </param>
        /// <param name='parameters'>
        /// Required. The required parameters for createing or updating a
        /// firewall rule.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Represents the response to a List Firewall Rules request.
        /// </returns>
        public async Task <FirewallRuleGetResponse> CreateOrUpdateAsync(string resourceGroupName, string serverName, string firewallRule, FirewallRuleCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }
            if (serverName == null)
            {
                throw new ArgumentNullException("serverName");
            }
            if (firewallRule == null)
            {
                throw new ArgumentNullException("firewallRule");
            }
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            if (parameters.Properties == null)
            {
                throw new ArgumentNullException("parameters.Properties");
            }

            // 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("resourceGroupName", resourceGroupName);
                tracingParameters.Add("serverName", serverName);
                tracingParameters.Add("firewallRule", firewallRule);
                tracingParameters.Add("parameters", parameters);
                Tracing.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
            }

            // Construct URL
            string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/resourceGroups/" + resourceGroupName.Trim() + "/providers/Microsoft.Sql/servers/" + serverName.Trim() + "/firewallRules/" + firewallRule.Trim() + "?";

            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

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

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

                JObject firewallRuleCreateOrUpdateParametersValue = new JObject();
                requestDoc = firewallRuleCreateOrUpdateParametersValue;

                JObject propertiesValue = new JObject();
                firewallRuleCreateOrUpdateParametersValue["properties"] = propertiesValue;

                if (parameters.Properties.StartIpAddress != null)
                {
                    propertiesValue["startIpAddress"] = parameters.Properties.StartIpAddress;
                }

                if (parameters.Properties.EndIpAddress != null)
                {
                    propertiesValue["endIpAddress"] = parameters.Properties.EndIpAddress;
                }

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

                // 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));
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

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

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

                    if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                    {
                        FirewallRule firewallRuleInstance = new FirewallRule();
                        result.FirewallRule = firewallRuleInstance;

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

                        JToken propertiesValue2 = responseDoc["properties"];
                        if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
                        {
                            FirewallRuleProperties propertiesInstance = new FirewallRuleProperties();
                            firewallRuleInstance.Properties = propertiesInstance;

                            JToken startIpAddressValue = propertiesValue2["startIpAddress"];
                            if (startIpAddressValue != null && startIpAddressValue.Type != JTokenType.Null)
                            {
                                string startIpAddressInstance = ((string)startIpAddressValue);
                                propertiesInstance.StartIpAddress = startIpAddressInstance;
                            }

                            JToken endIpAddressValue = propertiesValue2["endIpAddress"];
                            if (endIpAddressValue != null && endIpAddressValue.Type != JTokenType.Null)
                            {
                                string endIpAddressInstance = ((string)endIpAddressValue);
                                propertiesInstance.EndIpAddress = endIpAddressInstance;
                            }
                        }

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

                        JToken typeValue = responseDoc["type"];
                        if (typeValue != null && typeValue.Type != JTokenType.Null)
                        {
                            string typeInstance = ((string)typeValue);
                            firewallRuleInstance.Type = typeInstance;
                        }

                        JToken locationValue = responseDoc["location"];
                        if (locationValue != null && locationValue.Type != JTokenType.Null)
                        {
                            string locationInstance = ((string)locationValue);
                            firewallRuleInstance.Location = locationInstance;
                        }

                        JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
                        if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
                        {
                            firewallRuleInstance.Tags = new Dictionary <string, string>();
                            foreach (JProperty property in tagsSequenceElement)
                            {
                                string tagsKey   = ((string)property.Name);
                                string tagsValue = ((string)property.Value);
                                firewallRuleInstance.Tags.Add(tagsKey, tagsValue);
                            }
                        }
                    }

                    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();
                }
            }
        }
Exemple #2
0
        /// <summary>
        /// Returns a list of Azure SQL Database Server Firewall rules.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. The name of the Resource Group to which the server
        /// belongs.
        /// </param>
        /// <param name='serverName'>
        /// Required. The name of the Azure SQL Database Server on which the
        /// database is hosted.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Represents the response to a List Firewall Rules request.
        /// </returns>
        public async Task <FirewallRuleListResponse> ListAsync(string resourceGroupName, string serverName, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }
            if (serverName == null)
            {
                throw new ArgumentNullException("serverName");
            }

            // Tracing
            bool   shouldTrace  = TracingAdapter.IsEnabled;
            string invocationId = null;

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

            // Construct URL
            string url = "";

            url = url + "/subscriptions/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/resourceGroups/";
            url = url + Uri.EscapeDataString(resourceGroupName);
            url = url + "/providers/";
            url = url + "Microsoft.Sql";
            url = url + "/servers/";
            url = url + Uri.EscapeDataString(serverName);
            url = url + "/firewallRules";
            List <string> queryParameters = new List <string>();

            queryParameters.Add("api-version=2014-04-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.Get;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers

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

                // 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)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    FirewallRuleListResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                        result = new FirewallRuleListResponse();
                        JToken responseDoc = null;
                        if (string.IsNullOrEmpty(responseContent) == false)
                        {
                            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))
                                {
                                    FirewallRule firewallRuleInstance = new FirewallRule();
                                    result.FirewallRules.Add(firewallRuleInstance);

                                    JToken propertiesValue = valueValue["properties"];
                                    if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
                                    {
                                        FirewallRuleProperties propertiesInstance = new FirewallRuleProperties();
                                        firewallRuleInstance.Properties = propertiesInstance;

                                        JToken startIpAddressValue = propertiesValue["startIpAddress"];
                                        if (startIpAddressValue != null && startIpAddressValue.Type != JTokenType.Null)
                                        {
                                            string startIpAddressInstance = ((string)startIpAddressValue);
                                            propertiesInstance.StartIpAddress = startIpAddressInstance;
                                        }

                                        JToken endIpAddressValue = propertiesValue["endIpAddress"];
                                        if (endIpAddressValue != null && endIpAddressValue.Type != JTokenType.Null)
                                        {
                                            string endIpAddressInstance = ((string)endIpAddressValue);
                                            propertiesInstance.EndIpAddress = endIpAddressInstance;
                                        }
                                    }

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

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

                                    JToken typeValue = valueValue["type"];
                                    if (typeValue != null && typeValue.Type != JTokenType.Null)
                                    {
                                        string typeInstance = ((string)typeValue);
                                        firewallRuleInstance.Type = typeInstance;
                                    }

                                    JToken locationValue = valueValue["location"];
                                    if (locationValue != null && locationValue.Type != JTokenType.Null)
                                    {
                                        string locationInstance = ((string)locationValue);
                                        firewallRuleInstance.Location = locationInstance;
                                    }

                                    JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
                                    if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
                                    {
                                        foreach (JProperty property in tagsSequenceElement)
                                        {
                                            string tagsKey   = ((string)property.Name);
                                            string tagsValue = ((string)property.Value);
                                            firewallRuleInstance.Tags.Add(tagsKey, tagsValue);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    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();
                }
            }
        }