private void ProcessWithContext(IServerDataServiceContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context", "The ServerDataServiceContext cannot be null.");
            }

            try
            {
                if (this.ServiceObjectiveName != null)
                {
                    // Retrieve the service objective with the specified name
                    this.WriteObject(context.GetServiceObjective(this.ServiceObjectiveName));
                }
                else if (this.ServiceObjective != null)
                {
                    // Retrieve the latest service objective with the specified service objective
                    this.WriteObject(context.GetServiceObjective(this.ServiceObjective));
                }
                else
                {
                    // No name specified, retrieve all service objectives in the server
                    this.WriteObject(context.GetServiceObjectives(), true);
                }
            }
            catch (Exception ex)
            {
                SqlDatabaseExceptionHandler.WriteErrorDetails(
                    this,
                    context.ClientRequestId,
                    ex);
            }
        }
Exemple #2
0
        /// <summary>
        /// Connect to a Azure SQL Server with the given ManagementService Uri using
        /// SQL authentication credentials.
        /// </summary>
        /// <param name="serverName">The server name.</param>
        /// <param name="managementServiceUri">The server's ManagementService Uri.</param>
        /// <param name="credentials">The SQL Authentication credentials for the server.</param>
        /// <returns>A new <see cref="ServerDataServiceSqlAuth"/> context,
        /// or <c>null</c> if an error occurred.</returns>
        internal IServerDataServiceContext GetServerDataServiceBySqlAuth(
            string serverName,
            Uri managementServiceUri,
            SqlAuthenticationCredentials credentials,
            Uri manageUrl)
        {
            IServerDataServiceContext context = null;
            Guid sessionActivityId            = Guid.NewGuid();

            try
            {
                context = SqlAuthContextFactory.GetContext(this, serverName, manageUrl, credentials, sessionActivityId, managementServiceUri);
            }
            catch (Exception ex)
            {
                SqlDatabaseExceptionHandler.WriteErrorDetails(
                    this,
                    sessionActivityId.ToString(),
                    ex);

                // The context is not in an valid state because of the error, set the context
                // back to null.
                context = null;
            }

            return(context);
        }
        /// <summary>
        /// Process the command.
        /// </summary>
        protected override void ProcessRecord()
        {
            try
            {
                base.ProcessRecord();

                // First obtain the Management Service Uri and the ServerName
                Uri    manageUrl            = this.GetManageUrl(this.ParameterSetName);
                Uri    managementServiceUri = DataConnectionUtility.GetManagementServiceUri(manageUrl);
                string serverName           = this.GetServerName(manageUrl);

                // Creates a new Server Data Service Context for the service
                IServerDataServiceContext operationContext =
                    this.CreateServerDataServiceContext(serverName, managementServiceUri);

                if (operationContext != null)
                {
                    this.WriteObject(operationContext);
                }
            }
            catch (Exception ex)
            {
                this.WriteError(new ErrorRecord(ex, string.Empty, ErrorCategory.CloseError, null));
            }
        }
 /// <summary>
 /// Process the request using the provided connection context
 /// </summary>
 /// <param name="context"></param>
 private void ProcessWithContext(IServerDataServiceContext context)
 {
     try
     {
         if (this.DatabaseName != null)
         {
             // Retrieve the operations with the specified database name
             this.WriteObject(context.GetDatabaseOperations(this.DatabaseName), true);
         }
         else if (this.Database != null)
         {
             // Retrieve the operations with the database name specified by the database object
             this.WriteObject(context.GetDatabaseOperations(this.Database.Name), true);
         }
         else if (this.OperationGuid != Guid.Empty)
         {
             // Retrieve the operation with the operation Guid
             this.WriteObject(context.GetDatabaseOperation(this.OperationGuid), true);
         }
         else
         {
             // No name specified, retrieve all database's operations in the server
             this.WriteObject(context.GetDatabasesOperations(), true);
         }
     }
     catch (Exception ex)
     {
         SqlDatabaseExceptionHandler.WriteErrorDetails(
             this,
             context.ClientRequestId,
             ex);
     }
 }
        /// <summary>
        /// Process the request using the provided connection context
        /// </summary>
        /// <param name="databaseName">the name of the database to retrieve</param>
        private void ProcessWithContext(IServerDataServiceContext context)
        {
            string databaseName = GetDatabaseName();

            try
            {
                if (databaseName != null)
                {
                    // Retrieve the database with the specified name
                    this.WriteObject(context.GetDatabase(databaseName), true);
                }
                else
                {
                    // No name specified, retrieve all databases in the server
                    this.WriteObject(context.GetDatabases(), true);
                }
            }
            catch (Exception ex)
            {
                SqlDatabaseExceptionHandler.WriteErrorDetails(
                    this,
                    context.ClientRequestId,
                    ex);
            }
        }
Exemple #6
0
        /// <summary>
        /// Gets a sql auth connection context.
        /// </summary>
        /// <param name="cmdlet">The cmdlet requesting the context</param>
        /// <param name="serverName">The name of the server to connect to</param>
        /// <param name="manageUrl">The manage url of the server</param>
        /// <param name="credentials">The credentials to connect to the server</param>
        /// <param name="sessionActivityId">The session activity ID</param>
        /// <param name="managementServiceUri">The URI for management service</param>
        /// <returns>The connection context</returns>
        public static IServerDataServiceContext GetContext(
            PSCmdlet cmdlet,
            string serverName,
            Uri manageUrl,
            SqlAuthenticationCredentials credentials,
            Guid sessionActivityId,
            Uri managementServiceUri)
        {
            Version version;

            // If a version was specified (by tests) us it.
            if (sqlVersion == SqlVersion.v2)
            {
                version = new Version(11, 0);
            }
            else if (sqlVersion == SqlVersion.v12)
            {
                version = new Version(12, 0);
            }
            else // If no version specified, determine the version by querying the server.
            {
                version = GetVersion(manageUrl, credentials);
            }
            sqlVersion = SqlVersion.None;

            IServerDataServiceContext context = null;

            if (version.Major >= 12)
            {
                context = new TSqlConnectionContext(
                    sessionActivityId,
                    manageUrl.Host,
                    credentials,
                    serverName);
            }
            else
            {
                context = ServerDataServiceSqlAuth.Create(
                    managementServiceUri,
                    sessionActivityId,
                    credentials,
                    serverName);

                // Retrieve $metadata to verify model version compatibility
                XDocument metadata         = ((ServerDataServiceSqlAuth)context).RetrieveMetadata();
                XDocument filteredMetadata = DataConnectionUtility.FilterMetadataDocument(metadata);
                string    metadataHash     = DataConnectionUtility.GetDocumentHash(filteredMetadata);
                if (!((ServerDataServiceSqlAuth)context).metadataHashes.Any(knownHash => metadataHash == knownHash))
                {
                    cmdlet.WriteWarning(Resources.WarningModelOutOfDate);
                }

                ((ServerDataServiceSqlAuth)context).MergeOption = MergeOption.PreserveChanges;
            }

            return(context);
        }
Exemple #7
0
 /// <summary>
 /// Copies all the internal fields from one database object into another.
 /// </summary>
 /// <param name="other">The database to be copied.</param>
 internal void CopyFields(Database other)
 {
     this._CollationName = other._CollationName;
     this._CreationDate  = other._CreationDate;
     this._Edition       = other._Edition;
     this._Id            = other._Id;
     this._MaxSizeGB     = other._MaxSizeGB;
     this._Name          = other._Name;
     this._Server        = other._Server;
     this.Context        = other.Context;
 }
 /// <summary>
 /// Copies all the internal fields from one database object into another.
 /// </summary>
 /// <param name="other">The database to be copied.</param>
 internal void CopyFields(Database other)
 {
     this._CollationName = other._CollationName;
     this._CreationDate = other._CreationDate;
     this._Edition = other._Edition;
     this._Id = other._Id;
     this._MaxSizeGB = other._MaxSizeGB;
     this._Name = other._Name;
     this._Server = other._Server;
     this.Context = other.Context;
 }
 internal void LoadExtraProperties(IServerDataServiceContext context)
 {
     try
     {
         // Fill in the context property
         this.Context = context;
     }
     catch
     {
         // Ignore exceptions when loading extra properties, for backward compatibility.
     }
 }
Exemple #10
0
 internal void LoadExtraProperties(IServerDataServiceContext context)
 {
     try
     {
         // Fill in the context property
         this.Context = context;
     }
     catch
     {
         // Ignore exceptions when loading extra properties, for backward compatibility.
     }
 }
 /// <summary>
 /// Copies all the internal fields from one database object into another.
 /// </summary>
 /// <param name="other">The database to be copied.</param>
 internal void CopyFields(Database other)
 {
     this._CollationName = other._CollationName;
     this._CreationDate = other._CreationDate;
     this._Edition = other._Edition;
     this._Id = other._Id;
     this._MaxSizeGB = other._MaxSizeGB;
     this._MaxSizeBytes = other._MaxSizeBytes;
     this._Name = other._Name;
     this._Server = other._Server;
     this.Context = other.Context;
     this._AssignedServiceObjectiveId = other.AssignedServiceObjectiveId;
     this.ServiceObjective = other.ServiceObjective;
 }
 /// <summary>
 /// Copies all the internal fields from one database object into another.
 /// </summary>
 /// <param name="other">The database to be copied.</param>
 internal void CopyFields(Database other)
 {
     this._CollationName = other._CollationName;
     this._CreationDate  = other._CreationDate;
     this._Edition       = other._Edition;
     this._Id            = other._Id;
     this._MaxSizeGB     = other._MaxSizeGB;
     this._MaxSizeBytes  = other._MaxSizeBytes;
     this._Name          = other._Name;
     this._Server        = other._Server;
     this.Context        = other.Context;
     this._AssignedServiceObjectiveId = other.AssignedServiceObjectiveId;
     this.ServiceObjective            = other.ServiceObjective;
 }
        internal void LoadExtraProperties(IServerDataServiceContext context)
        {
            try
            {
                // Fill in the context property
                this.Context = context;

                // Fill in the service objective Dimension Settings
                this.Context.LoadProperty(this, "DimensionSettings");
            }
            catch
            {
                // Ignore exceptions when loading extra properties, for backward compatibility.
            }
        }
Exemple #14
0
        internal void LoadExtraProperties(IServerDataServiceContext context)
        {
            try
            {
                // Fill in the context property
                this.Context = context;

                // Fill in the service objective Dimension Settings
                this.Context.LoadProperty(this, "DimensionSettings");
            }
            catch
            {
                // Ignore exceptions when loading extra properties, for backward compatibility.
            }
        }
Exemple #15
0
        /// <summary>
        /// Process the command.
        /// </summary>
        public override void ExecuteCmdlet()
        {
            // Obtain the source server and database name from the given parameters.
            var sourceServerName =
                this.SourceDatabase != null ? this.SourceDatabase.ServerName :
                this.SourceServerName ??
                this.TargetServerName;

            var sourceDatabaseName =
                this.SourceDatabase != null ? this.SourceDatabase.Name :
                this.SourceDatabaseName;

            IServerDataServiceContext connectionContext = null;

            // If a database object was piped in, use its connection context...
            if (this.SourceDatabase != null)
            {
                connectionContext = this.SourceDatabase.Context;
            }
            else
            {
                // ... else create a temporary context
                connectionContext = ServerDataServiceCertAuth.Create(this.TargetServerName, WindowsAzureProfile.Instance.CurrentSubscription);
            }

            string clientRequestId = connectionContext.ClientRequestId;

            try
            {
                if (sourceDatabaseName != null)
                {
                    // Retrieve the database with the specified name and deletion date
                    this.WriteObject(connectionContext.GetRecoverableDatabase(sourceServerName, sourceDatabaseName));
                }
                else
                {
                    // No name specified, retrieve all restorable dropped databases in the server
                    this.WriteObject(connectionContext.GetRecoverableDatabases(sourceServerName), true);
                }
            }
            catch (Exception ex)
            {
                SqlDatabaseExceptionHandler.WriteErrorDetails(
                    this,
                    clientRequestId,
                    ex);
            }
        }
Exemple #16
0
        /// <summary>
        /// Execute the command.
        /// </summary>
        protected override void ProcessRecord()
        {
            IServerDataServiceContext context = null;

            switch (this.ParameterSetName)
            {
            case ByConnectionContext:
                context = this.Context;
                break;

            case ByServerName:
                context = ServerDataServiceCertAuth.Create(this.ServerName, WindowsAzureProfile.Instance.CurrentSubscription);
                break;
            }
            ProcessWithContext(context);
        }
Exemple #17
0
        /// <summary>
        /// Execute the command.
        /// </summary>
        public override void ExecuteCmdlet()
        {
            this.SourceDatabaseName =
                this.SourceDatabase != null ? this.SourceDatabase.Name :
                this.SourceDatabaseName;

            this.SourceServerName =
                this.SourceDatabase != null ? this.SourceDatabase.ServerName :
                this.SourceServerName;

            this.TargetDatabaseName = this.TargetDatabaseName ?? this.SourceDatabaseName;

            // Get the current subscription data
            var subscription = WindowsAzureProfile.Instance.CurrentSubscription;

            IServerDataServiceContext connectionContext = null;

            // If a database object was piped in, use its connection context...
            if (this.SourceDatabase != null)
            {
                connectionContext = this.SourceDatabase.Context;
            }
            else
            {
                // ... else create a temporary context
                connectionContext = ServerDataServiceCertAuth.Create(this.TargetServerName, subscription);
            }

            string clientRequestId = connectionContext.ClientRequestId;

            try
            {
                RecoverDatabaseOperation operation = connectionContext.RecoverDatabase(
                    this.SourceServerName,
                    this.SourceDatabaseName,
                    this.TargetDatabaseName);

                this.WriteObject(operation);
            }
            catch (Exception ex)
            {
                SqlDatabaseExceptionHandler.WriteErrorDetails(
                    this,
                    clientRequestId,
                    ex);
            }
        }
        /// <summary>
        /// Process the command.
        /// </summary>
        public override void ExecuteCmdlet()
        {
            ParameterValidation();
            IServerDataServiceContext context = null;

            switch (this.ParameterSetName)
            {
            case ByConnectionContext:
                context = this.ConnectionContext;
                break;

            case ByServerName:
                context = ServerDataServiceCertAuth.Create(this.ServerName, Profile, Profile.Context.Subscription);
                break;
            }
            ProcessWithContext(context);
        }
        /// <summary>
        /// Tries to copy the context into the database field.
        /// </summary>
        /// <param name="context">The context to store in the database object</param>
        internal void LoadExtraProperties(IServerDataServiceContext context)
        {
            try
            {
                // Fill in the context property
                this.Context = context;

                // Fill in the service objective properties
                this.Context.LoadProperty(this, "ServiceObjective");
                this.ServiceObjectiveName =
                    this.ServiceObjective == null ? null : this.ServiceObjective.Name;
            }
            catch
            {
                // Ignore exceptions when loading extra properties, for backward compatibility.
            }
        }
Exemple #20
0
        /// <summary>
        /// Tries to copy the context into the database field.
        /// </summary>
        /// <param name="context">The context to store in the database object</param>
        internal void LoadExtraProperties(IServerDataServiceContext context)
        {
            try
            {
                // Fill in the context property
                this.Context = context;

                // Fill in the service objective properties
                this.Context.LoadProperty(this, "ServiceObjective");
                this.ServiceObjectiveName =
                    this.ServiceObjective == null ? null : this.ServiceObjective.Name;
            }
            catch
            {
                // Ignore exceptions when loading extra properties, for backward compatibility.
            }
        }
        /// <summary>
        /// Execute the command.
        /// </summary>
        public override void ExecuteCmdlet()
        {
            // Obtain the database name from the given parameters.
            string databaseName = null;

            if (this.MyInvocation.BoundParameters.ContainsKey("Database"))
            {
                databaseName = this.Database.Name;
            }
            else if (this.MyInvocation.BoundParameters.ContainsKey("DatabaseName"))
            {
                databaseName = this.DatabaseName;
            }

            // Use the provided ServerDataServiceContext or create one from the
            // provided ServerName and the active subscription.
            IServerDataServiceContext context = ServerDataServiceCertAuth.Create(this.ServerName,
                                                                                 Profile,
                                                                                 Profile.Context.Subscription);

            try
            {
                if (this.MyInvocation.BoundParameters.ContainsKey("DatabaseCopy"))
                {
                    // Refresh the specified database copy object
                    this.WriteObject(context.GetDatabaseCopy(this.DatabaseCopy), true);
                }
                else
                {
                    // Retrieve all database copy object with matching parameters
                    DatabaseCopyModel[] copies = context.GetDatabaseCopy(
                        databaseName,
                        this.PartnerServer,
                        this.PartnerDatabase);
                    this.WriteObject(copies, true);
                }
            }
            catch (Exception ex)
            {
                SqlDatabaseExceptionHandler.WriteErrorDetails(
                    this,
                    context.ClientRequestId,
                    ex);
            }
        }
        /// <summary>
        /// Execute the command.
        /// </summary>
        public override void ExecuteCmdlet()
        {
            IServerDataServiceContext context = null;

            switch (this.ParameterSetName)
            {
            case ByConnectionContext:
                context = this.Context;
                break;

            case ByServerName:
                context = ServerDataServiceCertAuth.Create(this.ServerName, WindowsAzureProfile.Instance.CurrentSubscription);
                break;

            default:
                throw new InvalidPowerShellStateException("Unrecognized parameter set name used.");
            }
            ProcessWithContext(context);
        }
        /// <summary>
        /// Queries the server until the database assignment succeeds or there is an error.
        /// </summary>
        /// <param name="context">The context upon which to perform the action</param>
        /// <param name="response">The database object.</param>
        /// <returns>Returns the response from the server</returns>
        internal static Database WaitForDatabaseOperation(PSCmdlet cmdlet, IServerDataServiceContext context, Database response, string databaseName, bool isCreate)
        {
            // Duration to sleep: 2 second
            TimeSpan sleepDuration = TimeSpan.FromSeconds(2.0);

            // Poll for a maximum of 10 minutes;
            TimeSpan maximumPollDuration = TimeSpan.FromMinutes(10.0);

            // Text to display to the user while they wait.
            string pendingText   = "Pending";
            string textToDisplay = "";

            // Start the timer
            Stopwatch watch = Stopwatch.StartNew();

            while (watch.Elapsed < maximumPollDuration)
            {
                if (response == null)
                {
                    throw new Exception("An unexpected error occured. The response from the server was invalid, please try your request again.");
                }

                // Check to see if the database is ready for use.
                if ((isCreate && (response.Status != (int)DatabaseStatus.Creating)) || // The database is done being created
                    (!isCreate && (response.ServiceObjectiveAssignmentState != 0)))    // The database is done with SLO upgrade
                {
                    break;
                }

                // Wait before next poll.
                Thread.Sleep(sleepDuration);

                // Display that the status is pending and how long the operation has been waiting
                textToDisplay = string.Format("{0}: {1}", pendingText, watch.Elapsed.ToString("%s' sec.'"));
                cmdlet.WriteProgress(new ProgressRecord(0, "Waiting for database creation completion.", textToDisplay));

                // Poll the server for the database status.
                response = context.GetDatabase(databaseName);
            }

            return(response);
        }
        /// <summary>
        /// Queries the server until the database assignment succeeds or there is an error.
        /// </summary>
        /// <param name="context">The context upon which to perform the action</param>
        /// <param name="response">The database object.</param>
        /// <returns>Returns the response from the server</returns>
        internal static Database WaitForDatabaseOperation(PSCmdlet cmdlet, IServerDataServiceContext context, Database response, string databaseName, bool isCreate)
        {
            // Duration to sleep: 2 second
            TimeSpan sleepDuration = TimeSpan.FromSeconds(2.0);

            // Poll for a maximum of 10 minutes;
            TimeSpan maximumPollDuration = TimeSpan.FromMinutes(10.0);

            // Text to display to the user while they wait.
            string pendingText = "Pending";
            string textToDisplay = "";

            // Start the timer
            Stopwatch watch = Stopwatch.StartNew();

            while (watch.Elapsed < maximumPollDuration)
            {
                if (response == null)
                {
                    throw new Exception("An unexpected error occured. The response from the server was invalid, please try your request again.");
                }

                // Check to see if the database is ready for use.
                if ((isCreate && (response.Status != (int)DatabaseStatus.Creating)) || // The database is done being created
                    (!isCreate && (response.ServiceObjectiveAssignmentState != 0)))     // The database is done with SLO upgrade
                {
                    break;
                }

                // Wait before next poll.
                Thread.Sleep(sleepDuration);

                // Display that the status is pending and how long the operation has been waiting
                textToDisplay = string.Format("{0}: {1}", pendingText, watch.Elapsed.ToString("%s' sec.'"));
                cmdlet.WriteProgress(new ProgressRecord(0, "Waiting for database creation completion.", textToDisplay));

                // Poll the server for the database status.
                response = context.GetDatabase(databaseName);
            }

            return response;
        }
        /// <summary>
        /// Process the command.
        /// </summary>
        public override void ExecuteCmdlet()
        {
            IServerDataServiceContext context = null;

            switch (this.ParameterSetName)
            {
            case ByConnectionContext:
                context = this.ConnectionContext;
                break;

            case ByServerName:
                context = ServerDataServiceCertAuth.Create(this.ServerName, AzureSession.CurrentContext.Subscription);
                break;

            default:
                throw new NotSupportedException("ParameterSet");
            }

            ProcessWithContext(context);
        }
        /// <summary>
        /// Process the request using the provided connection context
        /// </summary>
        /// <param name="context">The connection context</param>
        private void ProcessWithContext(IServerDataServiceContext context)
        {
            // This is to enforce the mutual exclusivity of the parameters: Database
            // and DatabaseName.  This can't be done with parameter sets without changing
            // existing behaviour of the cmdlet.
            if (
                this.MyInvocation.BoundParameters.ContainsKey(DatabaseParameter) &&
                this.MyInvocation.BoundParameters.ContainsKey(DatabaseNameParameter))
            {
                this.WriteError(new ErrorRecord(
                    new PSArgumentException(
                        string.Format(Resources.InvalidParameterCombination, DatabaseParameter, DatabaseNameParameter)),
                    string.Empty,
                    ErrorCategory.InvalidArgument,
                    null));
            }

            // ... and similarly for RestorableDroppedDatabase and DatabaseName / DatabaseDeletionDate
            if (
                this.MyInvocation.BoundParameters.ContainsKey(RestorableDroppedDatabaseParameter) &&
                this.MyInvocation.BoundParameters.ContainsKey(DatabaseNameParameter))
            {
                this.WriteError(new ErrorRecord(
                    new PSArgumentException(
                        string.Format(Resources.InvalidParameterCombination, RestorableDroppedDatabaseParameter, DatabaseNameParameter)),
                    string.Empty,
                    ErrorCategory.InvalidArgument,
                    null));
            }
            if (
                this.MyInvocation.BoundParameters.ContainsKey(RestorableDroppedDatabaseParameter) &&
                this.MyInvocation.BoundParameters.ContainsKey(DatabaseDeletionDateParameter))
            {
                this.WriteError(new ErrorRecord(
                    new PSArgumentException(
                        string.Format(Resources.InvalidParameterCombination, RestorableDroppedDatabaseParameter, DatabaseDeletionDateParameter)),
                    string.Empty,
                    ErrorCategory.InvalidArgument,
                    null));
            }

            // The DatabaseDeletionDate parameter can only be used if the RestorableDropped switch is also present
            if (!this.RestorableDropped.IsPresent && this.MyInvocation.BoundParameters.ContainsKey(DatabaseDeletionDateParameter))
            {
                throw new PSArgumentException(
                    string.Format(Resources.RestorableDroppedSwitchNotSpecified, DatabaseDeletionDateParameter));
            }

            // The Database parameter can only be used if the RestorableDropped switch is not present
            if (this.RestorableDropped.IsPresent && this.MyInvocation.BoundParameters.ContainsKey(DatabaseParameter))
            {
                throw new PSArgumentException(
                    string.Format(Resources.InvalidParameterCombination, RestorableDroppedParameter, DatabaseParameter));
            }

            // If the RestorableDropped switch is present, then either both the DatabaseName and DatabaseDeletionDate parameters must be present, or neither of them should be present.
            if (
                this.RestorableDropped.IsPresent && (
                    (this.MyInvocation.BoundParameters.ContainsKey(DatabaseNameParameter) && !this.MyInvocation.BoundParameters.ContainsKey(DatabaseDeletionDateParameter)) ||
                    (!this.MyInvocation.BoundParameters.ContainsKey(DatabaseNameParameter) && this.MyInvocation.BoundParameters.ContainsKey(DatabaseDeletionDateParameter))))
            {
                throw new PSArgumentException(Resources.BothDatabaseNameAndDeletionDateNeedToBeSpecified);
            }

            // Obtain the database name from the given parameters.
            string databaseName = null;
            if (this.MyInvocation.BoundParameters.ContainsKey(DatabaseParameter))
            {
                databaseName = this.Database.Name;
            }
            else if (this.MyInvocation.BoundParameters.ContainsKey(RestorableDroppedDatabaseParameter))
            {
                databaseName = this.RestorableDroppedDatabase.Name;
            }
            else if (this.MyInvocation.BoundParameters.ContainsKey(DatabaseNameParameter))
            {
                databaseName = this.DatabaseName;
            }

            DateTime databaseDeletionDate = default(DateTime);
            if (this.MyInvocation.BoundParameters.ContainsKey(RestorableDroppedDatabaseParameter))
            {
                databaseDeletionDate = this.RestorableDroppedDatabase.DeletionDate;
            }
            else if (this.MyInvocation.BoundParameters.ContainsKey(DatabaseDeletionDateParameter))
            {
                databaseDeletionDate = this.DatabaseDeletionDate;
            }
            databaseDeletionDate = CmdletCommon.NormalizeToUtc(databaseDeletionDate);

            try
            {
                if (!this.RestorableDropped.IsPresent && this.RestorableDroppedDatabase == null)
                {
                    // Live databases

                    if (databaseName != null)
                    {
                        // Retrieve the database with the specified name
                        this.WriteObject(context.GetDatabase(databaseName), true);
                    }
                    else
                    {
                        // No name specified, retrieve all databases in the server
                        this.WriteObject(context.GetDatabases(), true);
                    }
                }

                else
                {
                    // Dropped databases

                    if (databaseName != null)
                    {
                        // Retrieve the database with the specified name
                        this.WriteObject(context.GetRestorableDroppedDatabase(databaseName, databaseDeletionDate), true);
                    }
                    else
                    {
                        // No name specified, retrieve all databases in the server
                        this.WriteObject(context.GetRestorableDroppedDatabases(), true);
                    }
                }
            }
            catch (Exception ex)
            {
                SqlDatabaseExceptionHandler.WriteErrorDetails(
                    this,
                    context.ClientRequestId,
                    ex);
            }
        }
        /// <summary>
        /// Execute the command.
        /// </summary>
        public override void ExecuteCmdlet()
        {
            // Obtain the database name from the given parameters.
            string databaseName = null;

            if (this.MyInvocation.BoundParameters.ContainsKey("Database"))
            {
                databaseName = this.Database.Name;
            }
            else if (this.MyInvocation.BoundParameters.ContainsKey("DatabaseName"))
            {
                databaseName = this.DatabaseName;
            }

            // Use the provided ServerDataServiceContext or create one from the
            // provided ServerName and the active subscription.
            IServerDataServiceContext context = ServerDataServiceCertAuth.Create(this.ServerName,
                                                                                 WindowsAzureProfile.Instance.CurrentSubscription);

            DatabaseCopyModel databaseCopy;

            if (this.MyInvocation.BoundParameters.ContainsKey("DatabaseCopy"))
            {
                // Refreshes the given copy object
                databaseCopy = context.GetDatabaseCopy(this.DatabaseCopy);
            }
            else
            {
                // Retrieve all database copy object with matching parameters
                DatabaseCopyModel[] copies = context.GetDatabaseCopy(
                    databaseName,
                    this.PartnerServer,
                    this.PartnerDatabase);
                if (copies.Length == 0)
                {
                    throw new ApplicationException(Resources.DatabaseCopyNotFoundGeneric);
                }
                else if (copies.Length > 1)
                {
                    throw new ApplicationException(Resources.MoreThanOneDatabaseCopyFound);
                }

                databaseCopy = copies.Single();
            }

            // Do nothing if force is not specified and user cancelled the operation
            string actionDescription = string.Format(
                CultureInfo.InvariantCulture,
                Resources.StopAzureSqlDatabaseCopyDescription,
                databaseCopy.SourceServerName,
                databaseCopy.SourceDatabaseName,
                databaseCopy.DestinationServerName,
                databaseCopy.DestinationDatabaseName);
            string actionWarning = string.Format(
                CultureInfo.InvariantCulture,
                Resources.StopAzureSqlDatabaseCopyWarning,
                databaseCopy.SourceServerName,
                databaseCopy.SourceDatabaseName,
                databaseCopy.DestinationServerName,
                databaseCopy.DestinationDatabaseName);

            this.WriteVerbose(actionDescription);
            if (!this.Force.IsPresent &&
                !this.ShouldProcess(
                    actionDescription,
                    actionWarning,
                    Resources.ShouldProcessCaption))
            {
                return;
            }

            try
            {
                // Stop the specified database copy
                context.StopDatabaseCopy(
                    databaseCopy,
                    this.ForcedTermination.IsPresent);
            }
            catch (Exception ex)
            {
                SqlDatabaseExceptionHandler.WriteErrorDetails(
                    this,
                    context.ClientRequestId,
                    ex);
            }
        }
Exemple #28
0
        /// <summary>
        /// Execute the command.
        /// </summary>
        public override void ExecuteCmdlet()
        {
            // Obtain the name of the source database / source restorable dropped database from the parameters
            this.SourceDatabaseName =
                this.SourceDatabase != null ? this.SourceDatabase.Name :
                this.SourceRestorableDroppedDatabase != null ? this.SourceRestorableDroppedDatabase.Name :
                this.SourceDatabaseName;

            // Obtain the deletion date of the source restorable dropped database from the parameters
            DateTime?sourceDatabaseDeletionDate = null;

            if (this.SourceRestorableDroppedDatabase != null)
            {
                sourceDatabaseDeletionDate = this.SourceRestorableDroppedDatabase.DeletionDate;
            }
            else if (this.RestorableDropped.IsPresent)
            {
                sourceDatabaseDeletionDate = this.SourceDatabaseDeletionDate;
            }

            // Normalize the deletion date and point in time to UTC, if given
            if (sourceDatabaseDeletionDate != null)
            {
                sourceDatabaseDeletionDate = CmdletCommon.NormalizeToUtc(sourceDatabaseDeletionDate.Value);
            }

            if (this.PointInTime != null)
            {
                this.PointInTime = CmdletCommon.NormalizeToUtc(this.PointInTime.Value);
            }

            IServerDataServiceContext connectionContext = null;

            // If a database object was piped in, use its connection context...
            if (this.SourceDatabase != null)
            {
                connectionContext = this.SourceDatabase.Context;
            }
            else if (this.SourceRestorableDroppedDatabase != null)
            {
                connectionContext = this.SourceRestorableDroppedDatabase.Context;
            }

            // ... but only if it's a cert auth context. Otherwise, create a cert auth context using this.ServerName or the server name of the SQL auth context.
            if (!(connectionContext is ServerDataServiceCertAuth))
            {
                string serverName = this.SourceServerName ?? connectionContext.ServerName;

                connectionContext = ServerDataServiceCertAuth.Create(serverName, Profile, Profile.Context.Subscription);
            }

            string clientRequestId = connectionContext.ClientRequestId;

            try
            {
                RestoreDatabaseOperation operation = connectionContext.RestoreDatabase(
                    this.SourceDatabaseName,
                    sourceDatabaseDeletionDate,
                    this.TargetServerName,
                    this.TargetDatabaseName,
                    this.PointInTime);

                this.WriteObject(operation);
            }
            catch (Exception ex)
            {
                SqlDatabaseExceptionHandler.WriteErrorDetails(
                    this,
                    clientRequestId,
                    ex);
            }
        }
 /// <summary>
 /// Process the request using the provided connection context
 /// </summary>
 /// <param name="databaseName">the name of the database to retrieve</param>
 private void ProcessWithContext(IServerDataServiceContext context)
 {
     string databaseName = GetDatabaseName();
     try
     {
         if (databaseName != null)
         {
             // Retrieve the database with the specified name
             this.WriteObject(context.GetDatabase(databaseName), true);
         }
         else
         {
             // No name specified, retrieve all databases in the server
             this.WriteObject(context.GetDatabases(), true);
         }
     }
     catch (Exception ex)
     {
         SqlDatabaseExceptionHandler.WriteErrorDetails(
             this,
             context.ClientRequestId,
             ex);
     }
 }
 private void ProcessWithContext(IServerDataServiceContext context)
 {
     try
     {
         if (this.ServiceObjectiveName != null)
         {
             // Retrieve the service objective with the specified name
             this.WriteObject(context.GetServiceObjective(this.ServiceObjectiveName));
         }
         else if (this.ServiceObjective != null)
         {
             // Retrieve the latest service objective with the specified service objective
             this.WriteObject(context.GetServiceObjective(this.ServiceObjective));
         }
         else
         {
             // No name specified, retrieve all service objectives in the server
             this.WriteObject(context.GetServiceObjectives(), true);
         }
     }
     catch (Exception ex)
     {
         SqlDatabaseExceptionHandler.WriteErrorDetails(
             this,
             context.ClientRequestId,
             ex);
     }
 }
 /// <summary>
 /// Process the request using the provided connection context
 /// </summary>
 /// <param name="context"></param>
 private void ProcessWithContext(IServerDataServiceContext context)
 {
     try
     {
         if (this.DatabaseName != null)
         {
             // Retrieve the operations with the specified database name
             this.WriteObject(context.GetDatabaseOperations(this.DatabaseName), true);
         }
         else if (this.Database != null)
         {
             // Retrieve the operations with the database name specified by the database object
             this.WriteObject(context.GetDatabaseOperations(this.Database.Name), true);
         }
         else if (this.OperationGuid != Guid.Empty)
         {
             // Retrieve the operation with the operation Guid
             this.WriteObject(context.GetDatabaseOperation(this.OperationGuid), true);
         }
         else
         {
             // No name specified, retrieve all database's operations in the server
             this.WriteObject(context.GetDatabasesOperations(), true);
         }
     }
     catch (Exception ex)
     {
         SqlDatabaseExceptionHandler.WriteErrorDetails(
             this,
             context.ClientRequestId,
             ex);
     }
 }
        /// <summary>
        /// Process the request using the provided connection context
        /// </summary>
        /// <param name="context">The connection context</param>
        private void ProcessWithContext(IServerDataServiceContext context)
        {
            // This is to enforce the mutual exclusivity of the parameters: Database
            // and DatabaseName.  This can't be done with parameter sets without changing
            // existing behaviour of the cmdlet.
            if (
                this.MyInvocation.BoundParameters.ContainsKey(DatabaseParameter) &&
                this.MyInvocation.BoundParameters.ContainsKey(DatabaseNameParameter))
            {
                this.WriteError(new ErrorRecord(
                                    new PSArgumentException(
                                        string.Format(Resources.InvalidParameterCombination, DatabaseParameter, DatabaseNameParameter)),
                                    string.Empty,
                                    ErrorCategory.InvalidArgument,
                                    null));
            }

            // ... and similarly for RestorableDroppedDatabase and DatabaseName / DatabaseDeletionDate
            if (
                this.MyInvocation.BoundParameters.ContainsKey(RestorableDroppedDatabaseParameter) &&
                this.MyInvocation.BoundParameters.ContainsKey(DatabaseNameParameter))
            {
                this.WriteError(new ErrorRecord(
                                    new PSArgumentException(
                                        string.Format(Resources.InvalidParameterCombination, RestorableDroppedDatabaseParameter, DatabaseNameParameter)),
                                    string.Empty,
                                    ErrorCategory.InvalidArgument,
                                    null));
            }
            if (
                this.MyInvocation.BoundParameters.ContainsKey(RestorableDroppedDatabaseParameter) &&
                this.MyInvocation.BoundParameters.ContainsKey(DatabaseDeletionDateParameter))
            {
                this.WriteError(new ErrorRecord(
                                    new PSArgumentException(
                                        string.Format(Resources.InvalidParameterCombination, RestorableDroppedDatabaseParameter, DatabaseDeletionDateParameter)),
                                    string.Empty,
                                    ErrorCategory.InvalidArgument,
                                    null));
            }

            // The DatabaseDeletionDate parameter can only be used if the RestorableDropped switch is also present
            if (!this.RestorableDropped.IsPresent && this.MyInvocation.BoundParameters.ContainsKey(DatabaseDeletionDateParameter))
            {
                throw new PSArgumentException(
                          string.Format(Resources.RestorableDroppedSwitchNotSpecified, DatabaseDeletionDateParameter));
            }

            // The Database parameter can only be used if the RestorableDropped switch is not present
            if (this.RestorableDropped.IsPresent && this.MyInvocation.BoundParameters.ContainsKey(DatabaseParameter))
            {
                throw new PSArgumentException(
                          string.Format(Resources.InvalidParameterCombination, RestorableDroppedParameter, DatabaseParameter));
            }

            // If the RestorableDropped switch is present, then either both the DatabaseName and DatabaseDeletionDate parameters must be present, or neither of them should be present.
            if (
                this.RestorableDropped.IsPresent && (
                    (this.MyInvocation.BoundParameters.ContainsKey(DatabaseNameParameter) && !this.MyInvocation.BoundParameters.ContainsKey(DatabaseDeletionDateParameter)) ||
                    (!this.MyInvocation.BoundParameters.ContainsKey(DatabaseNameParameter) && this.MyInvocation.BoundParameters.ContainsKey(DatabaseDeletionDateParameter))))
            {
                throw new PSArgumentException(Resources.BothDatabaseNameAndDeletionDateNeedToBeSpecified);
            }

            // Obtain the database name from the given parameters.
            string databaseName = null;

            if (this.MyInvocation.BoundParameters.ContainsKey(DatabaseParameter))
            {
                databaseName = this.Database.Name;
            }
            else if (this.MyInvocation.BoundParameters.ContainsKey(RestorableDroppedDatabaseParameter))
            {
                databaseName = this.RestorableDroppedDatabase.Name;
            }
            else if (this.MyInvocation.BoundParameters.ContainsKey(DatabaseNameParameter))
            {
                databaseName = this.DatabaseName;
            }

            DateTime databaseDeletionDate = default(DateTime);

            if (this.MyInvocation.BoundParameters.ContainsKey(RestorableDroppedDatabaseParameter))
            {
                databaseDeletionDate = this.RestorableDroppedDatabase.DeletionDate;
            }
            else if (this.MyInvocation.BoundParameters.ContainsKey(DatabaseDeletionDateParameter))
            {
                databaseDeletionDate = this.DatabaseDeletionDate;
            }
            databaseDeletionDate = CmdletCommon.NormalizeToUtc(databaseDeletionDate);

            try
            {
                if (!this.RestorableDropped.IsPresent && this.RestorableDroppedDatabase == null)
                {
                    // Live databases

                    if (databaseName != null)
                    {
                        // Retrieve the database with the specified name
                        this.WriteObject(context.GetDatabase(databaseName), true);
                    }
                    else
                    {
                        // No name specified, retrieve all databases in the server
                        this.WriteObject(context.GetDatabases(), true);
                    }
                }

                else
                {
                    // Dropped databases

                    if (databaseName != null)
                    {
                        // Retrieve the database with the specified name
                        this.WriteObject(context.GetRestorableDroppedDatabase(databaseName, databaseDeletionDate), true);
                    }
                    else
                    {
                        // No name specified, retrieve all databases in the server
                        this.WriteObject(context.GetRestorableDroppedDatabases(), true);
                    }
                }
            }
            catch (Exception ex)
            {
                SqlDatabaseExceptionHandler.WriteErrorDetails(
                    this,
                    context.ClientRequestId,
                    ex);
            }
        }
        /// <summary>
        /// Execute the command.
        /// </summary>
        public override void ExecuteCmdlet()
        {
            // Obtain the database name from the given parameters.
            string databaseName = null;

            if (this.MyInvocation.BoundParameters.ContainsKey("Database"))
            {
                databaseName = this.Database.Name;
            }
            else if (this.MyInvocation.BoundParameters.ContainsKey("DatabaseName"))
            {
                databaseName = this.DatabaseName;
            }

            string partnerServerName   = this.PartnerServer;
            string partnerDatabaseName = this.PartnerDatabase;

            if (this.ContinuousCopy.IsPresent)
            {
                // Default partnerDatabaseName to the only allowed value for continuous copies.
                partnerDatabaseName = partnerDatabaseName ?? databaseName;
            }
            else
            {
                // Default partnerServerName to the only allowed value for normal copies.
                partnerServerName = partnerServerName ?? this.ServerName;
            }

            // Do nothing if force is not specified and user cancelled the operation
            string actionDescription = string.Format(
                CultureInfo.InvariantCulture,
                Resources.StartAzureSqlDatabaseCopyDescription,
                this.ServerName,
                databaseName,
                partnerServerName,
                partnerDatabaseName);
            string actionWarning = string.Format(
                CultureInfo.InvariantCulture,
                Resources.StartAzureSqlDatabaseCopyWarning,
                this.ServerName,
                databaseName,
                partnerServerName,
                partnerDatabaseName);

            this.WriteVerbose(actionDescription);
            if (!this.Force.IsPresent &&
                !this.ShouldProcess(
                    actionDescription,
                    actionWarning,
                    Resources.ShouldProcessCaption))
            {
                return;
            }

            // Use the provided ServerDataServiceContext or create one from the
            // provided ServerName and the active subscription.
            IServerDataServiceContext context = ServerDataServiceCertAuth.Create(this.ServerName,
                                                                                 WindowsAzureProfile.Instance.CurrentSubscription);

            try
            {
                // Update the database with the specified name
                DatabaseCopyModel databaseCopy = context.StartDatabaseCopy(
                    databaseName,
                    partnerServerName,
                    partnerDatabaseName,
                    this.ContinuousCopy.IsPresent,
                    this.OfflineSecondary.IsPresent);

                this.WriteObject(databaseCopy, true);
            }
            catch (Exception ex)
            {
                SqlDatabaseExceptionHandler.WriteErrorDetails(
                    this,
                    context.ClientRequestId,
                    ex);
            }
        }