Example #1
0
 /// <summary>
 /// Imports a database from blob storage
 /// </summary>
 /// <param name="proxy">Channel used for communication with Azure's service management APIs</param>
 /// <param name="subscriptionId">The subscription ID in which the server resides</param>
 /// <param name="serverName">The name of the server to put the database in</param>
 /// <param name="input">The input data for the import operation</param>
 /// <returns>An <see cref="XmlElement"/> containing the request ID (GUID).</returns>
 public static XmlElement ImportDatabase(
     this ISqlDatabaseManagement proxy,
     string subscriptionId,
     string serverName,
     ImportInput input)
 {
     return(proxy.EndImportDatabase(proxy.BeginImportDatabase(
                                        subscriptionId,
                                        serverName,
                                        input,
                                        null,
                                        null)));
 }
Example #2
0
        /// <summary>
        /// A mock call to BeginImportDatabase
        /// </summary>
        /// <param name="subscriptionId">The subscription Id to pass through</param>
        /// <param name="serverName">The server name to pass through</param>
        /// <param name="input">The input object to pass through</param>
        /// <param name="callback">The callback object to pass through</param>
        /// <param name="state">The state object to pass through</param>
        /// <returns>An <see cref="IAsyncResult"/> of the mock request</returns>
        public IAsyncResult BeginImportDatabase(
            string subscriptionId,
            string serverName,
            ImportInput input,
            AsyncCallback callback,
            object state)
        {
            SimpleServiceManagementAsyncResult result = new SimpleServiceManagementAsyncResult();

            result.Values["subscriptionId"] = subscriptionId;
            result.Values["serverName"]     = serverName;
            result.Values["input"]          = input;
            result.Values["callback"]       = callback;
            result.Values["state"]          = state;
            return(result);
        }
Example #3
0
        private static ImportInput BuildImportInput(long time, string serverName, string databaseName)
        {
            string key, blobUri;

            PrepareBlob(time, databaseName, out key, out blobUri);
            var importInputs = new ImportInput
            {
                AzureEdition     = "Web",
                DatabaseSizeInGB = 1,
                BlobCredentials  = new BlobStorageAccessKeyCredentials
                {
                    StorageAccessKey = key,
                    Uri = blobUri
                },
                ConnectionInfo = BuildConnectionInfo(serverName, databaseName)
            };

            return(importInputs);
        }
        public string DoImport(ImportDatabaseEventSource log, string blobUri, bool whatIf, int databaseSizeInGB = 5)
        {
            string requestGuid = null;

            //Setup Web Request for Import Operation
            WebRequest webRequest = WebRequest.Create(this.EndPointUri + @"/Import");
            webRequest.Method = WebRequestMethods.Http.Post;
            webRequest.ContentType = @"application/xml";

            //Create Web Request Inputs - Database Size & Edition, Blob Store Credentials and Server Connection Info
            ImportInput importInputs = new ImportInput
            {
                AzureEdition = "Web",
                DatabaseSizeInGB = databaseSizeInGB,
                BlobCredentials = new BlobStorageAccessKeyCredentials
                {
                    StorageAccessKey = this.StorageKey,
                    Uri = String.Format(blobUri, this.DatabaseName, DateTime.UtcNow.Ticks.ToString())
                },
                ConnectionInfo = new ConnectionInfo
                {
                    ServerName = this.ServerName,
                    DatabaseName = this.DatabaseName,
                    UserName = this.UserName,
                    Password = this.Password
                }
            };

            //Perform Web Request
            Stream webRequestStream = webRequest.GetRequestStream();
            DataContractSerializer dataContractSerializer = new DataContractSerializer(importInputs.GetType());

            if (whatIf)
            {
                using (var strm = new MemoryStream())
                {
                    dataContractSerializer.WriteObject(strm, importInputs);
                    strm.Flush();
                    strm.Seek(0, SeekOrigin.Begin);
                    using (var reader = new StreamReader(strm))
                    {
                        log.WouldHaveSent(reader.ReadToEnd());
                    }
                }
                return null;
            }
            else
            {
                using (var strm = new MemoryStream())
                {
                    dataContractSerializer.WriteObject(strm, importInputs);
                    strm.Flush();
                    strm.Seek(0, SeekOrigin.Begin);
                    using (var reader = new StreamReader(strm))
                    {
                        log.SendingRequest(reader.ReadToEnd());
                    }
                }

                dataContractSerializer.WriteObject(webRequestStream, importInputs);
                webRequestStream.Close();

                //Get Response and Extract Request Identifier
                WebResponse webResponse = null;
                XmlReader xmlStreamReader = null;

                try
                {
                    //Initialize the WebResponse to the response from the WebRequest
                    webResponse = webRequest.GetResponse();

                    xmlStreamReader = XmlReader.Create(webResponse.GetResponseStream());
                    xmlStreamReader.ReadToFollowing("guid");
                    requestGuid = xmlStreamReader.ReadElementContentAsString();
                    return requestGuid;
                }
                catch (WebException responseException)
                {
                    log.RequestFailed(responseException.Message);
                    {
                        log.ErrorStatusCode((int)(((HttpWebResponse)responseException.Response).StatusCode));
                        log.ErrorStatusDescription(((HttpWebResponse)responseException.Response).StatusDescription);
                    }

                    return null;
                }
            }
        }
Example #5
0
        /// <summary>
        /// Process the import request
        /// </summary>
        protected override void ProcessRecord()
        {
            try
            {
                base.ProcessRecord();

                string accessKey = null;
                string blobUri   = null;

                switch (this.ParameterSetName)
                {
                case ByContainerNameParameterSet:
                    accessKey =
                        System.Convert.ToBase64String(
                            this.StorageContext.StorageAccount.Credentials.ExportKey());

                    blobUri =
                        this.StorageContext.BlobEndPoint +
                        this.StorageContainerName + "/" +
                        this.BlobName;
                    break;

                case ByContainerObjectParameterSet:
                    accessKey =
                        System.Convert.ToBase64String(
                            this.StorageContainer.CloudBlobContainer.ServiceClient.Credentials.ExportKey());

                    blobUri =
                        this.StorageContainer.Context.BlobEndPoint +
                        this.StorageContainer.Name + "/" +
                        this.BlobName;
                    break;
                }

                string fullyQualifiedServerName =
                    this.SqlConnectionContext.ServerName + DataServiceConstants.AzureSqlDatabaseDnsSuffix;

                // Create Web Request Inputs - Blob Storage Credentials and Server Connection Info
                ImportInput importInput = new ImportInput
                {
                    BlobCredentials = new BlobStorageAccessKeyCredentials
                    {
                        StorageAccessKey = accessKey,
                        Uri = blobUri
                    },
                    ConnectionInfo = new ConnectionInfo
                    {
                        ServerName   = fullyQualifiedServerName,
                        DatabaseName = this.DatabaseName,
                        UserName     = this.SqlConnectionContext.SqlCredentials.UserName,
                        Password     = this.SqlConnectionContext.SqlCredentials.Password
                    }
                };

                if (this.MyInvocation.BoundParameters.ContainsKey("Edition"))
                {
                    importInput.AzureEdition = this.Edition.ToString();
                }

                if (this.MyInvocation.BoundParameters.ContainsKey("DatabaseMaxSize"))
                {
                    importInput.DatabaseSizeInGB = this.DatabaseMaxSize;
                }

                ImportExportRequest request =
                    this.ImportSqlAzureDatabaseProcess(this.SqlConnectionContext.ServerName, importInput);

                if (request != null)
                {
                    request.SqlCredentials = this.SqlConnectionContext.SqlCredentials;
                    request.ServerName     = this.SqlConnectionContext.ServerName;
                    this.WriteObject(request);
                }
            }
            catch (Exception ex)
            {
                SqlDatabaseExceptionHandler.WriteErrorDetails(
                    this,
                    this.SqlConnectionContext.ClientRequestId,
                    ex);
            }
        }
Example #6
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="input">The <see cref="ImportInput"/> object that contains
        /// all the connection information</param>
        /// <returns>The result of the import request.  Upon success the <see cref="ImportExportRequest"/>
        /// for the request</returns>
        internal ImportExportRequest ImportSqlAzureDatabaseProcess(string serverName, ImportInput input)
        {
            ImportExportRequest result = null;

            try
            {
                XmlElement requestId = RetryCall(subscription =>
                                                 this.Channel.ImportDatabase(subscription, serverName, input));
                Microsoft.WindowsAzure.ServiceManagement.Operation operation = WaitForSqlDatabaseOperation();

                if (requestId != null)
                {
                    result             = new ImportExportRequest();
                    result.RequestGuid = requestId.InnerText;
                }
            }
            catch (Exception ex)
            {
                SqlDatabaseExceptionHandler.WriteErrorDetails(
                    this,
                    this.SqlConnectionContext.ClientRequestId,
                    ex);
            }

            return(result);
        }
Example #7
0
        public void ImportAzureSqlDatabaseProcessTest()
        {
            string      serverName = "TestServer";
            ImportInput input      = new ImportInput()
            {
                AzureEdition     = "Web",
                DatabaseSizeInGB = 1,
                BlobCredentials  = new BlobStorageAccessKeyCredentials()
                {
                    Uri = "blobUri",
                    StorageAccessKey = "storage access key"
                },
                ConnectionInfo = new ConnectionInfo()
                {
                    DatabaseName = "databaseName",
                    Password     = "******",
                    ServerName   = "serverName",
                    UserName     = "******"
                }
            };

            Guid testGuid = Guid.NewGuid();

            MockCommandRuntime          commandRuntime = new MockCommandRuntime();
            SimpleSqlDatabaseManagement channel        = new SimpleSqlDatabaseManagement();

            channel.ImportDatabaseThunk = ar =>
            {
                Assert.AreEqual(serverName, (string)ar.Values["serverName"]);
                Assert.AreEqual(
                    input.AzureEdition,
                    ((ImportInput)ar.Values["input"]).AzureEdition);
                Assert.AreEqual(
                    input.DatabaseSizeInGB,
                    ((ImportInput)ar.Values["input"]).DatabaseSizeInGB);
                Assert.AreEqual(
                    input.BlobCredentials.Uri,
                    ((ImportInput)ar.Values["input"]).BlobCredentials.Uri);
                Assert.AreEqual(
                    input.ConnectionInfo.DatabaseName,
                    ((ImportInput)ar.Values["input"]).ConnectionInfo.DatabaseName);
                Assert.AreEqual(
                    input.ConnectionInfo.Password,
                    ((ImportInput)ar.Values["input"]).ConnectionInfo.Password);
                Assert.AreEqual(
                    input.ConnectionInfo.ServerName,
                    ((ImportInput)ar.Values["input"]).ConnectionInfo.ServerName);
                Assert.AreEqual(
                    input.ConnectionInfo.UserName,
                    ((ImportInput)ar.Values["input"]).ConnectionInfo.UserName);

                XmlElement operationResult =
                    new XmlDocument().CreateElement(
                        "guid",
                        "http://schemas.microsoft.com/2003/10/Serialization/");

                operationResult.InnerText = testGuid.ToString();
                return(operationResult);
            };

            StartAzureSqlDatabaseImport importAzureSqlDatabase =
                new StartAzureSqlDatabaseImport(channel)
            {
                ShareChannel = true
            };

            importAzureSqlDatabase.CurrentSubscription = UnitTestHelper.CreateUnitTestSubscription();
            importAzureSqlDatabase.CommandRuntime      = commandRuntime;
            var result = importAzureSqlDatabase.ImportSqlAzureDatabaseProcess(serverName, input);

            Assert.AreEqual(testGuid.ToString(), result.RequestGuid);

            Assert.AreEqual(0, commandRuntime.ErrorStream.Count);
        }
        public bool DoImport(string blobUri)
        {
            logger.Info(String.Format("Starting Import Operation - {0}\n\r", DateTime.Now));
            string requestGuid = null;
            bool importComplete = false;

            //Setup Web Request for Import Operation
            WebRequest webRequest = WebRequest.Create(this.EndPointUri + @"/Import");
            webRequest.Method = WebRequestMethods.Http.Post;
            webRequest.ContentType = @"application/xml";

            //Create Web Request Inputs - Database Size & Edition, Blob Store Credentials and Server Connection Info
            ImportInput importInputs = new ImportInput
            {
                AzureEdition = "Web",
                DatabaseSizeInGB = 1,
                BlobCredentials = new BlobStorageAccessKeyCredentials
                {
                    StorageAccessKey = this.StorageKey,
                    Uri = String.Format(blobUri, this.DatabaseName, DateTime.UtcNow.Ticks.ToString())
                },
                ConnectionInfo = new ConnectionInfo
                {
                    ServerName = this.ServerName,
                    DatabaseName = this.DatabaseName,
                    UserName = this.UserName,
                    Password = this.Password
                }
            };

            //Perform Web Request
            logger.Info("Making Web Request for Import Operation...");
            Stream webRequestStream = webRequest.GetRequestStream();
            DataContractSerializer dataContractSerializer = new DataContractSerializer(importInputs.GetType());
            dataContractSerializer.WriteObject(webRequestStream, importInputs);
            webRequestStream.Close();

            //Get Response and Extract Request Identifier
            logger.Info("Serializing response and extracting guid...");
            WebResponse webResponse = null;
            XmlReader xmlStreamReader = null;

            try
            {
                //Initialize the WebResponse to the response from the WebRequest
                webResponse = webRequest.GetResponse();

                xmlStreamReader = XmlReader.Create(webResponse.GetResponseStream());
                xmlStreamReader.ReadToFollowing("guid");
                requestGuid = xmlStreamReader.ReadElementContentAsString();
                logger.Info(String.Format("Request Guid: {0}", requestGuid));

                //Get Status of Import Operation
                while (!importComplete)
                {
                    logger.Info("Checking status of Import...");
                    List<StatusInfo> statusInfoList = CheckRequestStatus(requestGuid);
                    StatusInfo statusInfo = statusInfoList.FirstOrDefault();
                    logger.Info(statusInfo.Status);

                    if (statusInfo.Status == "Failed")
                    {
                        logger.Info(String.Format("Database import failed: {0}", statusInfo.ErrorMessage));
                        importComplete = true;
                    }

                    if (statusInfo.Status == "Completed")
                    {
                        logger.Info(String.Format("Import Complete - Database imported to: {0}\n\r", statusInfo.DatabaseName));
                        importComplete = true;
                    }
                }

                return importComplete;
            }
            catch (WebException responseException)
            {
                logger.ErrorFormat("Request Falied: {0}",responseException, responseException.Message);
                {
                    logger.ErrorFormat("Status Code: {0}", ((HttpWebResponse)responseException.Response).StatusCode);
                    logger.ErrorFormat("Status Description: {0}\n\r", ((HttpWebResponse)responseException.Response).StatusDescription);
                }

                return importComplete;
            }
        }
        public bool DoImport(string blobUri)
        {
            logger.Info(String.Format("Starting Import Operation - {0}\n\r", DateTime.Now));
            string requestGuid    = null;
            bool   importComplete = false;

            //Setup Web Request for Import Operation
            WebRequest webRequest = WebRequest.Create(this.EndPointUri + @"/Import");

            webRequest.Method      = WebRequestMethods.Http.Post;
            webRequest.ContentType = @"application/xml";

            //Create Web Request Inputs - Database Size & Edition, Blob Store Credentials and Server Connection Info
            ImportInput importInputs = new ImportInput
            {
                AzureEdition     = "Web",
                DatabaseSizeInGB = 1,
                BlobCredentials  = new BlobStorageAccessKeyCredentials
                {
                    StorageAccessKey = this.StorageKey,
                    Uri = String.Format(blobUri, this.DatabaseName, DateTime.UtcNow.Ticks.ToString())
                },
                ConnectionInfo = new ConnectionInfo
                {
                    ServerName   = this.ServerName,
                    DatabaseName = this.DatabaseName,
                    UserName     = this.UserName,
                    Password     = this.Password
                }
            };

            //Perform Web Request
            logger.Info("Making Web Request for Import Operation...");
            Stream webRequestStream = webRequest.GetRequestStream();
            DataContractSerializer dataContractSerializer = new DataContractSerializer(importInputs.GetType());

            dataContractSerializer.WriteObject(webRequestStream, importInputs);
            webRequestStream.Close();

            //Get Response and Extract Request Identifier
            logger.Info("Serializing response and extracting guid...");
            WebResponse webResponse     = null;
            XmlReader   xmlStreamReader = null;

            try
            {
                //Initialize the WebResponse to the response from the WebRequest
                webResponse = webRequest.GetResponse();

                xmlStreamReader = XmlReader.Create(webResponse.GetResponseStream());
                xmlStreamReader.ReadToFollowing("guid");
                requestGuid = xmlStreamReader.ReadElementContentAsString();
                logger.Info(String.Format("Request Guid: {0}", requestGuid));

                //Get Status of Import Operation
                while (!importComplete)
                {
                    logger.Info("Checking status of Import...");
                    List <StatusInfo> statusInfoList = CheckRequestStatus(requestGuid);
                    StatusInfo        statusInfo     = statusInfoList.FirstOrDefault();
                    logger.Info(statusInfo.Status);

                    if (statusInfo.Status == "Failed")
                    {
                        logger.Info(String.Format("Database import failed: {0}", statusInfo.ErrorMessage));
                        importComplete = true;
                    }

                    if (statusInfo.Status == "Completed")
                    {
                        logger.Info(String.Format("Import Complete - Database imported to: {0}\n\r", statusInfo.DatabaseName));
                        importComplete = true;
                    }
                }

                return(importComplete);
            }
            catch (WebException responseException)
            {
                logger.ErrorFormat("Request Falied: {0}", responseException, responseException.Message);
                {
                    logger.ErrorFormat("Status Code: {0}", ((HttpWebResponse)responseException.Response).StatusCode);
                    logger.ErrorFormat("Status Description: {0}\n\r", ((HttpWebResponse)responseException.Response).StatusDescription);
                }

                return(importComplete);
            }
        }
        public string DoImport(ImportDatabaseEventSource log, string blobUri, bool whatIf, int databaseSizeInGB = 5)
        {
            string requestGuid = null;

            //Setup Web Request for Import Operation
            WebRequest webRequest = WebRequest.Create(this.EndPointUri + @"/Import");

            webRequest.Method      = WebRequestMethods.Http.Post;
            webRequest.ContentType = @"application/xml";

            //Create Web Request Inputs - Database Size & Edition, Blob Store Credentials and Server Connection Info
            ImportInput importInputs = new ImportInput
            {
                AzureEdition     = "Web",
                DatabaseSizeInGB = databaseSizeInGB,
                BlobCredentials  = new BlobStorageAccessKeyCredentials
                {
                    StorageAccessKey = this.StorageKey,
                    Uri = String.Format(blobUri, this.DatabaseName, DateTime.UtcNow.Ticks.ToString())
                },
                ConnectionInfo = new ConnectionInfo
                {
                    ServerName   = this.ServerName,
                    DatabaseName = this.DatabaseName,
                    UserName     = this.UserName,
                    Password     = this.Password
                }
            };

            //Perform Web Request
            Stream webRequestStream = webRequest.GetRequestStream();
            DataContractSerializer dataContractSerializer = new DataContractSerializer(importInputs.GetType());

            if (whatIf)
            {
                using (var strm = new MemoryStream())
                {
                    dataContractSerializer.WriteObject(strm, importInputs);
                    strm.Flush();
                    strm.Seek(0, SeekOrigin.Begin);
                    using (var reader = new StreamReader(strm))
                    {
                        log.WouldHaveSent(reader.ReadToEnd());
                    }
                }
                return(null);
            }
            else
            {
                using (var strm = new MemoryStream())
                {
                    dataContractSerializer.WriteObject(strm, importInputs);
                    strm.Flush();
                    strm.Seek(0, SeekOrigin.Begin);
                    using (var reader = new StreamReader(strm))
                    {
                        log.SendingRequest(reader.ReadToEnd());
                    }
                }

                dataContractSerializer.WriteObject(webRequestStream, importInputs);
                webRequestStream.Close();

                //Get Response and Extract Request Identifier
                WebResponse webResponse     = null;
                XmlReader   xmlStreamReader = null;

                try
                {
                    //Initialize the WebResponse to the response from the WebRequest
                    webResponse = webRequest.GetResponse();

                    xmlStreamReader = XmlReader.Create(webResponse.GetResponseStream());
                    xmlStreamReader.ReadToFollowing("guid");
                    requestGuid = xmlStreamReader.ReadElementContentAsString();
                    return(requestGuid);
                }
                catch (WebException responseException)
                {
                    log.RequestFailed(responseException.Message);
                    {
                        log.ErrorStatusCode((int)(((HttpWebResponse)responseException.Response).StatusCode));
                        log.ErrorStatusDescription(((HttpWebResponse)responseException.Response).StatusDescription);
                    }

                    return(null);
                }
            }
        }