コード例 #1
0
        private RestoreParams CreateOptionsTestData()
        {
            RestoreParams optionValues = new RestoreParams();

            optionValues.Options.Add(RestoreOptionsHelper.CloseExistingConnections, false);
            optionValues.Options.Add(RestoreOptionsHelper.DataFileFolder, "Data file folder");
            optionValues.Options.Add("DbFiles", new List <DbFile>()
            {
                new DbFile("", '1', "")
            });
            optionValues.Options.Add("DefaultDataFileFolder", "Default data file folder");
            optionValues.Options.Add("DefaultLogFileFolder", "Default log file folder");
            optionValues.Options.Add("IsTailLogBackupPossible", true);
            optionValues.Options.Add("IsTailLogBackupWithNoRecoveryPossible", true);
            optionValues.Options.Add("GetDefaultStandbyFile", "default standby file");
            optionValues.Options.Add("GetDefaultTailLogbackupFile", "default tail log backup file");
            optionValues.Options.Add(RestoreOptionsHelper.LogFileFolder, "Log file folder");
            optionValues.Options.Add(RestoreOptionsHelper.RelocateDbFiles, true);
            optionValues.Options.Add("TailLogBackupFile", "tail log backup file");
            optionValues.Options.Add("TailLogWithNoRecovery", false);
            optionValues.Options.Add(RestoreOptionsHelper.BackupTailLog, false);
            optionValues.Options.Add(RestoreOptionsHelper.KeepReplication, false);
            optionValues.Options.Add(RestoreOptionsHelper.ReplaceDatabase, false);
            optionValues.Options.Add(RestoreOptionsHelper.SetRestrictedUser, false);
            optionValues.Options.Add(RestoreOptionsHelper.StandbyFile, "Stand by file");
            optionValues.Options.Add(RestoreOptionsHelper.RecoveryState, DatabaseRecoveryState.WithNoRecovery.ToString());
            optionValues.Options.Add(RestoreOptionsHelper.TargetDatabaseName, "target db name");
            optionValues.Options.Add(RestoreOptionsHelper.SourceDatabaseName, "source db name");
            optionValues.Options.Add("CanChangeTargetDatabase", true);
            optionValues.Options.Add("DefaultSourceDbName", "DefaultSourceDbName");
            optionValues.Options.Add("DefaultTargetDbName", "DefaultTargetDbName");
            optionValues.Options.Add("SourceDbNames", new List <string>());
            optionValues.Options.Add("CanDropExistingConnections", true);
            return(optionValues);
        }
コード例 #2
0
ファイル: NuGetViewModel.cs プロジェクト: phillijw/RoslynPad
        private static TargetFrameworkInformation CreateTargetFramework(RestoreParams restoreParameters)
        {
            var targetFramework = new TargetFrameworkInformation
            {
                FrameworkName = restoreParameters.TargetFramework
            };

            if (restoreParameters.TargetFramework.Framework == ".NETCoreApp")
            {
                targetFramework.Dependencies.Add(new LibraryDependency(
                                                     libraryRange: new LibraryRange("Microsoft.NETCore.App",
                                                                                    new VersionRange(restoreParameters.FrameworkVersion != null
                            ? new NuGetVersion(restoreParameters.FrameworkVersion)
                            : new NuGetVersion(restoreParameters.TargetFramework.Version)), LibraryDependencyTarget.Package),
                                                     type: LibraryDependencyType.Platform,
                                                     includeType: LibraryIncludeFlags.All,
                                                     suppressParent: LibraryIncludeFlags.All,
                                                     noWarn: Array.Empty <NuGetLogCode>(),
                                                     autoReferenced: true));
            }

            if (restoreParameters.Libraries != null)
            {
                foreach (var package in restoreParameters.Libraries)
                {
                    AddPackageToFramework(targetFramework, package);
                }
            }

            return(targetFramework);
        }
コード例 #3
0
        /// <summary>
        /// Handles a restore request
        /// </summary>
        internal async Task HandleRestorePlanRequest(
            RestoreParams restoreParams,
            RequestContext <RestorePlanResponse> requestContext)
        {
            RestorePlanResponse response = new RestorePlanResponse();

            try
            {
                ConnectionInfo connInfo;
                bool           supported = IsBackupRestoreOperationSupported(restoreParams, out connInfo);

                if (supported && connInfo != null)
                {
                    RestoreDatabaseTaskDataObject restoreDataObject = this.restoreDatabaseService.CreateRestoreDatabaseTaskDataObject(restoreParams);
                    response = this.restoreDatabaseService.CreateRestorePlanResponse(restoreDataObject);
                }
                else
                {
                    response.CanRestore   = false;
                    response.ErrorMessage = SR.RestoreNotSupported;
                }
                await requestContext.SendResult(response);
            }
            catch (Exception ex)
            {
                response.CanRestore   = false;
                response.ErrorMessage = ex.Message;
                await requestContext.SendResult(response);
            }
        }
コード例 #4
0
        public async Task CancelRestorePlanRequestShouldCancelSuccessfully()
        {
            await VerifyBackupFileCreated();

            using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
            {
                TestConnectionResult connectionResult = await LiveConnectionHelper.InitLiveConnectionInfoAsync("master", queryTempFile.FilePath);

                string filePath = GetBackupFilePath(fullBackupFilePath);

                RestoreParams restoreParams = new RestoreParams
                {
                    BackupFilePaths = filePath,
                    OwnerUri        = queryTempFile.FilePath
                };

                await RunAndVerify <RestorePlanResponse>(
                    test : (requestContext) => service.HandleRestorePlanRequest(restoreParams, requestContext),
                    verify : ((result) =>
                {
                    restoreParams.SessionId = result.SessionId;
                    Assert.True(result.DbFiles.Any());
                }));

                await RunAndVerify <bool>(
                    test : (requestContext) => service.HandleCancelRestorePlanRequest(restoreParams, requestContext),
                    verify : ((result) =>
                {
                    Assert.True(result);
                }));
            }
        }
コード例 #5
0
        /// <summary>
        /// Creates anew restore task object to do the restore operations
        /// </summary>
        /// <param name="restoreParams">Restore request parameters</param>
        /// <returns>Restore task object</returns>
        public RestoreDatabaseTaskDataObject CreateRestoreDatabaseTaskDataObject(RestoreParams restoreParams)
        {
            ConnectionInfo connInfo;

            DisasterRecoveryService.ConnectionServiceInstance.TryFindConnection(
                restoreParams.OwnerUri,
                out connInfo);

            if (connInfo != null)
            {
                SqlConnection         connection;
                DbConnection          dbConnection          = connInfo.AllConnections.First();
                ReliableSqlConnection reliableSqlConnection = dbConnection as ReliableSqlConnection;
                SqlConnection         sqlConnection         = dbConnection as SqlConnection;
                if (reliableSqlConnection != null)
                {
                    connection = reliableSqlConnection.GetUnderlyingConnection();
                }
                else if (sqlConnection != null)
                {
                    connection = sqlConnection;
                }
                else
                {
                    Logger.Write(LogLevel.Warning, "Cannot find any sql connection for restore operation");
                    return(null);
                }
                Server server = new Server(new ServerConnection(connection));

                RestoreDatabaseTaskDataObject restoreDataObject = new RestoreDatabaseTaskDataObject(server, restoreParams.DatabaseName);
                restoreDataObject.RestoreParams = restoreParams;
                return(restoreDataObject);
            }
            return(null);
        }
コード例 #6
0
        public static RestoreResult Restore(this Cloudinary cloudinary, params string[] publicIds)
        {
            var parameters = new RestoreParams();

            parameters.PublicIds.AddRange(publicIds);
            return(cloudinary.Restore(parameters));
        }
コード例 #7
0
        private bool IsBackupRestoreOperationSupported(RestoreParams restoreParams, out ConnectionInfo connectionInfo)
        {
            SqlConnection sqlConn = null;

            try
            {
                ConnectionInfo connInfo;
                DisasterRecoveryService.ConnectionServiceInstance.TryFindConnection(
                    restoreParams.OwnerUri,
                    out connInfo);

                if (connInfo != null)
                {
                    sqlConn = GetSqlConnection(connInfo);
                    if ((sqlConn != null) && !connInfo.IsSqlDW && !connInfo.IsAzure)
                    {
                        connectionInfo = connInfo;
                        return(true);
                    }
                }
            }
            catch
            {
                if (sqlConn != null)
                {
                    sqlConn.Close();
                }
            }
            connectionInfo = null;
            return(false);
        }
コード例 #8
0
ファイル: NuGetViewModel.cs プロジェクト: phillijw/RoslynPad
        private static ProjectRestoreMetadata CreateRestoreMetadata(RestoreParams restoreParameters)
        {
            var metadata = new ProjectRestoreMetadata
            {
                ProjectUniqueName        = restoreParameters.ProjectName,
                ProjectName              = restoreParameters.ProjectName,
                ProjectStyle             = ProjectStyle.PackageReference,
                ProjectPath              = restoreParameters.ProjectName,
                OutputPath               = restoreParameters.OutputPath,
                PackagesPath             = restoreParameters.PackagesPath,
                ValidateRuntimeAssets    = false,
                OriginalTargetFrameworks = { restoreParameters.TargetFramework.GetShortFolderName() }
            };

            foreach (var configPath in restoreParameters.ConfigFilePaths)
            {
                metadata.ConfigFilePaths.Add(configPath);
            }

            foreach (var source in restoreParameters.Sources)
            {
                metadata.Sources.Add(source);
            }

            return(metadata);
        }
コード例 #9
0
 public async Task <RestoreResult> RestoreAsync(RestoreParams parameters)
 {
     using (
         var response = await Api.CallAsync(HttpMethod.Post, Api.ApiUrlV.ResourceType("resources").Add(Api.GetCloudinaryParam(parameters.ResourceType)).Add("upload").Add("restore").BuildUrl(),
                                            parameters.ToParamsDictionary(), null, null))
     {
         return(await RestoreResult.Parse(response));
     }
 }
コード例 #10
0
        /// <summary>
        /// Handles a restore request
        /// </summary>
        internal async Task HandleRestoreRequest(
            RestoreParams restoreParams,
            RequestContext <RestoreResponse> requestContext)
        {
            RestoreResponse response = new RestoreResponse();

            try
            {
                ConnectionInfo connInfo;
                bool           supported = IsBackupRestoreOperationSupported(restoreParams, out connInfo);

                if (supported && connInfo != null)
                {
                    try
                    {
                        RestoreDatabaseTaskDataObject restoreDataObject = this.restoreDatabaseService.CreateRestoreDatabaseTaskDataObject(restoreParams);

                        if (restoreDataObject != null)
                        {
                            // create task metadata
                            TaskMetadata metadata = new TaskMetadata();
                            metadata.ServerName   = connInfo.ConnectionDetails.ServerName;
                            metadata.DatabaseName = connInfo.ConnectionDetails.DatabaseName;
                            metadata.Name         = SR.RestoreTaskName;
                            metadata.IsCancelable = true;
                            metadata.Data         = restoreDataObject;

                            // create restore task and perform
                            SqlTask sqlTask = SqlTaskManager.Instance.CreateAndRun(metadata, this.restoreDatabaseService.RestoreTaskAsync, restoreDatabaseService.CancelTaskAsync);
                            response.TaskId = sqlTask.TaskId.ToString();
                        }
                        else
                        {
                            response.ErrorMessage = SR.RestorePlanFailed;
                        }
                    }
                    catch (Exception ex)
                    {
                        response.ErrorMessage = ex.Message;
                    }
                }
                else
                {
                    response.ErrorMessage = SR.RestoreNotSupported;
                }

                await requestContext.SendResult(response);
            }
            catch (Exception ex)
            {
                response.Result       = false;
                response.ErrorMessage = ex.Message;
                await requestContext.SendResult(response);
            }
        }
コード例 #11
0
        /// <summary>
        /// Handles a restore request
        /// </summary>
        internal async Task HandleRestoreRequest(
            RestoreParams restoreParams,
            RequestContext <RestoreResponse> requestContext)
        {
            RestoreResponse response = new RestoreResponse();

            try
            {
                ConnectionInfo connInfo;
                bool           supported = IsBackupRestoreOperationSupported(restoreParams.OwnerUri, out connInfo);

                if (supported && connInfo != null)
                {
                    try
                    {
                        RestoreDatabaseTaskDataObject restoreDataObject = this.restoreDatabaseService.CreateRestoreDatabaseTaskDataObject(restoreParams, connInfo);

                        if (restoreDataObject != null)
                        {
                            restoreDataObject.LockedDatabaseManager = ConnectionServiceInstance.LockedDatabaseManager;
                            // create task metadata
                            TaskMetadata metadata = TaskMetadata.Create(restoreParams, SR.RestoreTaskName, restoreDataObject, ConnectionServiceInstance);
                            metadata.DatabaseName = restoreParams.TargetDatabaseName;

                            // create restore task and perform
                            SqlTask sqlTask = SqlTaskManagerInstance.CreateAndRun <SqlTask>(metadata);
                            response.TaskId = sqlTask.TaskId.ToString();
                        }
                        else
                        {
                            response.ErrorMessage = SR.RestorePlanFailed;
                        }
                    }
                    catch (Exception ex)
                    {
                        response.ErrorMessage = ex.Message;
                    }
                }
                else
                {
                    response.ErrorMessage = SR.RestoreNotSupported;
                }

                await requestContext.SendResult(response);
            }
            catch (Exception ex)
            {
                response.Result       = false;
                response.ErrorMessage = ex.Message;
                await requestContext.SendResult(response);
            }
        }
コード例 #12
0
        /// <summary>
        /// Creates anew restore task object to do the restore operations
        /// </summary>
        /// <param name="restoreParams">Restore request parameters</param>
        /// <returns>Restore task object</returns>
        public RestoreDatabaseTaskDataObject CreateRestoreDatabaseTaskDataObject(RestoreParams restoreParams)
        {
            RestoreDatabaseTaskDataObject restoreTaskObject = null;
            string sessionId = string.IsNullOrWhiteSpace(restoreParams.SessionId) ? Guid.NewGuid().ToString() : restoreParams.SessionId;

            if (!sessions.TryGetValue(sessionId, out restoreTaskObject))
            {
                restoreTaskObject = CreateRestoreForNewSession(restoreParams.OwnerUri, restoreParams.TargetDatabaseName);
                sessions.AddOrUpdate(sessionId, restoreTaskObject, (key, old) => restoreTaskObject);
            }
            restoreTaskObject.SessionId     = sessionId;
            restoreTaskObject.RestoreParams = restoreParams;

            return(restoreTaskObject);
        }
コード例 #13
0
        internal static async Task <RestoreResult> RestoreAsync(RestoreParams restoreParameters, ILogger logger, CancellationToken cancellationToken = default)
        {
            var providerCache = new RestoreCommandProvidersCache();

            using (var cacheContext = new SourceCacheContext())
            {
                cacheContext.NoCache             = false;
                cacheContext.IgnoreFailedSources = true;

                var providers = new List <IPreLoadedRestoreRequestProvider>();

                var dgSpec = new DependencyGraphSpec();
                dgSpec.AddRestore(restoreParameters.ProjectName);
                var projectSpec = new PackageSpec
                {
                    Name             = restoreParameters.ProjectName,
                    FilePath         = restoreParameters.ProjectName,
                    RestoreMetadata  = CreateRestoreMetadata(restoreParameters),
                    TargetFrameworks = { CreateTargetFramework(restoreParameters) }
                };
                dgSpec.AddProject(projectSpec);

                providers.Add(new DependencyGraphSpecRequestProvider(providerCache, dgSpec));

                var restoreContext = new RestoreArgs
                {
                    CacheContext              = cacheContext,
                    LockFileVersion           = LockFileFormat.Version,
                    DisableParallel           = false,
                    Log                       = logger,
                    MachineWideSettings       = new XPlatMachineWideSetting(),
                    PreLoadedRequestProviders = providers,
                    AllowNoOp                 = true,
                    HideWarningsAndErrors     = true
                };

                var restoreSummaries = await RestoreRunner.RunAsync(restoreContext, cancellationToken).ConfigureAwait(false);

                var result = new RestoreResult
                {
                    NoOp    = restoreSummaries.All(x => x.NoOpRestore),
                    Success = restoreSummaries.All(x => x.Success),
                    Errors  = restoreSummaries.SelectMany(x => x.Errors).Select(x => x.Message).ToImmutableArray()
                };

                return(result);
            }
        }
コード例 #14
0
        public void KeepReplicationShouldSetToValueInRequestGivenRecoveryStateWithRecovery()
        {
            RestoreParams restoreParams = CreateOptionsTestData();

            restoreParams.Options[RestoreOptionsHelper.RecoveryState] = DatabaseRecoveryState.WithRecovery;
            IRestoreDatabaseTaskDataObject             restoreDatabaseTaskDataObject = CreateRestoreDatabaseTaskDataObject(restoreParams);
            Dictionary <string, RestorePlanDetailInfo> options = RestoreOptionsHelper.CreateRestorePlanOptions(restoreDatabaseTaskDataObject);

            restoreParams.Options[RestoreOptionsHelper.KeepReplication] = true;
            RestoreOptionsHelper.UpdateOptionsInPlan(restoreDatabaseTaskDataObject);

            bool actual   = restoreDatabaseTaskDataObject.RestoreOptions.KeepReplication;
            bool expected = true;

            Assert.Equal(actual, expected);
        }
コード例 #15
0
        /// <summary>
        /// Handles a restore request
        /// </summary>
        internal async Task HandleCancelRestorePlanRequest(
            RestoreParams restoreParams,
            RequestContext <bool> requestContext)
        {
            bool result = false;

            try
            {
                result = this.restoreDatabaseService.CancelRestorePlan(restoreParams);
                await requestContext.SendResult(result);
            }
            catch (Exception ex)
            {
                Logger.Write(TraceEventType.Error, "Failed to cancel restore session. error: " + ex.Message);
                await requestContext.SendResult(result);
            }
        }
コード例 #16
0
        /// <summary>
        /// Cancels existing restore plan
        /// </summary>
        public bool CancelRestorePlan(RestoreParams restoreParams)
        {
            RestoreDatabaseTaskDataObject restoreTaskObject = null;
            string sessionId = restoreParams.SessionId;

            if (!string.IsNullOrEmpty(sessionId) && sessions.TryGetValue(sessionId, out restoreTaskObject))
            {
                ServerConnection connection = restoreTaskObject?.Server?.ConnectionContext;
                if (connection != null && connection.IsOpen)
                {
                    connection.Disconnect();
                }
                sessions.TryRemove(sessionId, out restoreTaskObject);
                return(true);
            }
            return(false);
        }
コード例 #17
0
        private async Task <RestorePlanResponse> VerifyRestore(string backupFileName, bool canRestore, bool execute = false, string targetDatabase = null)
        {
            string filePath = GetBackupFilePath(backupFileName);

            using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
            {
                TestConnectionResult connectionResult = await LiveConnectionHelper.InitLiveConnectionInfoAsync("master", queryTempFile.FilePath);

                RestoreDatabaseHelper service = new RestoreDatabaseHelper();
                var request = new RestoreParams
                {
                    BackupFilePath = filePath,
                    DatabaseName   = targetDatabase,
                    OwnerUri       = queryTempFile.FilePath
                };

                var restoreDataObject = service.CreateRestoreDatabaseTaskDataObject(request);
                var response          = service.CreateRestorePlanResponse(restoreDataObject);

                Assert.NotNull(response);
                Assert.Equal(response.CanRestore, canRestore);
                if (canRestore)
                {
                    Assert.True(response.DbFiles.Any());
                    if (string.IsNullOrEmpty(targetDatabase))
                    {
                        targetDatabase = response.DatabaseName;
                    }
                    Assert.Equal(response.DatabaseName, targetDatabase);

                    if (execute)
                    {
                        await DropDatabase(targetDatabase);

                        Thread.Sleep(2000);
                        request.RelocateDbFiles = response.RelocateFilesNeeded;
                        service.ExecuteRestore(restoreDataObject);
                        Assert.True(restoreDataObject.Server.Databases.Contains(targetDatabase));
                        await DropDatabase(targetDatabase);
                    }
                }

                return(response);
            }
        }
コード例 #18
0
        internal RestoreParams CreateRestoreParams()
        {
            var restoreParams = new RestoreParams();

            foreach (var packageSource in _packageSources)
            {
                restoreParams.Sources.Add(packageSource);
            }

            foreach (var configFile in _configFilePaths)
            {
                restoreParams.ConfigFilePaths.Add(configFile);
            }

            restoreParams.PackagesPath = GlobalPackageFolder;

            return(restoreParams);
        }
コード例 #19
0
        public void TargetDatabaseNameShouldBeWhatIsRequested2()
        {
            RestoreParams restoreParams = CreateOptionsTestData();
            string        defaultDbName = "default";
            string        currentDbName = "db3";

            restoreParams.Options["DefaultTargetDbName"] = defaultDbName;
            restoreParams.Options[RestoreOptionsHelper.TargetDatabaseName] = currentDbName;
            restoreParams.Options["CanChangeTargetDatabase"] = true;

            IRestoreDatabaseTaskDataObject restoreDatabaseTaskDataObject = CreateRestoreDatabaseTaskDataObject(restoreParams);

            RestoreOptionFactory.Instance.SetAndValidate(RestoreOptionsHelper.TargetDatabaseName, restoreDatabaseTaskDataObject);

            string actual   = restoreDatabaseTaskDataObject.TargetDatabaseName;
            string expected = currentDbName;

            Assert.Equal(actual, expected);
        }
コード例 #20
0
        public void SourceDatabaseNameShouldStayTheSameIfValid()
        {
            RestoreParams restoreParams = CreateOptionsTestData();
            string        defaultDbName = "default";
            string        currentDbName = "db3";

            restoreParams.Options["SourceDbNames"] = new List <string> {
                "db1", "db2", "db3"
            };
            restoreParams.Options["DefaultSourceDbName"] = defaultDbName;
            restoreParams.Options[RestoreOptionsHelper.SourceDatabaseName] = currentDbName;

            IRestoreDatabaseTaskDataObject restoreDatabaseTaskDataObject = CreateRestoreDatabaseTaskDataObject(restoreParams);

            RestoreOptionFactory.Instance.SetAndValidate(RestoreOptionsHelper.SourceDatabaseName, restoreDatabaseTaskDataObject);

            string actual   = restoreDatabaseTaskDataObject.SourceDatabaseName;
            string expected = currentDbName;

            Assert.Equal(actual, expected);
        }
コード例 #21
0
        /// <summary>
        /// Creates anew restore task object to do the restore operations
        /// </summary>
        /// <param name="restoreParams">Restore request parameters</param>
        /// <returns>Restore task object</returns>
        public RestoreDatabaseTaskDataObject CreateRestoreDatabaseTaskDataObject(RestoreParams restoreParams)
        {
            RestoreDatabaseTaskDataObject restoreTaskObject = null;

            if (!string.IsNullOrWhiteSpace(restoreParams.SessionId))
            {
                this.restoreSessions.TryGetValue(restoreParams.SessionId, out restoreTaskObject);
            }

            if (restoreTaskObject == null)
            {
                restoreTaskObject = CreateRestoreForNewSession(restoreParams);
                string sessionId = string.IsNullOrWhiteSpace(restoreParams.SessionId) ? Guid.NewGuid().ToString() : restoreParams.SessionId;
                this.restoreSessions.AddOrUpdate(sessionId, restoreTaskObject, (key, oldSession) => restoreTaskObject);
                restoreTaskObject.SessionId = sessionId;
            }
            else
            {
                restoreTaskObject.RestoreParams = restoreParams;
            }
            return(restoreTaskObject);
        }
コード例 #22
0
        public async Task RestorePlanRequestShouldReturnResponseWithDbFiles()
        {
            using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
            {
                TestConnectionResult connectionResult = await LiveConnectionHelper.InitLiveConnectionInfoAsync("master", queryTempFile.FilePath);

                string filePath = GetBackupFilePath("FullBackup.bak");

                RestoreParams restoreParams = new RestoreParams
                {
                    BackupFilePath = filePath,
                    OwnerUri       = queryTempFile.FilePath
                };

                await RunAndVerify <RestorePlanResponse>(
                    test : (requestContext) => service.HandleRestorePlanRequest(restoreParams, requestContext),
                    verify : ((result) =>
                {
                    Assert.True(result.DbFiles.Any());
                    Assert.Equal(result.DatabaseName, "BackupTestDb");
                }));
            }
        }
コード例 #23
0
        public async Task RestorePlanRequestShouldReturnErrorMessageGivenInvalidFilePath()
        {
            using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
            {
                TestConnectionResult connectionResult = await LiveConnectionHelper.InitLiveConnectionInfoAsync("master", queryTempFile.FilePath);

                string filePath = GetBackupFilePath("InvalidFilePath");

                RestoreParams restoreParams = new RestoreParams
                {
                    BackupFilePaths = filePath,
                    OwnerUri        = queryTempFile.FilePath
                };

                await RunAndVerify <RestorePlanResponse>(
                    test : (requestContext) => service.HandleRestorePlanRequest(restoreParams, requestContext),
                    verify : ((result) =>
                {
                    Assert.False(string.IsNullOrEmpty(result.ErrorMessage));
                    Assert.False(result.CanRestore);
                }));
            }
        }
コード例 #24
0
        public async Task RestoreDatabaseRequestShouldStartTheRestoreTask()
        {
            using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
            {
                TestConnectionResult connectionResult = await LiveConnectionHelper.InitLiveConnectionInfoAsync("master", queryTempFile.FilePath);

                string filePath = GetBackupFilePath("SomeFile.bak");

                RestoreParams restoreParams = new RestoreParams
                {
                    BackupFilePaths = filePath,
                    OwnerUri        = queryTempFile.FilePath
                };

                await RunAndVerify <RestoreResponse>(
                    test : (requestContext) => service.HandleRestoreRequest(restoreParams, requestContext),
                    verify : ((result) =>
                {
                    string taskId = result.TaskId;
                    var task = SqlTaskManager.Instance.Tasks.FirstOrDefault(x => x.TaskId.ToString() == taskId);
                    Assert.NotNull(task);
                }));
            }
        }
コード例 #25
0
        private async Task <RestorePlanResponse> VerifyRestore(
            string[] backupFileNames,
            bool canRestore,
            bool execute                         = false,
            string targetDatabase                = null,
            string[] selectedBackupSets          = null,
            Dictionary <string, object> options  = null,
            Func <Database, bool> verifyDatabase = null)
        {
            var    filePaths      = backupFileNames.Select(x => GetBackupFilePath(x));
            string backUpFilePath = filePaths.Aggregate((current, next) => current + " ," + next);


            using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
            {
                TestConnectionResult connectionResult = await LiveConnectionHelper.InitLiveConnectionInfoAsync("master", queryTempFile.FilePath);

                RestoreDatabaseHelper service = new RestoreDatabaseHelper();
                var request = new RestoreParams
                {
                    BackupFilePaths    = backUpFilePath,
                    TargetDatabaseName = targetDatabase,
                    OwnerUri           = queryTempFile.FilePath,
                    SelectedBackupSets = selectedBackupSets
                };

                if (options != null)
                {
                    foreach (var item in options)
                    {
                        if (!request.Options.ContainsKey(item.Key))
                        {
                            request.Options.Add(item.Key, item.Value);
                        }
                    }
                }

                var restoreDataObject = service.CreateRestoreDatabaseTaskDataObject(request);
                var response          = service.CreateRestorePlanResponse(restoreDataObject);

                Assert.NotNull(response);
                Assert.False(string.IsNullOrWhiteSpace(response.SessionId));
                Assert.Equal(response.CanRestore, canRestore);
                if (canRestore)
                {
                    Assert.True(response.DbFiles.Any());
                    if (string.IsNullOrEmpty(targetDatabase))
                    {
                        targetDatabase = response.DatabaseName;
                    }
                    Assert.Equal(response.DatabaseName, targetDatabase);
                    Assert.NotNull(response.PlanDetails);
                    Assert.True(response.PlanDetails.Any());
                    Assert.NotNull(response.PlanDetails[RestoreOptionsHelper.DefaultBackupTailLog]);
                    Assert.NotNull(response.PlanDetails[RestoreOptionsHelper.DefaultTailLogBackupFile]);
                    Assert.NotNull(response.PlanDetails[RestoreOptionsHelper.DefaultDataFileFolder]);
                    Assert.NotNull(response.PlanDetails[RestoreOptionsHelper.DefaultLogFileFolder]);
                    Assert.NotNull(response.PlanDetails[RestoreOptionsHelper.DefaultStandbyFile]);
                    Assert.NotNull(response.PlanDetails[RestoreOptionsHelper.DefaultStandbyFile]);

                    if (execute)
                    {
                        request.SessionId = response.SessionId;
                        restoreDataObject = service.CreateRestoreDatabaseTaskDataObject(request);
                        Assert.Equal(response.SessionId, restoreDataObject.SessionId);
                        request.RelocateDbFiles = !restoreDataObject.DbFilesLocationAreValid();
                        service.ExecuteRestore(restoreDataObject);
                        Assert.True(restoreDataObject.Server.Databases.Contains(targetDatabase));

                        if (verifyDatabase != null)
                        {
                            Assert.True(verifyDatabase(restoreDataObject.Server.Databases[targetDatabase]));
                        }

                        //To verify the backupset that are restored, verifying the database is a better options.
                        //Some tests still verify the number of backup sets that are executed which in some cases can be less than the selected list
                        if (verifyDatabase == null && selectedBackupSets != null)
                        {
                            Assert.Equal(selectedBackupSets.Count(), restoreDataObject.RestorePlanToExecute.RestoreOperations.Count());
                        }

                        await DropDatabase(targetDatabase);
                    }
                }

                return(response);
            }
        }
コード例 #26
0
 public static RestoreResult Restore(this Cloudinary cloudinary, RestoreParams parameters)
 {
     return(cloudinary.RestoreAsync(parameters).ExecSync());
 }
コード例 #27
0
        private async Task <RestorePlanResponse> VerifyRestore(
            string[] backupFileNames             = null,
            string sourceDbName                  = null,
            bool canRestore                      = true,
            TaskExecutionModeFlag executionMode  = TaskExecutionModeFlag.None,
            string targetDatabase                = null,
            string[] selectedBackupSets          = null,
            Dictionary <string, object> options  = null,
            Func <Database, bool> verifyDatabase = null,
            bool shouldFail                      = false)
        {
            string backUpFilePath = string.Empty;

            if (backupFileNames != null)
            {
                var filePaths = backupFileNames.Select(x => GetBackupFilePath(x));
                backUpFilePath = filePaths.Aggregate((current, next) => current + " ," + next);
            }

            using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
            {
                TestConnectionResult connectionResult = await LiveConnectionHelper.InitLiveConnectionInfoAsync("master", queryTempFile.FilePath);

                RestoreDatabaseHelper service = new RestoreDatabaseHelper();

                // If source database is sepecified verfiy it's part of source db list
                if (!string.IsNullOrEmpty(sourceDbName))
                {
                    RestoreConfigInfoResponse configInfoResponse = service.CreateConfigInfoResponse(new RestoreConfigInfoRequestParams
                    {
                        OwnerUri = queryTempFile.FilePath
                    });
                    IEnumerable <string> dbNames = configInfoResponse.ConfigInfo[RestoreOptionsHelper.SourceDatabaseNamesWithBackupSets] as IEnumerable <string>;
                    Assert.True(dbNames.Any(x => x == sourceDbName));
                }
                var request = new RestoreParams
                {
                    BackupFilePaths    = backUpFilePath,
                    TargetDatabaseName = targetDatabase,
                    OwnerUri           = queryTempFile.FilePath,
                    SelectedBackupSets = selectedBackupSets,
                    SourceDatabaseName = sourceDbName
                };
                request.Options[RestoreOptionsHelper.ReadHeaderFromMedia] = backupFileNames != null;

                if (options != null)
                {
                    foreach (var item in options)
                    {
                        if (!request.Options.ContainsKey(item.Key))
                        {
                            request.Options.Add(item.Key, item.Value);
                        }
                    }
                }

                var restoreDataObject = service.CreateRestoreDatabaseTaskDataObject(request);
                restoreDataObject.ConnectionInfo = connectionResult.ConnectionInfo;
                var response = service.CreateRestorePlanResponse(restoreDataObject);

                Assert.NotNull(response);
                Assert.False(string.IsNullOrWhiteSpace(response.SessionId));
                Assert.Equal(response.CanRestore, canRestore);
                if (canRestore)
                {
                    Assert.True(response.DbFiles.Any());
                    if (string.IsNullOrEmpty(targetDatabase))
                    {
                        targetDatabase = response.DatabaseName;
                    }
                    Assert.Equal(response.DatabaseName, targetDatabase);
                    Assert.NotNull(response.PlanDetails);
                    Assert.True(response.PlanDetails.Any());
                    Assert.NotNull(response.PlanDetails[RestoreOptionsHelper.BackupTailLog]);
                    Assert.NotNull(response.PlanDetails[RestoreOptionsHelper.TailLogBackupFile]);
                    Assert.NotNull(response.PlanDetails[RestoreOptionsHelper.DataFileFolder]);
                    Assert.NotNull(response.PlanDetails[RestoreOptionsHelper.LogFileFolder]);
                    Assert.NotNull(response.PlanDetails[RestoreOptionsHelper.StandbyFile]);
                    Assert.NotNull(response.PlanDetails[RestoreOptionsHelper.StandbyFile]);

                    if (executionMode != TaskExecutionModeFlag.None)
                    {
                        try
                        {
                            request.SessionId = response.SessionId;
                            restoreDataObject = service.CreateRestoreDatabaseTaskDataObject(request);
                            Assert.Equal(response.SessionId, restoreDataObject.SessionId);
                            request.RelocateDbFiles = !restoreDataObject.DbFilesLocationAreValid();
                            restoreDataObject.Execute((TaskExecutionMode)Enum.Parse(typeof(TaskExecutionMode), executionMode.ToString()));

                            if (executionMode.HasFlag(TaskExecutionModeFlag.Execute))
                            {
                                Assert.True(restoreDataObject.Server.Databases.Contains(targetDatabase));

                                if (verifyDatabase != null)
                                {
                                    Assert.True(verifyDatabase(restoreDataObject.Server.Databases[targetDatabase]));
                                }

                                //To verify the backupset that are restored, verifying the database is a better options.
                                //Some tests still verify the number of backup sets that are executed which in some cases can be less than the selected list
                                if (verifyDatabase == null && selectedBackupSets != null)
                                {
                                    Assert.Equal(selectedBackupSets.Count(), restoreDataObject.RestorePlanToExecute.RestoreOperations.Count());
                                }
                            }
                            if (executionMode.HasFlag(TaskExecutionModeFlag.Script))
                            {
                                Assert.False(string.IsNullOrEmpty(restoreDataObject.ScriptContent));
                            }
                        }
                        catch (Exception ex)
                        {
                            if (!shouldFail)
                            {
                                Assert.False(true, ex.Message);
                            }
                        }
                        finally
                        {
                            await DropDatabase(targetDatabase);
                        }
                    }
                }

                return(response);
            }
        }