Example #1
0
        /// <summary>
        /// Creates a new sql database.
        /// </summary>
        /// <param name="databaseName">The name for the new database</param>
        /// <param name="databaseMaxSizeInGB">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?databaseMaxSizeInGB,
            string databaseCollation,
            DatabaseEdition databaseEdition,
            ServiceObjective serviceObjective)
        {
            this.clientRequestId = SqlDatabaseCmdletBase.GenerateClientTracingId();

            // Get the SQL management client
            SqlManagementClient sqlManagementClient = this.subscription.CreateClient <SqlManagementClient>();

            this.AddTracingHeaders(sqlManagementClient);

            // Create the database
            DatabaseCreateResponse response = sqlManagementClient.Databases.Create(
                this.serverName,
                new DatabaseCreateParameters()
            {
                Name    = databaseName,
                Edition = databaseEdition != DatabaseEdition.None ?
                          databaseEdition.ToString() : DatabaseEdition.Web.ToString(),
                CollationName           = databaseCollation ?? string.Empty,
                MaximumDatabaseSizeInGB = databaseMaxSizeInGB ??
                                          (databaseEdition == DatabaseEdition.Business || databaseEdition == DatabaseEdition.Premium ? 10 : 1),
                ServiceObjectiveId = serviceObjective != null ? serviceObjective.Id.ToString() : null,
            });

            // Construct the resulting Database object
            Database database = CreateDatabaseFromResponse(response);

            return(database);
        }
        /// <summary>
        /// Terminate an ongoing database copy operation.
        /// </summary>
        /// <param name="copyModel">The database copy to terminate.</param>
        /// <param name="forcedTermination"><c>true</c> to forcefully terminate the copy.</param>
        public void StopDatabaseCopy(
            DatabaseCopyModel copyModel,
            bool forcedTermination)
        {
            DatabaseCopy databaseCopy = GetCopyForCopyModel(copyModel);

            // Create a new request Id for this operation
            this.clientRequestId = SqlDatabaseCmdletBase.GenerateClientTracingId();

            try
            {
                // Mark Forced/Friendly flag on the databaseCopy object first
                databaseCopy.IsForcedTerminate = forcedTermination;
                this.UpdateObject(databaseCopy);
                this.SaveChanges();

                // Mark the copy operation for delete
                this.DeleteObject(databaseCopy);
                this.SaveChanges();
            }
            catch
            {
                this.RevertChanges(databaseCopy);
                throw;
            }
        }
Example #3
0
        /// <summary>
        /// Removes a new firewall rule on the specified server.
        /// </summary>
        /// <param name="serverName">
        /// The name of the server containing the firewall rule.
        /// </param>
        /// <param name="ruleName">
        /// The name of the firewall rule to remove.
        /// </param>
        /// <returns>The context to this operation.</returns>
        internal SqlDatabaseServerOperationContext RemoveAzureSqlDatabaseServerFirewallRuleProcess(string serverName, string ruleName)
        {
            // Do nothing if force is not specified and user cancelled the operation
            if (!Force.IsPresent &&
                !ShouldProcess(
                    string.Format(CultureInfo.InvariantCulture, Resources.RemoveAzureSqlDatabaseServerFirewallRuleDescription, ruleName, serverName),
                    string.Format(CultureInfo.InvariantCulture, Resources.RemoveAzureSqlDatabaseServerFirewallRuleWarning, ruleName, serverName),
                    Resources.ShouldProcessCaption))
            {
                return(null);
            }

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

            // Delete the specified firewall rule.
            OperationResponse response = sqlManagementClient.FirewallRules.Delete(serverName, ruleName);

            SqlDatabaseServerOperationContext operationContext = new SqlDatabaseServerOperationContext()
            {
                OperationStatus      = Services.Constants.OperationSuccess,
                OperationDescription = CommandRuntime.ToString(),
                OperationId          = response.RequestId,
                ServerName           = serverName
            };

            return(operationContext);
        }
Example #4
0
        /// <summary>
        /// Retrieves the list of all operations on the database.
        /// </summary>
        /// <param name="databaseName">The name of database to retrieve operations.</param>
        /// <returns>An array of all operations on the database.</returns>
        public DatabaseOperation[] GetDatabaseOperations(string databaseName)
        {
            this.clientRequestId = SqlDatabaseCmdletBase.GenerateClientTracingId();

            // Get the SQL management client
            SqlManagementClient sqlManagementClient = this.subscription.CreateClient <SqlManagementClient>();

            this.AddTracingHeaders(sqlManagementClient);

            // Retrieve all operations on specified database
            DatabaseOperationListResponse response = sqlManagementClient.DatabaseOperations.ListByDatabase(
                this.serverName,
                databaseName);

            // For any database which has ever been created, there should be at least one operation
            if (response.Count() == 0)
            {
                throw new InvalidOperationException(
                          string.Format(
                              CultureInfo.InvariantCulture,
                              Resources.DatabaseOperationNotFoundOnDatabase,
                              this.ServerName,
                              databaseName));
            }

            // Construct the resulting database operations
            DatabaseOperation[] operations = response.Select(operation => CreateDatabaseOperationsFromResponse(operation)).ToArray();
            return(operations);
        }
Example #5
0
        /// <summary>
        /// Creates a new firewall rule on the specified server.
        /// </summary>
        /// <param name="parameterSetName">The parameter set for the command.</param>
        /// <param name="serverName">The name of the server in which to create the firewall rule.</param>
        /// <param name="ruleName">The name of the new firewall rule.</param>
        /// <param name="startIpAddress">The starting IP address for the firewall rule.</param>
        /// <param name="endIpAddress">The ending IP address for the firewall rule.</param>
        /// <returns>The context to the newly created firewall rule.</returns>
        internal SqlDatabaseServerFirewallRuleContext NewAzureSqlDatabaseServerFirewallRuleProcess(
            string parameterSetName,
            string serverName,
            string ruleName,
            string startIpAddress,
            string endIpAddress)
        {
            // Get the SQL management client for the current subscription
            SqlManagementClient sqlManagementClient = SqlDatabaseCmdletBase.GetCurrentSqlClient();

            // Create the firewall rule
            FirewallRuleCreateResponse response = sqlManagementClient.FirewallRules.Create(
                serverName,
                new FirewallRuleCreateParameters()
            {
                Name           = ruleName,
                StartIPAddress = startIpAddress,
                EndIPAddress   = endIpAddress,
            });

            SqlDatabaseServerFirewallRuleContext operationContext = new SqlDatabaseServerFirewallRuleContext()
            {
                OperationDescription = CommandRuntime.ToString(),
                OperationStatus      = Services.Constants.OperationSuccess,
                OperationId          = response.RequestId,
                ServerName           = serverName,
                RuleName             = ruleName,
                StartIpAddress       = response.StartIPAddress,
                EndIpAddress         = response.EndIPAddress,
            };

            return(operationContext);
        }
        /// <summary>
        /// Resets the administrator password for an existing server in the
        /// current subscription.
        /// </summary>
        /// <param name="serverName">
        /// The name of the server for which to reset the password.
        /// </param>
        /// <param name="newPassword">
        /// The new password for the server.
        /// </param>
        /// <returns>The context to this operation.</returns>
        internal SqlDatabaseServerOperationContext ResetAzureSqlDatabaseServerAdminPasswordProcess(string serverName, string newPassword)
        {
            // Do nothing if force is not specified and user cancelled the operation
            if (!Force.IsPresent &&
                !ShouldProcess(
                    string.Format(CultureInfo.InvariantCulture, Resources.SetAzureSqlDatabaseServerAdminPasswordDescription, serverName),
                    string.Format(CultureInfo.InvariantCulture, Resources.SetAzureSqlDatabaseServerAdminPasswordWarning, serverName),
                    Resources.ShouldProcessCaption))
            {
                return(null);
            }

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

            // Issue the change admin password request
            OperationResponse response = sqlManagementClient.Servers.ChangeAdministratorPassword(
                serverName,
                new ServerChangeAdministratorPasswordParameters()
            {
                NewPassword = newPassword
            });

            SqlDatabaseServerOperationContext operationContext = new SqlDatabaseServerOperationContext()
            {
                OperationStatus      = Services.Constants.OperationSuccess,
                OperationDescription = CommandRuntime.ToString(),
                OperationId          = response.RequestId,
                ServerName           = serverName,
            };

            return(operationContext);
        }
Example #7
0
        /// <summary>
        /// Performs the call to export database using the server data service context channel.
        /// </summary>
        /// <param name="serverName">The name of the server to connect to.</param>
        /// <param name="fullyQualifiedServerName">The fully qualfied name of the server to connect to.</param>
        /// <param name="userName">The username for authentication</param>
        /// <param name="password">The password for authentication</param>
        /// <param name="requestId">The request Id of the operation to query</param>
        /// <returns>The status of the import/export operation</returns>
        internal IEnumerable <StatusInfo> GetAzureSqlDatabaseImportExportStatusProcess(
            string serverName,
            string fullyQualifiedServerName,
            string userName,
            string password,
            string requestId)
        {
            // Get the SQL management client for the current subscription
            SqlManagementClient sqlManagementClient = SqlDatabaseCmdletBase.GetCurrentSqlClient();

            // Start the database export operation
            DacGetStatusResponse response = sqlManagementClient.Dacs.GetStatus(
                serverName,
                fullyQualifiedServerName,
                userName,
                password,
                requestId);

            // Construct the result
            IEnumerable <StatusInfo> result = response.StatusInfoList.Select(status => new StatusInfo
            {
                BlobUri          = status.BlobUri.ToString(),
                ServerName       = status.ServerName,
                DatabaseName     = status.DatabaseName,
                Status           = status.Status,
                RequestId        = status.RequestId,
                LastModifiedTime = status.LastModifiedTime,
                QueuedTime       = status.QueuedTime,
                RequestType      = status.RequestType,
                ErrorMessage     = status.ErrorMessage,
            });

            return(result);
        }
 /// <summary>
 /// Creates an instance of a SQLAuth to TSql class
 /// </summary>
 /// <param name="fullyQualifiedServerName">The full server name</param>
 /// <param name="credentials">The login credentials for the server</param>
 public TSqlConnectionContext(Guid sessionActivityId, string fullyQualifiedServerName, SqlAuthenticationCredentials credentials, string serverName)
 {
     this.serverName        = serverName;
     this.sessionActivityId = sessionActivityId;
     this.clientRequestId   = SqlDatabaseCmdletBase.GenerateClientTracingId();
     this.credentials       = credentials;
     builder = GenerateSqlConnectionBuilder(fullyQualifiedServerName, credentials.UserName, credentials.Password);
 }
Example #9
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 = SqlDatabaseCmdletBase.GenerateClientTracingId();

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

            return(doc);
        }
Example #10
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 = SqlDatabaseCmdletBase.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.
            this.LoadExtraProperties(database);

            return(database);
        }
Example #11
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 = SqlDatabaseCmdletBase.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);
        }
Example #12
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 = SqlDatabaseCmdletBase.GenerateClientTracingId();

            // Get the SQL management client
            SqlManagementClient sqlManagementClient = this.subscription.CreateClient <SqlManagementClient>();

            this.AddTracingHeaders(sqlManagementClient);

            // Retrieve the list of databases
            OperationResponse response = sqlManagementClient.Databases.Delete(
                this.serverName,
                databaseName);
        }
Example #13
0
        /// <summary>
        /// Creates and returns a new instance of the <see cref="ServerDataServiceCertAuth"/> class
        /// which connects to the specified server using the specified subscription credentials.
        /// </summary>
        /// <param name="subscription">The subscription used to connect and authenticate.</param>
        /// <param name="serverName">The name of the server to connect to.</param>
        /// <returns>An instance of <see cref="ServerDataServiceCertAuth"/> class.</returns>
        public static ServerDataServiceCertAuth Create(
            string serverName,
            WindowsAzureSubscription subscription)
        {
            if (string.IsNullOrEmpty(serverName))
            {
                throw new ArgumentException("serverName");
            }

            SqlDatabaseCmdletBase.ValidateSubscription(subscription);

            // Create a new ServerDataServiceCertAuth object to be used
            return(new ServerDataServiceCertAuth(
                       subscription,
                       serverName));
        }
Example #14
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 = SqlDatabaseCmdletBase.GenerateClientTracingId();

            // Get the SQL management client
            SqlManagementClient sqlManagementClient = this.subscription.CreateClient <SqlManagementClient>();

            this.AddTracingHeaders(sqlManagementClient);

            // Retrieve the list of databases
            DatabaseListResponse response = sqlManagementClient.Databases.List(this.serverName);

            // Construct the resulting Database objects
            Database[] databases = response.Databases.Select((db) => CreateDatabaseFromResponse(db)).ToArray();
            return(databases);
        }
Example #15
0
        /// <summary>
        /// Retrieves the list of all service objectives on the server.
        /// </summary>
        /// <returns>An array of all service objectives on the server.</returns>
        public ServiceObjective[] GetServiceObjectives()
        {
            this.clientRequestId = SqlDatabaseCmdletBase.GenerateClientTracingId();

            // Get the SQL management client
            SqlManagementClient sqlManagementClient = this.subscription.CreateClient <SqlManagementClient>();

            this.AddTracingHeaders(sqlManagementClient);

            // Retrieve the specified database
            ServiceObjectiveListResponse response = sqlManagementClient.ServiceObjectives.List(
                this.serverName);

            // Construct the resulting Database object
            ServiceObjective[] serviceObjectives = response.Select(serviceObjective => CreateServiceObjectiveFromResponse(serviceObjective)).ToArray();
            return(serviceObjectives);
        }
        /// <summary>
        /// Start database copy on the database with the name <paramref name="databaseName"/>.
        /// </summary>
        /// <param name="databaseName">The name of the database to copy.</param>
        /// <param name="partnerServer">The name for the partner server.</param>
        /// <param name="partnerDatabaseName">The name of the database on the partner server.</param>
        /// <param name="continuousCopy"><c>true</c> to make this a continuous copy.</param>
        /// <param name="isOfflineSecondary"><c>true</c> to make this an offline secondary copy.</param>
        /// <returns>The new instance of database copy operation.</returns>
        public DatabaseCopyModel StartDatabaseCopy(
            string databaseName,
            string partnerServer,
            string partnerDatabaseName,
            bool continuousCopy,
            bool isOfflineSecondary)
        {
            // Create a new request Id for this operation
            this.clientRequestId = SqlDatabaseCmdletBase.GenerateClientTracingId();

            // Create a new database copy object with all the required properties
            DatabaseCopy databaseCopy = new DatabaseCopy();

            databaseCopy.SourceServerName        = this.ServerName;
            databaseCopy.SourceDatabaseName      = databaseName;
            databaseCopy.DestinationServerName   = partnerServer;
            databaseCopy.DestinationDatabaseName = partnerDatabaseName;

            // Set the optional continuous copy flag
            databaseCopy.IsContinuous = continuousCopy;

            // Set the optional IsOfflineSecondary flag
            databaseCopy.IsOfflineSecondary = isOfflineSecondary;

            this.AddToDatabaseCopies(databaseCopy);
            DatabaseCopy trackedDatabaseCopy = databaseCopy;

            try
            {
                this.SaveChanges(SaveChangesOptions.None);

                // Requery for the entity to obtain updated linkid and state
                databaseCopy = this.RefreshEntity(databaseCopy);
                if (databaseCopy == null)
                {
                    throw new ApplicationException(Resources.ErrorRefreshingDatabaseCopy);
                }
            }
            catch
            {
                this.RevertChanges(trackedDatabaseCopy);
                throw;
            }

            return(CreateCopyModelFromCopy(databaseCopy));
        }
Example #17
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>
        /// <param name="credentials">The SQL authentication credentials used for this context</param>
        private ServerDataServiceSqlAuth(
            Uri managementServiceUri,
            DataServiceConnectionType connectionType,
            Guid sessionActivityId,
            AccessTokenResult accessToken,
            SqlAuthenticationCredentials credentials)
            : base(new Uri(managementServiceUri, connectionType.RelativeEntityUri))
        {
            this.sessionActivityId = sessionActivityId;
            this.connectionType    = connectionType;
            this.accessToken       = accessToken;
            this.credentials       = credentials;

            // Generate a requestId and retrieve the server name
            this.clientRequestId = SqlDatabaseCmdletBase.GenerateClientTracingId();
            this.serverName      = this.Servers.First().Name;
        }
Example #18
0
        /// <summary>
        /// Retrieves one or more firewall rules on the specified server.
        /// </summary>
        /// <param name="serverName">The name of the server to retrieve firewall rules for.</param>
        /// <param name="ruleName">
        /// The specific name of the rule to retrieve, or <c>null</c> to
        /// retrieve all rules on the specified server.
        /// </param>
        /// <returns>A list of firewall rules on the server.</returns>
        internal IEnumerable <SqlDatabaseServerFirewallRuleContext> GetAzureSqlDatabaseServerFirewallRuleProcess(
            string serverName,
            string ruleName)
        {
            // Get the SQL management client for the current subscription
            SqlManagementClient sqlManagementClient = SqlDatabaseCmdletBase.GetCurrentSqlClient();

            // Retrieve the list of databases
            FirewallRuleListResponse   response      = sqlManagementClient.FirewallRules.List(serverName);
            IEnumerable <FirewallRule> firewallRules = response.FirewallRules;

            if (!string.IsNullOrEmpty(ruleName))
            {
                // Firewall rule name is specified, find the one
                // with the specified rule name and return that.
                firewallRules = firewallRules.Where(p => p.Name == ruleName);
                if (!firewallRules.Any())
                {
                    throw new ItemNotFoundException(string.Format(
                                                        CultureInfo.InvariantCulture,
                                                        Resources.GetAzureSqlDatabaseServerFirewallRuleNotFound,
                                                        ruleName,
                                                        serverName));
                }
            }
            else
            {
                // Firewall rule name is not specified, return all
                // firewall rules.
            }

            IEnumerable <SqlDatabaseServerFirewallRuleContext> processResult = firewallRules.Select(p => new SqlDatabaseServerFirewallRuleContext()
            {
                OperationDescription = CommandRuntime.ToString(),
                OperationStatus      = Services.Constants.OperationSuccess,
                OperationId          = response.RequestId,
                ServerName           = serverName,
                RuleName             = p.Name,
                StartIpAddress       = p.StartIPAddress,
                EndIpAddress         = p.EndIPAddress
            });

            return(processResult);
        }
Example #19
0
        /// <summary>
        /// Retrieves the list of all databases' operations on the server.
        /// </summary>
        /// <returns>An array of all operations on the server.</returns>
        public DatabaseOperation[] GetDatabasesOperations()
        {
            this.clientRequestId = SqlDatabaseCmdletBase.GenerateClientTracingId();

            // Get the SQL management client
            SqlManagementClient sqlManagementClient = this.subscription.CreateClient <SqlManagementClient>();

            this.AddTracingHeaders(sqlManagementClient);

            // Retrieve the operations on specified server
            // We do not validate the number of operations returned since it's possible that there is no
            // database operations on a new created server.
            DatabaseOperationListResponse response = sqlManagementClient.DatabaseOperations.ListByServer(
                this.serverName);

            // Construct the resulting database operations array
            DatabaseOperation[] operations = response.Select(operation => CreateDatabaseOperationsFromResponse(operation)).ToArray();
            return(operations);
        }
Example #20
0
        /// <summary>
        /// Retrieve information on operation with the guid
        /// </summary>
        /// <param name="OperationGuid">The Guid of the operation to retrieve.</param>
        /// <returns>An object containing the information about the specific operation.</returns>
        public DatabaseOperation GetDatabaseOperation(Guid OperationGuid)
        {
            this.clientRequestId = SqlDatabaseCmdletBase.GenerateClientTracingId();

            // Get the SQL management client
            SqlManagementClient sqlManagementClient = this.subscription.CreateClient <SqlManagementClient>();

            this.AddTracingHeaders(sqlManagementClient);

            // Retrieve the specified Operation
            DatabaseOperationGetResponse response = sqlManagementClient.DatabaseOperations.Get(
                this.serverName,
                OperationGuid.ToString());

            // Construct the resulting Operation object
            DatabaseOperation operation = CreateDatabaseOperationFromResponse(response);

            return(operation);
        }
Example #21
0
        /// <summary>
        /// Retrieve information on latest service objective with service objective
        /// </summary>
        /// <param name="serviceObjective">The service objective to refresh.</param>
        /// <returns>
        /// An object containing the information about the specific service objective.
        /// </returns>
        public ServiceObjective GetServiceObjective(ServiceObjective serviceObjectiveToRefresh)
        {
            this.clientRequestId = SqlDatabaseCmdletBase.GenerateClientTracingId();

            // Get the SQL management client
            SqlManagementClient sqlManagementClient = this.subscription.CreateClient <SqlManagementClient>();

            this.AddTracingHeaders(sqlManagementClient);

            // Retrieve the specified database
            ServiceObjectiveGetResponse response = sqlManagementClient.ServiceObjectives.Get(
                this.serverName,
                serviceObjectiveToRefresh.Id.ToString());

            // Construct the resulting Database object
            ServiceObjective serviceObjective = CreateServiceObjectiveFromResponse(response);

            return(serviceObjective);
        }
Example #22
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 = SqlDatabaseCmdletBase.GenerateClientTracingId();

            // Get the SQL management client
            SqlManagementClient sqlManagementClient = this.subscription.CreateClient <SqlManagementClient>();

            this.AddTracingHeaders(sqlManagementClient);

            // Retrieve the specified database
            DatabaseGetResponse response = sqlManagementClient.Databases.Get(
                this.serverName,
                databaseName);

            // Construct the resulting Database object
            Database database = CreateDatabaseFromResponse(response);

            return(database);
        }
Example #23
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="databaseMaxSizeInGB">The new maximum size of the database.</param>
        /// <param name="databaseEdition">The new edition of the database.</param>
        /// <param name="serviceObjective">The new service objective of the database.</param>
        /// <returns>The updated database.</returns>
        public Database UpdateDatabase(
            string databaseName,
            string newDatabaseName,
            int?databaseMaxSizeInGB,
            DatabaseEdition?databaseEdition,
            ServiceObjective serviceObjective)
        {
            this.clientRequestId = SqlDatabaseCmdletBase.GenerateClientTracingId();

            // Get the SQL management client
            SqlManagementClient sqlManagementClient = this.subscription.CreateClient <SqlManagementClient>();

            this.AddTracingHeaders(sqlManagementClient);

            // Retrieve the specified database
            DatabaseGetResponse database = sqlManagementClient.Databases.Get(
                this.serverName,
                databaseName);

            // Update the database with the new properties
            DatabaseUpdateResponse response = sqlManagementClient.Databases.Update(
                this.serverName,
                databaseName,
                new DatabaseUpdateParameters()
            {
                Id   = database.Id,
                Name = !string.IsNullOrEmpty(newDatabaseName) ?
                       newDatabaseName : database.Name,
                Edition = databaseEdition.HasValue && (databaseEdition != DatabaseEdition.None) ?
                          databaseEdition.ToString() : (database.Edition ?? string.Empty),
                CollationName           = database.CollationName ?? string.Empty,
                MaximumDatabaseSizeInGB = databaseMaxSizeInGB.HasValue ?
                                          databaseMaxSizeInGB.Value : database.MaximumDatabaseSizeInGB,
                ServiceObjectiveId = serviceObjective != null ?
                                     serviceObjective.Id.ToString() : null,
            });

            // Construct the resulting Database object
            Database updatedDatabase = CreateDatabaseFromResponse(response);

            return(updatedDatabase);
        }
        /// <summary>
        /// Retrieves one or more servers in the current subscription.
        /// </summary>
        /// <param name="serverName">
        /// The specific name of the server to retrieve, or <c>null</c> to
        /// retrieve all servers in the current subscription.
        /// </param>
        /// <returns>A list of servers in the subscription.</returns>
        internal IEnumerable <SqlDatabaseServerContext> GetAzureSqlDatabaseServersProcess(string serverName)
        {
            // Get the SQL management client for the current subscription
            SqlManagementClient sqlManagementClient = SqlDatabaseCmdletBase.GetCurrentSqlClient();

            // Retrieve the list of servers
            ServerListResponse   response = sqlManagementClient.Servers.List();
            IEnumerable <Server> servers  = response.Servers;

            if (!string.IsNullOrEmpty(serverName))
            {
                // Server name is specified, find the one with the
                // specified rule name and return that.
                servers = response.Servers.Where(s => s.Name == serverName);
                if (!servers.Any())
                {
                    throw new ItemNotFoundException(string.Format(
                                                        CultureInfo.InvariantCulture,
                                                        Resources.GetAzureSqlDatabaseServerNotFound,
                                                        serverName));
                }
            }
            else
            {
                // Server name is not specified, return all servers
                // in the subscription.
            }

            // Construct the result
            IEnumerable <SqlDatabaseServerContext> processResult = servers.Select(server => new SqlDatabaseServerContext
            {
                OperationStatus      = Services.Constants.OperationSuccess,
                OperationDescription = CommandRuntime.ToString(),
                OperationId          = response.RequestId,
                ServerName           = server.Name,
                Location             = server.Location,
                AdministratorLogin   = server.AdministratorUserName,
            });

            return(processResult);
        }
Example #25
0
        /// <summary>
        /// Connect to Azure SQL Server using certificate authentication.
        /// </summary>
        /// <param name="serverName">The name of the server to connect to</param>
        /// <param name="subscription">The subscription data to use for authentication</param>
        /// <returns>A new <see cref="ServerDataServiceCertAuth"/> context,
        /// or <c>null</c> if an error occurred.</returns>
        internal ServerDataServiceCertAuth GetServerDataServiceByCertAuth(
            string serverName,
            IAzureSubscription subscription)
        {
            ServerDataServiceCertAuth context = null;

            SqlDatabaseCmdletBase.ValidateSubscription(subscription);

            try
            {
                context = ServerDataServiceCertAuth.Create(serverName, Profile, subscription);
            }
            catch (ArgumentException e)
            {
                SqlDatabaseExceptionHandler.WriteErrorDetails(this, string.Empty, e);

                context = null;
            }

            return(context);
        }
        /// <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);
        }
Example #27
0
 /// <summary>
 /// Creates an instance of a SQLAuth to TSql class
 /// </summary>
 /// <param name="fullyQualifiedServerName"></param>
 /// <param name="username"></param>
 /// <param name="password"></param>
 public TSqlConnectionContext(Guid sessionActivityId, string fullyQualifiedServerName, string username, string password)
 {
     this.sessionActivityId = sessionActivityId;
     this.clientRequestId   = SqlDatabaseCmdletBase.GenerateClientTracingId();
     builder = GenerateSqlConnectionBuilder(fullyQualifiedServerName, username, password);
 }