コード例 #1
0
        /// <summary>
        /// Checks for the existence of a specific Azure Sql Firewall rule, if it doesn't exist it will create it.
        /// </summary>
        /// <param name="client">The <see cref="SqlManagementClient"/> that is performing the operation.</param>
        /// <param name="serverName">The name of the server that we want to use to create the database.</param>
        /// <param name="parameters">The <see cref="FirewallRuleCreateParameters"/> set of parameters for the rule.</param>
        /// <returns>The async <see cref="Task"/> wrapper.</returns>
        public static async Task CreateFirewallRuleIfNotExistsAsync(this SqlManagementClient client, string serverName, FirewallRuleCreateParameters parameters)
        {
            Contract.Requires(client != null);
            Contract.Requires(!string.IsNullOrWhiteSpace(serverName));
            Contract.Requires(parameters != null);
            Contract.Requires(!string.IsNullOrWhiteSpace(parameters.Name));
            Contract.Requires(!string.IsNullOrWhiteSpace(parameters.StartIPAddress));
            Contract.Requires(!string.IsNullOrWhiteSpace(parameters.EndIPAddress));

            FirewallRuleGetResponse rule = null;

            FlexStreams.BuildEventsObserver.OnNext(new CheckIfExistsEvent(AzureResource.FirewallRule, parameters.Name));

            try
            {
                rule = await client.FirewallRules.GetAsync(serverName, parameters.Name);
            }
            catch (CloudException cex)
            {
                if (!cex.Error.Message.Contains($"Resource with the name '{parameters.Name}' does not exist"))
                {
                    throw;
                }
            }

            if (rule != null)
            {
                FlexStreams.BuildEventsObserver.OnNext(new FoundExistingEvent(AzureResource.FirewallRule, parameters.Name));
                return;
            }

            await client.FirewallRules.CreateAsync(serverName, parameters);

            FlexStreams.BuildEventsObserver.OnNext(new ProvisionEvent(AzureResource.FirewallRule, parameters.Name));
        }
コード例 #2
0
        static FirewallRuleGetResponse CreateOrUpdateFirewallRule(SqlManagementClient sqlMgmtClient, string resourceGroupName, string serverName, string firewallRuleName, string startIpAddress, string endIpAddress)
        {
            FirewallRuleCreateOrUpdateParameters firewallParameters = new FirewallRuleCreateOrUpdateParameters()
            {
                Properties = new FirewallRuleCreateOrUpdateProperties()
                {
                    StartIpAddress = startIpAddress,
                    EndIpAddress   = endIpAddress
                }
            };
            FirewallRuleGetResponse firewallResult = sqlMgmtClient.FirewallRules.CreateOrUpdate(resourceGroupName, serverName, firewallRuleName, firewallParameters);

            return(firewallResult);
        }
コード例 #3
0
        static string _databasePerfLevel = ""; // "S0", "S1", and so on here for other tiers


        static void Main(string[] args)
        {
            // Authenticate:
            _token = GetToken(_tenantId, _applicationId, _applicationSecret);
            Console.WriteLine("Token acquired. Expires on:" + _token.ExpiresOn);

            // Instantiate management clients:
            _resourceMgmtClient = new ResourceManagementClient(new Microsoft.Rest.TokenCredentials(_token.AccessToken));
            _sqlMgmtClient      = new SqlManagementClient(new TokenCloudCredentials(_subscriptionId, _token.AccessToken));


            Console.WriteLine("Resource group...");
            ResourceGroup rg = CreateOrUpdateResourceGroup(_resourceMgmtClient, _subscriptionId, _resourceGroupName, _resourceGrouplocation);

            Console.WriteLine("Resource group: " + rg.Id);


            Console.WriteLine("Server...");
            ServerGetResponse sgr = CreateOrUpdateServer(_sqlMgmtClient, _resourceGroupName, _serverlocation, _serverName, _serverAdmin, _serverAdminPassword);

            Console.WriteLine("Server: " + sgr.Server.Id);

            Console.WriteLine("Server firewall...");
            FirewallRuleGetResponse fwr = CreateOrUpdateFirewallRule(_sqlMgmtClient, _resourceGroupName, _serverName, _firewallRuleName, _startIpAddress, _endIpAddress);

            Console.WriteLine("Server firewall: " + fwr.FirewallRule.Id);

            Console.WriteLine("Database...");
            DatabaseCreateOrUpdateResponse dbr = CreateOrUpdateDatabase(_sqlMgmtClient, _resourceGroupName, _serverName, _databaseName, _databaseEdition, _databasePerfLevel);

            Console.WriteLine("Database: " + dbr.Database.Id);


            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
コード例 #4
0
        /// <summary>
        /// Returns the Firewall rule for an Azure SQL Database Server with a
        /// matching name.
        /// </summary>
        /// <param name='serverName'>
        /// Required. The name of the Azure SQL Database Server to query for
        /// the Firewall Rule.
        /// </param>
        /// <param name='ruleName'>
        /// Required. The name of the rule to retrieve.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Contains the response from a request to Get Firewall Rule.
        /// </returns>
        public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.Sql.Models.FirewallRuleGetResponse> GetAsync(string serverName, string ruleName, CancellationToken cancellationToken)
        {
            // Validate
            if (serverName == null)
            {
                throw new ArgumentNullException("serverName");
            }
            if (ruleName == null)
            {
                throw new ArgumentNullException("ruleName");
            }

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

            // Construct URL
            string url     = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/sqlservers/servers/" + serverName.Trim() + "/firewallrules/" + ruleName.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("x-ms-version", "2012-03-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
                    FirewallRuleGetResponse result = null;
                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    result = new FirewallRuleGetResponse();
                    XDocument responseDoc = XDocument.Parse(responseContent);

                    XElement serviceResourceElement = responseDoc.Element(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure"));
                    if (serviceResourceElement != null)
                    {
                        FirewallRule serviceResourceInstance = new FirewallRule();
                        result.FirewallRule = serviceResourceInstance;

                        XElement startIPAddressElement = serviceResourceElement.Element(XName.Get("StartIPAddress", "http://schemas.microsoft.com/windowsazure"));
                        if (startIPAddressElement != null)
                        {
                            string startIPAddressInstance = startIPAddressElement.Value;
                            serviceResourceInstance.StartIPAddress = startIPAddressInstance;
                        }

                        XElement endIPAddressElement = serviceResourceElement.Element(XName.Get("EndIPAddress", "http://schemas.microsoft.com/windowsazure"));
                        if (endIPAddressElement != null)
                        {
                            string endIPAddressInstance = endIPAddressElement.Value;
                            serviceResourceInstance.EndIPAddress = endIPAddressInstance;
                        }

                        XElement nameElement = serviceResourceElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
                        if (nameElement != null)
                        {
                            string nameInstance = nameElement.Value;
                            serviceResourceInstance.Name = nameInstance;
                        }

                        XElement typeElement = serviceResourceElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
                        if (typeElement != null)
                        {
                            string typeInstance = typeElement.Value;
                            serviceResourceInstance.Type = typeInstance;
                        }

                        XElement stateElement = serviceResourceElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
                        if (stateElement != null)
                        {
                            string stateInstance = stateElement.Value;
                            serviceResourceInstance.State = stateInstance;
                        }
                    }

                    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();
                }
            }
        }
コード例 #5
0
        /// <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();
                }
            }
        }