Exemple #1
0
        /// <summary>
        /// Performs the call to import database using the server data service context channel.
        /// </summary>
        /// <param name="serverName">The name of the server to connect to.</param>
        /// <param name="blobUri">The storage blob Uri to import from.</param>
        /// <param name="storageAccessKey">The access key for the given storage blob.</param>
        /// <param name="fullyQualifiedServerName">The fully qualified server name.</param>
        /// <param name="databaseName">The name of the database for import.</param>
        /// <param name="edition">The edition of the database for import.</param>
        /// <param name="maxDatabaseSizeInGB">The database size for import.</param>
        /// <param name="sqlCredentials">The credentials used to connect to the database.</param>
        /// <returns>The result of the import request.  Upon success the <see cref="ImportExportRequest"/>
        /// for the request</returns>
        internal ImportExportRequest ImportSqlAzureDatabaseProcess(
            string serverName,
            Uri blobUri,
            string storageAccessKey,
            string fullyQualifiedServerName,
            string databaseName,
            string edition,
            int maxDatabaseSizeInGB,
            SqlAuthenticationCredentials sqlCredentials)
        {
            this.WriteVerbose("BlobUri: " + blobUri);
            this.WriteVerbose("ServerName: " + fullyQualifiedServerName);
            this.WriteVerbose("DatabaseName: " + databaseName);
            this.WriteVerbose("Edition: " + edition);
            this.WriteVerbose("MaxDatabaseSizeInGB: " + maxDatabaseSizeInGB);
            this.WriteVerbose("UserName: " + sqlCredentials.UserName);

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

            // Start the database export operation
            DacImportExportResponse response = sqlManagementClient.Dac.Import(
                serverName,
                new DacImportParameters()
            {
                BlobCredentials = new DacImportParameters.BlobCredentialsParameter()
                {
                    Uri = blobUri,
                    StorageAccessKey = storageAccessKey,
                },
                ConnectionInfo = new DacImportParameters.ConnectionInfoParameter()
                {
                    ServerName   = fullyQualifiedServerName,
                    DatabaseName = databaseName,
                    UserName     = sqlCredentials.UserName,
                    Password     = sqlCredentials.Password,
                },
                AzureEdition     = edition,
                DatabaseSizeInGB = maxDatabaseSizeInGB
            });

            ImportExportRequest result = new ImportExportRequest()
            {
                OperationStatus      = Services.Constants.OperationSuccess,
                OperationDescription = CommandRuntime.ToString(),
                OperationId          = response.RequestId,
                RequestGuid          = response.Guid,
                ServerName           = serverName,
                SqlCredentials       = sqlCredentials,
            };

            return(result);
        }
        /// <summary>
        /// Export DAC into Windows Azure blob storage.
        /// </summary>
        /// <param name='serverName'>
        /// The name of the server being exported from.
        /// </param>
        /// <param name='parameters'>
        /// Export parameters.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Response for an DAC Import/Export request.
        /// </returns>
        public async Task <DacImportExportResponse> ExportAsync(string serverName, DacExportParameters parameters, CancellationToken cancellationToken)
        {
            // Validate
            if (serverName == null)
            {
                throw new ArgumentNullException("serverName");
            }
            if (parameters != null)
            {
                if (parameters.BlobCredentials != null)
                {
                    if (parameters.BlobCredentials.StorageAccessKey == null)
                    {
                        throw new ArgumentNullException("parameters.BlobCredentials.StorageAccessKey");
                    }
                    if (parameters.BlobCredentials.Uri == null)
                    {
                        throw new ArgumentNullException("parameters.BlobCredentials.Uri");
                    }
                }
                if (parameters.ConnectionInfo != null)
                {
                    if (parameters.ConnectionInfo.DatabaseName == null)
                    {
                        throw new ArgumentNullException("parameters.ConnectionInfo.DatabaseName");
                    }
                    if (parameters.ConnectionInfo.Password == null)
                    {
                        throw new ArgumentNullException("parameters.ConnectionInfo.Password");
                    }
                    if (parameters.ConnectionInfo.ServerName == null)
                    {
                        throw new ArgumentNullException("parameters.ConnectionInfo.ServerName");
                    }
                    if (parameters.ConnectionInfo.UserName == null)
                    {
                        throw new ArgumentNullException("parameters.ConnectionInfo.UserName");
                    }
                }
            }

            // 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, "ExportAsync", tracingParameters);
            }

            // Construct URL
            string url = new Uri(this.Client.BaseUri, "/").ToString() + this.Client.Credentials.SubscriptionId + "/services/sqlservers/servers/" + serverName + "/DacOperations/Export";

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

                if (parameters != null)
                {
                    XElement exportInputElement = new XElement(XName.Get("ExportInput", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
                    requestDoc.Add(exportInputElement);

                    if (parameters.BlobCredentials != null)
                    {
                        XElement blobCredentialsElement = new XElement(XName.Get("BlobCredentials", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
                        exportInputElement.Add(blobCredentialsElement);

                        XAttribute typeAttribute = new XAttribute(XName.Get("type", "http://www.w3.org/2001/XMLSchema-instance"), "");
                        typeAttribute.Value = "BlobStorageAccessKeyCredentials";
                        blobCredentialsElement.Add(typeAttribute);

                        XElement uriElement = new XElement(XName.Get("Uri", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
                        uriElement.Value = parameters.BlobCredentials.Uri.ToString();
                        blobCredentialsElement.Add(uriElement);

                        XElement storageAccessKeyElement = new XElement(XName.Get("StorageAccessKey", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
                        storageAccessKeyElement.Value = parameters.BlobCredentials.StorageAccessKey;
                        blobCredentialsElement.Add(storageAccessKeyElement);
                    }

                    if (parameters.ConnectionInfo != null)
                    {
                        XElement connectionInfoElement = new XElement(XName.Get("ConnectionInfo", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
                        exportInputElement.Add(connectionInfoElement);

                        XElement databaseNameElement = new XElement(XName.Get("DatabaseName", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
                        databaseNameElement.Value = parameters.ConnectionInfo.DatabaseName;
                        connectionInfoElement.Add(databaseNameElement);

                        XElement passwordElement = new XElement(XName.Get("Password", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
                        passwordElement.Value = parameters.ConnectionInfo.Password;
                        connectionInfoElement.Add(passwordElement);

                        XElement serverNameElement = new XElement(XName.Get("ServerName", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
                        serverNameElement.Value = parameters.ConnectionInfo.ServerName;
                        connectionInfoElement.Add(serverNameElement);

                        XElement userNameElement = new XElement(XName.Get("UserName", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
                        userNameElement.Value = parameters.ConnectionInfo.UserName;
                        connectionInfoElement.Add(userNameElement);
                    }
                }

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

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

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

                    XElement guidElement = responseDoc.Element(XName.Get("guid", "http://schemas.microsoft.com/2003/10/Serialization/"));
                    if (guidElement != null)
                    {
                        result.Guid = guidElement.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();
                }
            }
        }