/// <summary>
        /// Refreshes the given database copy object.
        /// </summary>
        /// <param name="databaseCopy">The object to refresh.</param>
        /// <returns>The refreshed database copy object.</returns>
        public DatabaseCopyModel GetDatabaseCopy(DatabaseCopyModel databaseCopy)
        {
            DatabaseCopy refreshedDatabaseCopy;

            using (new MergeOptionTemporaryChange(this, MergeOption.OverwriteChanges))
            {
                // Find the database copy by its keys
                refreshedDatabaseCopy = this.DatabaseCopies
                                        .Where(c => c.SourceServerName == databaseCopy.SourceServerName)
                                        .Where(c => c.SourceDatabaseName == databaseCopy.SourceDatabaseName)
                                        .Where(c => c.DestinationServerName == databaseCopy.DestinationServerName)
                                        .Where(c => c.DestinationDatabaseName == databaseCopy.DestinationDatabaseName)
                                        .SingleOrDefault();
                if (refreshedDatabaseCopy == null)
                {
                    throw new InvalidOperationException(
                              string.Format(
                                  CultureInfo.InvariantCulture,
                                  Resources.DatabaseCopyNotFound,
                                  databaseCopy.SourceServerName,
                                  databaseCopy.SourceDatabaseName,
                                  databaseCopy.DestinationServerName,
                                  databaseCopy.DestinationDatabaseName));
                }
            }

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

            return(CreateCopyModelFromCopy(refreshedDatabaseCopy));
        }
        /// <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;
            }
        }
        private DatabaseCopy GetCopyForCopyModel(DatabaseCopyModel model)
        {
            DatabaseCopy retval = this.DatabaseCopies.Where(copy => copy.EntityId == model.EntityId &&
                                                            model.IsLocalDatabaseReplicationTarget == copy.IsLocalDatabaseReplicationTarget)
                                  .SingleOrDefault();

            if (retval == null)
            {
                throw new ApplicationException(Resources.DatabaseCopyNotFoundGeneric);
            }

            return(retval);
        }
        /// <summary>
        /// Terminate an ongoing database copy operation.
        /// </summary>
        /// <param name="databaseCopy">The database copy to terminate.</param>
        /// <param name="forcedTermination"><c>true</c> to forcefully terminate the copy.</param>
        public void StopDatabaseCopy(
            DatabaseCopyModel databaseCopy,
            bool forcedTermination)
        {
            // Create a new request Id for this operation
            this.clientRequestId = SqlDatabaseCmdletBase.GenerateClientTracingId();

            // Get the SQL management client
            SqlManagementClient sqlManagementClient = AzureSession.ClientFactory.CreateClient<SqlManagementClient>(this.profile, subscription, AzureEnvironment.Endpoint.ServiceManagement);
            this.AddTracingHeaders(sqlManagementClient);

            // Get the local database, as it's the one we need to pass in.
            string localDatabaseName =
                databaseCopy.IsLocalDatabaseReplicationTarget
                    ? databaseCopy.DestinationDatabaseName
                    : databaseCopy.SourceDatabaseName;

            // Update forced termination so that the terminate happens
            // the way it should.
            sqlManagementClient.DatabaseCopies.Update(
                this.ServerName,
                localDatabaseName,
                databaseCopy.EntityId,
                new DatabaseCopyUpdateParameters() { IsForcedTerminate = forcedTermination });

            sqlManagementClient.DatabaseCopies.Delete(
                this.ServerName,
                localDatabaseName,
                databaseCopy.EntityId);
        }
        /// <summary>
        /// Refreshes the given database copy object.
        /// </summary>
        /// <param name="databaseCopy">The object to refresh.</param>
        /// <returns>The refreshed database copy object.</returns>
        public DatabaseCopyModel GetDatabaseCopy(DatabaseCopyModel databaseCopy)
        {
            this.clientRequestId = SqlDatabaseCmdletBase.GenerateClientTracingId();

            // Get the SQL management client
            SqlManagementClient sqlManagementClient = AzureSession.ClientFactory.CreateClient<SqlManagementClient>(this.profile, subscription, AzureEnvironment.Endpoint.ServiceManagement);
            this.AddTracingHeaders(sqlManagementClient);

            // Figure out which database is local, as that's the one we need to pass in.
            string localDatabaseName =
                databaseCopy.IsLocalDatabaseReplicationTarget
                    ? databaseCopy.DestinationDatabaseName
                    : databaseCopy.SourceDatabaseName;

            DatabaseCopyModel refreshedDatabaseCopy = CreateDatabaseCopyFromResponse(
                sqlManagementClient.DatabaseCopies.Get(
                    this.ServerName,
                    localDatabaseName,
                    databaseCopy.EntityId.ToString())
                    .DatabaseCopy);

            return refreshedDatabaseCopy;
        }
        /// <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,
                                                                                 Profile,
                                                                                 Profile.Context.Subscription);

            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);
            }
        }
        /// <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;
            }
        }
        /// <summary>
        /// Refreshes the given database copy object.
        /// </summary>
        /// <param name="databaseCopy">The object to refresh.</param>
        /// <returns>The refreshed database copy object.</returns>
        public DatabaseCopyModel GetDatabaseCopy(DatabaseCopyModel databaseCopy)
        {
            DatabaseCopy refreshedDatabaseCopy;

            using (new MergeOptionTemporaryChange(this, MergeOption.OverwriteChanges))
            {
                // Find the database copy by its keys
                refreshedDatabaseCopy = this.DatabaseCopies
                    .Where(c => c.SourceServerName == databaseCopy.SourceServerName)
                    .Where(c => c.SourceDatabaseName == databaseCopy.SourceDatabaseName)
                    .Where(c => c.DestinationServerName == databaseCopy.DestinationServerName)
                    .Where(c => c.DestinationDatabaseName == databaseCopy.DestinationDatabaseName)
                    .SingleOrDefault();
                if (refreshedDatabaseCopy == null)
                {
                    throw new InvalidOperationException(
                        string.Format(
                            CultureInfo.InvariantCulture,
                            Resources.DatabaseCopyNotFound,
                            databaseCopy.SourceServerName,
                            databaseCopy.SourceDatabaseName,
                            databaseCopy.DestinationServerName,
                            databaseCopy.DestinationDatabaseName));
                }
            }

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

            return CreateCopyModelFromCopy(refreshedDatabaseCopy);
        }
        private DatabaseCopy GetCopyForCopyModel(DatabaseCopyModel model)
        {
            DatabaseCopy retval = this.DatabaseCopies.Where(copy => copy.EntityId == model.EntityId
                && model.IsLocalDatabaseReplicationTarget == copy.IsLocalDatabaseReplicationTarget)
                .SingleOrDefault();

            if (retval == null)
            {
                throw new ApplicationException(Resources.DatabaseCopyNotFoundGeneric);
            }

            return retval;
        }