/// <summary>
        /// Creates a new server in the current subscription.
        /// </summary>
        /// <param name="adminLogin">
        /// The administrator login name for the new server.
        /// </param>
        /// <param name="adminLoginPassword">
        /// The administrator login password for the new server.
        /// </param>
        /// <param name="location">
        /// The location in which to create the new server.
        /// </param>
        /// <returns>The context to the newly created server.</returns>
        internal SqlDatabaseServerContext NewAzureSqlDatabaseServerProcess(
            string adminLogin,
            string adminLoginPassword,
            string location,
            float?version)
        {
            // Do nothing if force is not specified and user cancelled the operation
            if (!Force.IsPresent &&
                !ShouldProcess(
                    Resources.NewAzureSqlDatabaseServerDescription,
                    Resources.NewAzureSqlDatabaseServerWarning,
                    Resources.ShouldProcessCaption))
            {
                return(null);
            }

            // Get the SQL management client for the current subscription
            SqlManagementClient sqlManagementClient = GetCurrentSqlClient();

            // Set the retry policty to not retry attempts.
            sqlManagementClient.SetRetryPolicy(new RetryPolicy(new DefaultHttpErrorDetectionStrategy(), 0));

            // Issue the create server request
            ServerCreateResponse response = sqlManagementClient.Servers.Create(
                new ServerCreateParameters()
            {
                Location = location,
                AdministratorUserName = adminLogin,
                AdministratorPassword = adminLoginPassword,
                Version = version.HasValue ? version.Value.ToString("F1", CultureInfo.InvariantCulture) : null
            });

            var newServer = sqlManagementClient.Servers.List().Servers.Where(s => s.Name == response.ServerName).FirstOrDefault();

            if (newServer == null)
            {
                throw new ItemNotFoundException(string.Format(
                                                    CultureInfo.InvariantCulture,
                                                    Resources.CreateServerServerNotFound,
                                                    response.ServerName));
            }

            SqlDatabaseServerContext operationContext = new SqlDatabaseServerContext()
            {
                OperationStatus      = Services.Constants.OperationSuccess,
                OperationDescription = CommandRuntime.ToString(),
                OperationId          = response.RequestId,
                ServerName           = newServer.Name,
                Location             = location,
                AdministratorLogin   = adminLogin,
                State   = newServer.State,
                Version = newServer.Version
            };

            return(operationContext);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Creates a new server in the current subscription.
        /// </summary>
        /// <param name="adminLogin">
        /// The administrator login name for the new server.
        /// </param>
        /// <param name="adminLoginPassword">
        /// The administrator login password for the new server.
        /// </param>
        /// <param name="location">
        /// The location in which to create the new server.
        /// </param>
        /// <returns>The context to the newly created server.</returns>
        internal SqlDatabaseServerContext NewAzureSqlDatabaseServerProcess(
            string adminLogin,
            string adminLoginPassword,
            string location,
            float?version)
        {
            // Do nothing if force is not specified and user cancelled the operation
            if (!Force.IsPresent &&
                !ShouldProcess(
                    Resources.NewAzureSqlDatabaseServerDescription,
                    Resources.NewAzureSqlDatabaseServerWarning,
                    Resources.ShouldProcessCaption))
            {
                return(null);
            }

            // Get the SQL management client for the current subscription
            SqlManagementClient sqlManagementClient = GetCurrentSqlClient();

            // Set the retry policty to not retry attempts.
            CloudExtensions.SetRetryPolicy <SqlManagementClient>(
                sqlManagementClient,
                new WindowsAzure.Common.TransientFaultHandling.RetryPolicy(new WindowsAzure.Common.TransientFaultHandling.DefaultHttpErrorDetectionStrategy(), 0));

            // Issue the create server request
            ServerCreateResponse response = sqlManagementClient.Servers.Create(
                new ServerCreateParameters()
            {
                Location = location,
                AdministratorUserName = adminLogin,
                AdministratorPassword = adminLoginPassword,
                Version = version.HasValue ? version.Value.ToString("F1") : null
            });

            SqlDatabaseServerContext operationContext = new SqlDatabaseServerContext()
            {
                OperationStatus      = Services.Constants.OperationSuccess,
                OperationDescription = CommandRuntime.ToString(),
                OperationId          = response.RequestId,
                ServerName           = response.ServerName,
                Location             = location,
                AdministratorLogin   = adminLogin,
            };

            return(operationContext);
        }
        /// <summary>
        /// Creates a new server in the current subscription.
        /// </summary>
        /// <param name="adminLogin">
        /// The administrator login name for the new server.
        /// </param>
        /// <param name="adminLoginPassword">
        /// The administrator login password for the new server.
        /// </param>
        /// <param name="location">
        /// The location in which to create the new server.
        /// </param>
        /// <returns>The context to the newly created server.</returns>
        internal SqlDatabaseServerContext NewAzureSqlDatabaseServerProcess(
            string adminLogin,
            string adminLoginPassword,
            string location)
        {
            // Do nothing if force is not specified and user cancelled the operation
            if (!Force.IsPresent &&
                !ShouldProcess(
                    Resources.NewAzureSqlDatabaseServerDescription,
                    Resources.NewAzureSqlDatabaseServerWarning,
                    Resources.ShouldProcessCaption))
            {
                return(null);
            }

            // Get the SQL management client for the current subscription
            SqlManagementClient sqlManagementClient = SqlDatabaseCmdletBase.GetCurrentSqlClient();

            // Issue the create server request
            ServerCreateResponse response = sqlManagementClient.Servers.Create(
                new ServerCreateParameters()
            {
                Location = location,
                AdministratorUserName = adminLogin,
                AdministratorPassword = adminLoginPassword
            });

            SqlDatabaseServerContext operationContext = new SqlDatabaseServerContext()
            {
                OperationStatus      = Services.Constants.OperationSuccess,
                OperationDescription = CommandRuntime.ToString(),
                OperationId          = response.RequestId,
                ServerName           = response.ServerName,
                Location             = location,
                AdministratorLogin   = adminLogin,
            };

            return(operationContext);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Provisions a new SQL Database server in a subscription.
        /// </summary>
        /// <param name='parameters'>
        /// Required. The parameters needed to provision a server.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response returned from the Create Server operation.  This
        /// contains all the information returned from the service when a
        /// server is created.
        /// </returns>
        public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.Sql.Models.ServerCreateResponse> CreateAsync(ServerCreateParameters parameters, CancellationToken cancellationToken)
        {
            // Validate
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            if (parameters.AdministratorPassword == null)
            {
                throw new ArgumentNullException("parameters.AdministratorPassword");
            }
            if (parameters.AdministratorUserName == null)
            {
                throw new ArgumentNullException("parameters.AdministratorUserName");
            }
            if (parameters.Location == null)
            {
                throw new ArgumentNullException("parameters.Location");
            }

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

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

            // Construct URL
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            string url     = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/sqlservers/servers";

            // 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;

            // 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 serverElement = new XElement(XName.Get("Server", "http://schemas.microsoft.com/sqlazure/2010/12/"));
                requestDoc.Add(serverElement);

                XElement administratorLoginElement = new XElement(XName.Get("AdministratorLogin", "http://schemas.microsoft.com/sqlazure/2010/12/"));
                administratorLoginElement.Value = parameters.AdministratorUserName;
                serverElement.Add(administratorLoginElement);

                XElement administratorLoginPasswordElement = new XElement(XName.Get("AdministratorLoginPassword", "http://schemas.microsoft.com/sqlazure/2010/12/"));
                administratorLoginPasswordElement.Value = parameters.AdministratorPassword;
                serverElement.Add(administratorLoginPasswordElement);

                XElement locationElement = new XElement(XName.Get("Location", "http://schemas.microsoft.com/sqlazure/2010/12/"));
                locationElement.Value = parameters.Location;
                serverElement.Add(locationElement);

                if (parameters.Version != null)
                {
                    XElement versionElement = new XElement(XName.Get("Version", "http://schemas.microsoft.com/sqlazure/2010/12/"));
                    versionElement.Value = parameters.Version;
                    serverElement.Add(versionElement);
                }

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

                // 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
                    ServerCreateResponse result = null;
                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

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

                    XElement serverNameElement = responseDoc.Element(XName.Get("ServerName", "http://schemas.microsoft.com/sqlazure/2010/12/"));
                    if (serverNameElement != null)
                    {
                        XAttribute fullyQualifiedDomainNameAttribute = serverNameElement.Attribute(XName.Get("FullyQualifiedDomainName", "http://schemas.microsoft.com/sqlazure/2010/12/"));
                        if (fullyQualifiedDomainNameAttribute != null)
                        {
                            result.FullyQualifiedDomainName = fullyQualifiedDomainNameAttribute.Value;
                        }

                        result.ServerName = serverNameElement.Value;
                    }

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