protected override ISqlDatabaseManagement CreateChannel()
        {
            // If ShareChannel is set by a unit test, use the same channel that
            // was passed into out constructor.  This allows the test to submit
            // a mock that we use for all network calls.
            if (ShareChannel)
            {
                return(Channel);
            }

            if (this.ServiceBinding == null)
            {
                this.ServiceBinding = ConfigurationConstants.WebHttpBinding(this.MaxStringContentLength);
            }

            if (string.IsNullOrEmpty(CurrentSubscription.ServiceEndpoint))
            {
                this.ServiceEndpoint = ConfigurationConstants.ServiceManagementEndpoint;
            }
            else
            {
                this.ServiceEndpoint = CurrentSubscription.ServiceEndpoint;
            }

            return(SqlDatabaseManagementHelper.CreateSqlDatabaseManagementChannel(this.ServiceBinding, new Uri(this.ServiceEndpoint), CurrentSubscription.Certificate, this.clientRequestId));
        }
Beispiel #2
0
        public void SqlDatabaseManagementErrorTest()
        {
            string serverRequestId = Guid.NewGuid().ToString();

            string errorMessage =
                @"<Error xmlns=""http://schemas.microsoft.com/sqlazure/2010/12/"">
  <Code>40647</Code>
  <Message>Subscription '00000000-1111-2222-3333-444444444444' does not have the server 'server0001'.</Message>
  <Severity>16</Severity>
  <State>1</State>
</Error>";
            WebException exception = CreateWebException(HttpStatusCode.BadRequest, errorMessage, (context) =>
            {
                context.Response.Headers.Add(Constants.RequestIdHeaderName, serverRequestId);
            });

            ErrorRecord errorRecord;
            string      requestId;

            SqlDatabaseManagementHelper.RetrieveExceptionDetails(exception, out errorRecord, out requestId);

            Assert.AreEqual(serverRequestId, requestId);
            Assert.AreEqual(
                @"Subscription '00000000-1111-2222-3333-444444444444' does not have the server 'server0001'.
Error Code: 40647",
                errorRecord.Exception.Message);
        }
Beispiel #3
0
        /// <summary>
        /// Remove a database from a server
        /// </summary>
        /// <param name="databaseName">The name of the database to delete</param>
        public void RemoveDatabase(string databaseName)
        {
            this.clientRequestId = SqlDatabaseManagementHelper.GenerateClientTracingId();

            ISqlDatabaseManagement channel = GetManagementChannel();

            Database database = this.GetDatabase(databaseName);

            SqlDatabaseInput input = new SqlDatabaseInput();

            input.Name          = databaseName;
            input.Id            = database.Id.ToString();
            input.CollationName = database.CollationName;
            input.Edition       = database.Edition.ToString();
            input.MaxSizeGB     = database.MaxSizeGB.ToString();

            channel.EndRemoveDatabase(
                channel.BeginRemoveDatabase(
                    this.subscriptionId,
                    this.serverName,
                    databaseName,
                    input,
                    null,
                    null));
        }
Beispiel #4
0
        /// <summary>
        /// Retrieves the metadata for the context as a <see cref="XDocument"/>
        /// </summary>
        /// <returns>The metadata for the context as a <see cref="XDocument"/></returns>
        public XDocument RetrieveMetadata()
        {
            // Create a new request Id for this operation
            this.clientRequestId = SqlDatabaseManagementHelper.GenerateClientTracingId();

            XDocument doc = DataConnectionUtility.GetMetadata(this, EnhanceRequest);

            return(doc);
        }
Beispiel #5
0
        /// <summary>
        /// Creates a new Sql Database.
        /// </summary>
        /// <param name="databaseName">The name for the new database.</param>
        /// <param name="databaseMaxSize">The max size for the database.</param>
        /// <param name="databaseCollation">The collation for the database.</param>
        /// <param name="databaseEdition">The edition for the database.</param>
        /// <returns>The newly created Sql Database.</returns>
        public Database CreateNewDatabase(
            string databaseName,
            int?databaseMaxSize,
            string databaseCollation,
            DatabaseEdition databaseEdition)
        {
            // Create a new request Id for this operation
            this.clientRequestId = SqlDatabaseManagementHelper.GenerateClientTracingId();

            // Create the new entity and set its properties
            Database database = new Database();

            database.Name = databaseName;

            if (databaseMaxSize != null)
            {
                database.MaxSizeGB = (int)databaseMaxSize;
            }

            if (!string.IsNullOrEmpty(databaseCollation))
            {
                database.CollationName = databaseCollation;
            }

            if (databaseEdition != DatabaseEdition.None)
            {
                database.Edition = databaseEdition.ToString();
            }

            // Save changes
            this.AddToDatabases(database);
            try
            {
                this.SaveChanges(SaveChangesOptions.None);

                // Re-Query the database for server side updated information
                database = this.RefreshEntity(database);
                if (database == null)
                {
                    throw new ApplicationException(Resources.ErrorRefreshingDatabase);
                }
            }
            catch
            {
                this.ClearTrackedEntity(database);
                throw;
            }

            // Load the extra properties for this object.
            database.LoadExtraProperties(this);

            return(database);
        }
Beispiel #6
0
 /// <summary>
 /// Creates a channel for communication with the server.
 /// </summary>
 /// <returns>a new channel to use for communication</returns>
 private ISqlDatabaseManagement GetManagementChannel()
 {
     if (this.Channel == null)
     {
         //create a channel to the server for communication
         ISqlDatabaseManagement channel = SqlDatabaseManagementHelper.CreateSqlDatabaseManagementChannel(
             ConfigurationConstants.WebHttpBinding(ConfigurationConstants.MaxStringContentLength),
             this.serviceEndpoint,
             this.certificate,
             this.clientRequestId);
         this.Channel = channel;
     }
     return(this.Channel);
 }
Beispiel #7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ServerDataServiceSqlAuth"/> class.
        /// </summary>
        /// <param name="managementServiceUri">The server's management service Uri.</param>
        /// <param name="connectionType">The server connection type with the server name</param>
        /// <param name="sessionActivityId">An activity ID provided by the user that should be associated with this session.</param>
        /// <param name="accessToken">The authentication access token to be used for executing web requests.</param>
        private ServerDataServiceSqlAuth(
            Uri managementServiceUri,
            DataServiceConnectionType connectionType,
            Guid sessionActivityId,
            AccessTokenResult accessToken)
            : base(new Uri(managementServiceUri, connectionType.RelativeEntityUri))
        {
            this.sessionActivityId = sessionActivityId;
            this.connectionType    = connectionType;
            this.accessToken       = accessToken;

            // Generate a requestId and retrieve the server name
            this.clientRequestId = SqlDatabaseManagementHelper.GenerateClientTracingId();
            this.serverName      = this.Servers.First().Name;
        }
Beispiel #8
0
        public void ServiceResourceErrorTest()
        {
            string serverRequestId = Guid.NewGuid().ToString();

            string       errorMessage = @"<Error xmlns=""Microsoft.SqlServer.Management.Framework.Web.Services"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""><Message>Resource with the name 'FirewallRule1' does not exist. To continue, specify a valid resource name.</Message><InnerError i:nil=""true""/></Error>";
            WebException exception    = CreateWebException(HttpStatusCode.NotFound, errorMessage, (context) =>
            {
                context.Response.Headers.Add(Constants.RequestIdHeaderName, serverRequestId);
            });

            ErrorRecord errorRecord;
            string      requestId;

            SqlDatabaseManagementHelper.RetrieveExceptionDetails(exception, out errorRecord, out requestId);

            Assert.AreEqual(serverRequestId, requestId);
            Assert.AreEqual("Resource with the name 'FirewallRule1' does not exist. To continue, specify a valid resource name.", errorRecord.Exception.Message);
        }
Beispiel #9
0
        /// <summary>
        /// Retrieve a specific database from the current context
        /// </summary>
        /// <param name="databaseName">The name of the database to retrieve</param>
        /// <returns>A database object</returns>
        public Database GetDatabase(string databaseName)
        {
            this.clientRequestId = SqlDatabaseManagementHelper.GenerateClientTracingId();

            //create a channel to the server for communication
            ISqlDatabaseManagement channel = GetManagementChannel();

            //query the server for the database
            SqlDatabaseResponse database =
                channel.EndGetDatabase(
                    channel.BeginGetDatabase(this.subscriptionId, this.ServerName, databaseName, null, null));

            //Create the database from the response
            Database result = CreateDatabaseFromResponse(database);

            //return the database
            return(result);
        }
Beispiel #10
0
        /// <summary>
        /// Gets a list of all the databases in the current context.
        /// </summary>
        /// <returns>An array of databases in the current context</returns>
        public Database[] GetDatabases()
        {
            this.clientRequestId = SqlDatabaseManagementHelper.GenerateClientTracingId();

            ISqlDatabaseManagement channel = GetManagementChannel();

            SqlDatabaseList databases =
                channel.EndGetDatabases(
                    channel.BeginGetDatabases(this.subscriptionId, this.ServerName, null, null));

            List <Database> results = new List <Database>();

            foreach (var db in databases)
            {
                //Create the database from the response
                results.Add(CreateDatabaseFromResponse(db));
            }

            return(results.ToArray());
        }
Beispiel #11
0
        /// <summary>
        /// Creates a new sql database.
        /// </summary>
        /// <param name="databaseName">The name for the new database</param>
        /// <param name="databaseMaxSize">The maximum size of the new database</param>
        /// <param name="databaseCollation">The collation for the new database</param>
        /// <param name="databaseEdition">The edition for the new database</param>
        /// <returns>The newly created Sql Database</returns>
        public Database CreateNewDatabase(
            string databaseName,
            int?databaseMaxSize,
            string databaseCollation,
            DatabaseEdition databaseEdition)
        {
            this.clientRequestId = SqlDatabaseManagementHelper.GenerateClientTracingId();

            ISqlDatabaseManagement channel = GetManagementChannel();

            SqlDatabaseInput input = new SqlDatabaseInput();

            input.Name          = databaseName;
            input.CollationName = databaseCollation ?? string.Empty;

            //determine the edition
            if (databaseEdition != DatabaseEdition.None)
            {
                input.Edition = databaseEdition.ToString();
            }
            else
            {
                input.Edition = string.Empty;
            }

            //determine the maximum size
            if (databaseMaxSize.HasValue)
            {
                input.MaxSizeGB = databaseMaxSize.ToString();
            }

            //create a new database on the server
            SqlDatabaseResponse response =
                channel.EndNewDatabase(
                    channel.BeginNewDatabase(this.subscriptionId, this.serverName, input, null, null));

            Database database = CreateDatabaseFromResponse(response);

            return(database);
        }
        protected override void WriteErrorDetails(CommunicationException exception)
        {
            string      requestId;
            ErrorRecord errorRecord;

            SqlDatabaseManagementHelper.RetrieveExceptionDetails(exception, out errorRecord, out requestId);

            // Write the request Id as a warning
            if (requestId != null)
            {
                // requestId was availiable from the server response, write that as warning to the console
                WriteWarning(string.Format(CultureInfo.InvariantCulture, Resources.ExceptionRequestId, requestId));
            }
            else
            {
                // requestId was not availiable from the server response, write the client Ids that was sent
                WriteWarning(string.Format(CultureInfo.InvariantCulture, Resources.ExceptionClientSessionId, SqlDatabaseManagementCmdletBase.clientSessionId));
                WriteWarning(string.Format(CultureInfo.InvariantCulture, Resources.ExceptionClientRequestId, this.clientRequestId));
            }

            // Write the actual errorRecord containing the exception details
            WriteError(errorRecord);
        }
 internal SqlDatabaseManagementCmdletBase()
 {
     this.clientRequestId = SqlDatabaseManagementHelper.GenerateClientTracingId();
 }
 static SqlDatabaseManagementCmdletBase()
 {
     clientSessionId = SqlDatabaseManagementHelper.GenerateClientTracingId();
 }
Beispiel #15
0
        /// <summary>
        /// Update a database on the server.
        /// </summary>
        /// <param name="databaseName">The name of the database to modify</param>
        /// <param name="newDatabaseName">The new name of the database</param>
        /// <param name="databaseMaxSize">The new maximum size of the database</param>
        /// <param name="databaseEdition">The new edition of the database</param>
        /// <returns>The updated database</returns>
        public Database UpdateDatabase(
            string databaseName,
            string newDatabaseName,
            int?databaseMaxSize,
            DatabaseEdition?databaseEdition,
            ServiceObjective serviceObjective)
        {
            this.clientRequestId = SqlDatabaseManagementHelper.GenerateClientTracingId();

            ISqlDatabaseManagement channel = GetManagementChannel();

            Database database = this.GetDatabase(databaseName);

            //make sure the database exists.
            if (database == null)
            {
                throw new Exception(
                          "Error: Result of GetDatabase() in ServerDataServiceCertAuth.UpdateDatabase() is null");
            }

            SqlDatabaseInput input = new SqlDatabaseInput();

            //Set the database ID and collation
            input.Id            = database.Id.ToString();
            input.CollationName = database.CollationName;

            if (serviceObjective != null)
            {
                input.ServiceObjectiveId = serviceObjective.Id.ToString();
            }

            //Determine what the new name for the database should be
            if (!string.IsNullOrEmpty(newDatabaseName))
            {
                input.Name = newDatabaseName;
            }
            else
            {
                input.Name = database.Name;
            }

            //Determine what the new edition for the database should be
            if (databaseEdition.HasValue && (databaseEdition != DatabaseEdition.None))
            {
                input.Edition = databaseEdition.ToString();
            }
            else
            {
                input.Edition = database.Edition;
            }

            //Determine what the new maximum size for the database should be.
            if (databaseMaxSize.HasValue)
            {
                input.MaxSizeGB = databaseMaxSize.ToString();
            }
            else
            {
                input.MaxSizeGB = database.MaxSizeGB.ToString();
            }

            //Send the update request and wait for the response.
            SqlDatabaseResponse response = channel.EndUpdateDatabase(
                channel.BeginUpdateDatabase(
                    this.subscriptionId,
                    this.serverName,
                    databaseName,
                    input,
                    null,
                    null));

            //Transform the response into a database object.
            Database updatedDatabase = CreateDatabaseFromResponse(response);

            return(updatedDatabase);
        }