public async Task <FirewallRuleCreateResponse> AddFireWallRule(string subscriptionId, string serverName, string ip, string user, string path)
        {
            using (SqlManagementClient client = new SqlManagementClient(getCredentials(subscriptionId, path))) {
                var rule = new FirewallRuleCreateParameters()
                {
                    Name           = string.Format("{0}-{1}", user, DateTime.UtcNow.ToShortDateString().Replace("/", "-")),
                    StartIPAddress = ip,
                    EndIPAddress   = ip
                };

                var result = await client.FirewallRules.CreateAsync(serverName, rule);

                return(result);
            }
        }
        /// <summary>
        /// Adds a new server-level Firewall Rule for an Azure SQL Database
        /// Server.
        /// </summary>
        /// <param name='serverName'>
        /// Required. The name of the Azure SQL Database Server to which this
        /// rule will be applied.
        /// </param>
        /// <param name='parameters'>
        /// Required. The parameters for the Create Firewall Rule operation.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Contains the response to a Create Firewall Rule operation.
        /// </returns>
        public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.Sql.Models.FirewallRuleCreateResponse> CreateAsync(string serverName, FirewallRuleCreateParameters parameters, CancellationToken cancellationToken)
        {
            // Validate
            if (serverName == null)
            {
                throw new ArgumentNullException("serverName");
            }
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            if (parameters.EndIPAddress == null)
            {
                throw new ArgumentNullException("parameters.EndIPAddress");
            }
            if (parameters.Name == null)
            {
                throw new ArgumentNullException("parameters.Name");
            }
            if (parameters.StartIPAddress == null)
            {
                throw new ArgumentNullException("parameters.StartIPAddress");
            }

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

            // Construct URL
            string url     = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/sqlservers/servers/" + serverName.Trim() + "/firewallrules";
            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.Post;
                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);

                // Serialize Request
                string    requestContent = null;
                XDocument requestDoc     = new XDocument();

                XElement serviceResourceElement = new XElement(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure"));
                requestDoc.Add(serviceResourceElement);

                XElement nameElement = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
                nameElement.Value = parameters.Name;
                serviceResourceElement.Add(nameElement);

                XElement startIPAddressElement = new XElement(XName.Get("StartIPAddress", "http://schemas.microsoft.com/windowsazure"));
                startIPAddressElement.Value = parameters.StartIPAddress;
                serviceResourceElement.Add(startIPAddressElement);

                XElement endIPAddressElement = new XElement(XName.Get("EndIPAddress", "http://schemas.microsoft.com/windowsazure"));
                endIPAddressElement.Value = parameters.EndIPAddress;
                serviceResourceElement.Add(endIPAddressElement);

                requestContent      = requestDoc.ToString();
                httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
                httpRequest.Content.Headers.ContentType         = new MediaTypeHeaderValue("application/xml");
                httpRequest.Content.Headers.ContentType.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.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
                    FirewallRuleCreateResponse result = null;
                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

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

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

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

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

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

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

                        XElement stateElement = serviceResourceElement2.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();
                }
            }
        }
 /// <summary>
 /// Adds a new server-level firewall rule for a SQL Database server
 /// that belongs to a subscription.  (see
 /// http://msdn.microsoft.com/en-us/library/windowsazure/gg715280.aspx
 /// for more information)
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.WindowsAzure.Management.Sql.IFirewallRuleOperations.
 /// </param>
 /// <param name='serverName'>
 /// The name of the SQL database server to which this rule will be
 /// applied.
 /// </param>
 /// <param name='parameters'>
 /// Parameters for the Create Firewall Rule operation.
 /// </param>
 /// <returns>
 /// A standard service response including an HTTP status code and
 /// request ID.
 /// </returns>
 public static FirewallRuleCreateResponse Create(this IFirewallRuleOperations operations, string serverName, FirewallRuleCreateParameters parameters)
 {
     try
     {
         return(operations.CreateAsync(serverName, parameters).Result);
     }
     catch (AggregateException ex)
     {
         if (ex.InnerExceptions.Count > 1)
         {
             throw;
         }
         else
         {
             throw ex.InnerException;
         }
     }
 }
 /// <summary>
 /// Adds a new server-level firewall rule for a SQL Database server
 /// that belongs to a subscription.  (see
 /// http://msdn.microsoft.com/en-us/library/windowsazure/gg715280.aspx
 /// for more information)
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.WindowsAzure.Management.Sql.IFirewallRuleOperations.
 /// </param>
 /// <param name='serverName'>
 /// The name of the SQL database server to which this rule will be
 /// applied.
 /// </param>
 /// <param name='parameters'>
 /// Parameters for the Create Firewall Rule operation.
 /// </param>
 /// <returns>
 /// A standard service response including an HTTP status code and
 /// request ID.
 /// </returns>
 public static Task <FirewallRuleCreateResponse> CreateAsync(this IFirewallRuleOperations operations, string serverName, FirewallRuleCreateParameters parameters)
 {
     return(operations.CreateAsync(serverName, parameters, CancellationToken.None));
 }
        /// <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));
        }
예제 #6
0
 /// <summary>
 /// Adds a new server-level Firewall Rule for an Azure SQL Database
 /// Server.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.WindowsAzure.Management.Sql.IFirewallRuleOperations.
 /// </param>
 /// <param name='serverName'>
 /// Required. The name of the Azure SQL Database Server to which this
 /// rule will be applied.
 /// </param>
 /// <param name='parameters'>
 /// Required. The parameters for the Create Firewall Rule operation.
 /// </param>
 /// <returns>
 /// Contains the response to a Create Firewall Rule operation.
 /// </returns>
 public static FirewallRuleCreateResponse Create(this IFirewallRuleOperations operations, string serverName, FirewallRuleCreateParameters parameters)
 {
     return(Task.Factory.StartNew((object s) =>
     {
         return ((IFirewallRuleOperations)s).CreateAsync(serverName, parameters);
     }
                                  , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult());
 }