/// <summary>
        /// Validates the RestorePointListResponse.
        /// </summary>
        /// <param name="restorePointsListResponse">Response to validate.</param>
        /// <param name="isDataWarehouseDatabase">Is this response from a data warehouse database? Data warehouse databases return different values than other databases.</param>
        /// <param name="expectedCount">Expected number of restore points.</param>
        private static void ValidateRestorePointListResponse(RestorePointListResponse restorePointsListResponse, bool isDataWarehouseDatabase, int expectedCount)
        {
            Assert.Equal(expectedCount, restorePointsListResponse.Count());
            int count = restorePointsListResponse.Count();

            if (count == expectedCount && count > 0)
            {
                RestorePoint selectedRestorePoint = restorePointsListResponse.RestorePoints.First();
                if (isDataWarehouseDatabase)
                {
                    Assert.Equal("DISCRETE", selectedRestorePoint.Properties.RestorePointType);
                    Assert.Null(selectedRestorePoint.Properties.EarliestRestoreDate);
                    Assert.NotNull(selectedRestorePoint.Properties.RestorePointCreationDate);
                }
                else
                {
                    Assert.Equal("CONTINUOUS", selectedRestorePoint.Properties.RestorePointType);
                    Assert.NotNull(selectedRestorePoint.Properties.EarliestRestoreDate);
                    Assert.Null(selectedRestorePoint.Properties.RestorePointCreationDate);
                }
            }
        }
 /// <summary>
 /// Validates the RestorePointListResponse.
 /// </summary>
 /// <param name="restorePointsListResponse">Response to validate.</param>
 /// <param name="isDataWarehouseDatabase">Is this response from a data warehouse database? Data warehouse databases return different values than other databases.</param>
 /// <param name="expectedCount">Expected number of restore points.</param>
 private static void ValidateRestorePointListResponse(RestorePointListResponse restorePointsListResponse, bool isDataWarehouseDatabase, int expectedCount)
 {
     Assert.Equal(expectedCount, restorePointsListResponse.Count());
     int count = restorePointsListResponse.Count();
     if (count == expectedCount && count > 0)
     {
         RestorePoint selectedRestorePoint = restorePointsListResponse.RestorePoints.First();
         if (isDataWarehouseDatabase)
         {
             Assert.Equal("DISCRETE", selectedRestorePoint.Properties.RestorePointType);
             Assert.Null(selectedRestorePoint.Properties.EarliestRestoreDate);
             Assert.NotNull(selectedRestorePoint.Properties.RestorePointCreationDate);
         }
         else
         {
             Assert.Equal("CONTINUOUS", selectedRestorePoint.Properties.RestorePointType);
             Assert.NotNull(selectedRestorePoint.Properties.EarliestRestoreDate);
             Assert.Null(selectedRestorePoint.Properties.RestorePointCreationDate);
         }
     }
 }
        public void ListRestorePointsTest()
        {
            var handler = new BasicDelegatingHandler();

            using (UndoContext context = UndoContext.Current)
            {
                context.Start();

                // Management Clients
                var sqlClient = Sql2ScenarioHelper.GetSqlClient(handler);
                var resClient = Sql2ScenarioHelper.GetResourceClient(handler);

                // Variables for server creation.
                string serverName   = TestUtilities.GenerateName("csm-sql-backup");
                string resGroupName = TestUtilities.GenerateName("csm-rg-backup");

                string serverLocation = "Japan East";
                string adminLogin     = "******";
                string adminPass      = "******";
                string version        = "12.0";

                // Constants for Azure SQL Data Warehouse database creation.
                var    defaultDatabaseSize = 250L * 1024L * 1024L * 1024L;                  // 250 GB
                Guid   dwSlo           = new Guid("4E63CB0E-91B9-46FD-B05C-51FDD2367618 "); // DW100
                var    databaseName    = TestUtilities.GenerateName("csm-sql-backup-dwdb");
                string databaseEdition = "DataWarehouse";

                // Constants for Azure SQL standard database creation.
                var    standardDefaultDatabaseSize = 1L * 1024L * 1024L * 1024L; // 1 GB
                var    standardDatabaseName        = TestUtilities.GenerateName("csm-sql-backup-db");
                string standardDatabaseEdition     = "Standard";

                // Create the resource group.
                resClient.ResourceGroups.CreateOrUpdate(resGroupName, new ResourceGroup()
                {
                    Location = serverLocation,
                });

                try
                {
                    //////////////////////////////////////////////////////////////////////
                    // Create server for test.
                    var createResponse = sqlClient.Servers.CreateOrUpdate(resGroupName, serverName, new ServerCreateOrUpdateParameters()
                    {
                        Location   = serverLocation,
                        Properties = new ServerCreateOrUpdateProperties()
                        {
                            AdministratorLogin         = adminLogin,
                            AdministratorLoginPassword = adminPass,
                            Version = version,
                        }
                    });

                    // Verify the the response from the service contains the right information
                    TestUtilities.ValidateOperationResponse(createResponse, HttpStatusCode.Created);
                    //////////////////////////////////////////////////////////////////////

                    //////////////////////////////////////////////////////////////////////
                    // Create database test.

                    // Create data warehouse database
                    var createDbResponse = sqlClient.Databases.CreateOrUpdate(resGroupName, serverName, databaseName, new DatabaseCreateOrUpdateParameters()
                    {
                        Location   = serverLocation,
                        Properties = new DatabaseCreateOrUpdateProperties()
                        {
                            MaxSizeBytes = defaultDatabaseSize,
                            Edition      = databaseEdition,
                            RequestedServiceObjectiveId = dwSlo,
                        },
                    });

                    TestUtilities.ValidateOperationResponse(createDbResponse, HttpStatusCode.Created);

                    // Create standard database
                    createDbResponse = sqlClient.Databases.CreateOrUpdate(resGroupName, serverName, standardDatabaseName, new DatabaseCreateOrUpdateParameters()
                    {
                        Location   = serverLocation,
                        Properties = new DatabaseCreateOrUpdateProperties()
                        {
                            MaxSizeBytes = standardDefaultDatabaseSize,
                            Edition      = standardDatabaseEdition,
                            RequestedServiceObjectiveId = SqlConstants.DbSloS0,
                        },
                    });

                    TestUtilities.ValidateOperationResponse(createDbResponse, HttpStatusCode.Created);
                    //////////////////////////////////////////////////////////////////////

                    //////////////////////////////////////////////////////////////////////
                    // Get restore points for data warehouse database.

                    RestorePointListResponse restorePointsListResponse = sqlClient.DatabaseBackup.ListRestorePoints(resGroupName, serverName, databaseName);

                    // Creating a data warehouse database should not have any discrete restore points right after.
                    TestUtilities.ValidateOperationResponse(restorePointsListResponse, HttpStatusCode.OK);
                    ValidateRestorePointListResponse(restorePointsListResponse, true, 0);
                    ///////////////////////////////////////////////////////////////////////

                    //////////////////////////////////////////////////////////////////////
                    // Get restore points for standard database.

                    restorePointsListResponse = sqlClient.DatabaseBackup.ListRestorePoints(resGroupName, serverName, standardDatabaseName);

                    TestUtilities.ValidateOperationResponse(restorePointsListResponse, HttpStatusCode.OK);
                    ValidateRestorePointListResponse(restorePointsListResponse, false, 1);
                    ///////////////////////////////////////////////////////////////////////
                }
                finally
                {
                    // Clean up the resource group.
                    resClient.ResourceGroups.Delete(resGroupName);
                }
            }
        }
Пример #4
0
        /// <summary>
        /// Returns a list of Azure SQL Database restore points.
        /// </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='databaseName'>
        /// Required. The name of the Azure SQL Database from which to retrieve
        /// available restore points.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Represents the response to a List Azure Sql Database restore points
        /// request.
        /// </returns>
        public async Task <RestorePointListResponse> ListRestorePointsAsync(string resourceGroupName, string serverName, string databaseName, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }
            if (serverName == null)
            {
                throw new ArgumentNullException("serverName");
            }
            if (databaseName == null)
            {
                throw new ArgumentNullException("databaseName");
            }

            // Tracing
            bool   shouldTrace  = TracingAdapter.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("serverName", serverName);
                tracingParameters.Add("databaseName", databaseName);
                TracingAdapter.Enter(invocationId, this, "ListRestorePointsAsync", tracingParameters);
            }

            // Construct URL
            string url = "";

            url = url + "/subscriptions/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/resourceGroups/";
            url = url + Uri.EscapeDataString(resourceGroupName);
            url = url + "/providers/";
            url = url + "Microsoft.Sql";
            url = url + "/servers/";
            url = url + Uri.EscapeDataString(serverName);
            url = url + "/databases/";
            url = url + Uri.EscapeDataString(databaseName);
            url = url + "/restorePoints";
            List <string> queryParameters = new List <string>();

            queryParameters.Add("api-version=2014-04-01");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            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

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        TracingAdapter.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)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    RestorePointListResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                        result = new RestorePointListResponse();
                        JToken responseDoc = null;
                        if (string.IsNullOrEmpty(responseContent) == false)
                        {
                            responseDoc = JToken.Parse(responseContent);
                        }

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            JToken valueArray = responseDoc["value"];
                            if (valueArray != null && valueArray.Type != JTokenType.Null)
                            {
                                foreach (JToken valueValue in ((JArray)valueArray))
                                {
                                    RestorePoint restorePointInstance = new RestorePoint();
                                    result.RestorePoints.Add(restorePointInstance);

                                    JToken propertiesValue = valueValue["properties"];
                                    if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
                                    {
                                        RestorePointProperties propertiesInstance = new RestorePointProperties();
                                        restorePointInstance.Properties = propertiesInstance;

                                        JToken restorePointTypeValue = propertiesValue["restorePointType"];
                                        if (restorePointTypeValue != null && restorePointTypeValue.Type != JTokenType.Null)
                                        {
                                            string restorePointTypeInstance = ((string)restorePointTypeValue);
                                            propertiesInstance.RestorePointType = restorePointTypeInstance;
                                        }

                                        JToken restorePointCreationDateValue = propertiesValue["restorePointCreationDate"];
                                        if (restorePointCreationDateValue != null && restorePointCreationDateValue.Type != JTokenType.Null)
                                        {
                                            DateTime restorePointCreationDateInstance = ((DateTime)restorePointCreationDateValue);
                                            propertiesInstance.RestorePointCreationDate = restorePointCreationDateInstance;
                                        }

                                        JToken earliestRestoreDateValue = propertiesValue["earliestRestoreDate"];
                                        if (earliestRestoreDateValue != null && earliestRestoreDateValue.Type != JTokenType.Null)
                                        {
                                            DateTime earliestRestoreDateInstance = ((DateTime)earliestRestoreDateValue);
                                            propertiesInstance.EarliestRestoreDate = earliestRestoreDateInstance;
                                        }
                                    }

                                    JToken idValue = valueValue["id"];
                                    if (idValue != null && idValue.Type != JTokenType.Null)
                                    {
                                        string idInstance = ((string)idValue);
                                        restorePointInstance.Id = idInstance;
                                    }

                                    JToken nameValue = valueValue["name"];
                                    if (nameValue != null && nameValue.Type != JTokenType.Null)
                                    {
                                        string nameInstance = ((string)nameValue);
                                        restorePointInstance.Name = nameInstance;
                                    }

                                    JToken typeValue = valueValue["type"];
                                    if (typeValue != null && typeValue.Type != JTokenType.Null)
                                    {
                                        string typeInstance = ((string)typeValue);
                                        restorePointInstance.Type = typeInstance;
                                    }

                                    JToken locationValue = valueValue["location"];
                                    if (locationValue != null && locationValue.Type != JTokenType.Null)
                                    {
                                        string locationInstance = ((string)locationValue);
                                        restorePointInstance.Location = locationInstance;
                                    }

                                    JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
                                    if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
                                    {
                                        foreach (JProperty property in tagsSequenceElement)
                                        {
                                            string tagsKey   = ((string)property.Name);
                                            string tagsValue = ((string)property.Value);
                                            restorePointInstance.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)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }