public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();
            ExecuteClientAction(() =>
            {
                if (ShouldProcess(this.Name, VerbsCommon.New))
                {
                    string resourceGroup                   = this.ResourceGroupName;
                    string restorePointName                = this.Name;
                    string restorePointCollectionName      = this.RestorePointCollectionName;
                    List <ApiEntityReference> disksExclude = new List <ApiEntityReference>();

                    RestorePoint restorePoint = new RestorePoint();
                    if (this.IsParameterBound(c => c.DisksToExclude))
                    {
                        foreach (string s in DisksToExclude)
                        {
                            disksExclude.Add(new ApiEntityReference(s));
                        }
                        restorePoint.ExcludeDisks = disksExclude;
                        var result   = RestorePointClient.Create(resourceGroup, restorePointCollectionName, restorePointName, restorePoint);
                        var psObject = new PSRestorePoint();
                        ComputeAutomationAutoMapperProfile.Mapper.Map <RestorePoint, PSRestorePoint>(result, psObject);
                        WriteObject(psObject);
                    }
                    else
                    {
                        var result   = RestorePointClient.Create(resourceGroup, restorePointCollectionName, restorePointName, restorePoint);
                        var psObject = new PSRestorePoint();
                        ComputeAutomationAutoMapperProfile.Mapper.Map <RestorePoint, PSRestorePoint>(result, psObject);
                        WriteObject(psObject);
                    }
                }
            });
        }
Esempio n. 2
0
        public bool IsWithin(RestorePoint rp)
        {
            if (_cleaners.Count == 1)
            {
                return(_cleaners[0].IsWithin(rp));
            }

            if (_cleaners.Count == 0)
            {
                return(true);
            }

            if (_typeOfHybrid)
            {
                bool result = true;
                foreach (var cleaner in _cleaners)
                {
                    result &= cleaner.IsWithin(rp);
                }

                return(result);
            }
            else
            {
                bool result = false;
                foreach (var cleaner in _cleaners)
                {
                    result = result || cleaner.IsWithin(rp);
                }

                return(result);
            }
        }
        // Verify restore point properties.
        // Verify disk exclusion by verifying that the returned restore point contains the id of the
        // excluded disk in 'ExcludeDisks' property and did not create diskRestorePoint
        // of the excluded data disk.
        // For RestorePoint created via cross-region copy scenario, sourceRestorePoint.Id is verified.
        // For GET instance view of RestorePoint created via cross-region copy scenario, instanceView is verified.
        void VerifyRestorePointDetails(RestorePoint restorePoint, string restorePointName, OSDisk osDisk,
                                       int excludeDisksCount, string excludeDiskId, string vmSize, bool isRemoteCopy = false, string sourceRestorePointId = null,
                                       bool isRemoteCopyInstanceView = false)
        {
            Assert.Equal(restorePointName, restorePoint.Name);
            Assert.NotNull(restorePoint.Id);
            Assert.Equal(ProvisioningState.Succeeded.ToString(), restorePoint.ProvisioningState);
            Assert.Equal(ConsistencyModeTypes.ApplicationConsistent, restorePoint.ConsistencyMode);
            RestorePointSourceVMStorageProfile storageProfile = restorePoint.SourceMetadata.StorageProfile;

            Assert.Equal(osDisk.Name, storageProfile.OsDisk.Name, ignoreCase: true);
            Assert.Equal(osDisk.ManagedDisk.Id, storageProfile.OsDisk.ManagedDisk.Id, ignoreCase: true);
            Assert.NotNull(restorePoint.SourceMetadata.VmId);
            Assert.Equal(vmSize, restorePoint.SourceMetadata.HardwareProfile.VmSize);
            if (isRemoteCopy)
            {
                Assert.Equal(sourceRestorePointId, restorePoint.SourceRestorePoint.Id);
                if (isRemoteCopyInstanceView)
                {
                    RestorePointInstanceView restorePointInstanceView = restorePoint.InstanceView;
                    Assert.NotNull(restorePointInstanceView);
                    Assert.Equal(storageProfile.DataDisks.Count + 1, restorePointInstanceView.DiskRestorePoints.Count);
                    Assert.NotNull(restorePointInstanceView.DiskRestorePoints[0].ReplicationStatus.CompletionPercent);
                }
            }
            else
            {
                Assert.Equal(excludeDisksCount, restorePoint.ExcludeDisks.Count);
                Assert.Equal(excludeDiskId, restorePoint.ExcludeDisks[0].Id, ignoreCase: true);
            }
        }
Esempio n. 4
0
        public RestorePoint Clean(RestorePoint lastPoint, out bool areMorePointsLeft)
        {
            areMorePointsLeft = false;
            var          point       = lastPoint;
            RestorePoint prevPoint   = null;
            long         currentSize = 0;

            while (point != null && (currentSize < MaxSize || point is IncrementalBackupPoint))
            {
                if (point.Size() + currentSize <= MaxSize || point is IncrementalBackupPoint)
                {
                    currentSize += point.Size();
                    prevPoint    = point;
                    point        = point.PreviousPoint;
                    continue;
                }
                break;
            }

            if (prevPoint != null)
            {
                prevPoint.PreviousPoint = null;
            }

            if (currentSize > MaxSize)
            {
                areMorePointsLeft = true;
            }

            return(lastPoint);
        }
Esempio n. 5
0
        public void testScanner3()
        {
            var source           = @"#if XXX
class
#else
interface
#endif
C {
}
";
            var codeErrorManager = new CodeErrorManager();
            var preprocessor     = new Preprocessor(codeErrorManager, source.toCharArray());
            var scanner          = new PreprocessedTextScanner(codeErrorManager, preprocessor.preprocess());

            Assert.assertEquals(LexicalUnit.Keyword, scanner.nextLexicalUnit());
            RestorePoint rp = scanner.createRestorePoint();

            Assert.assertEquals(LexicalUnit.NewLine, scanner.nextLexicalUnit());
            Assert.assertEquals(LexicalUnit.Identifier, scanner.nextLexicalUnit());
            Assert.assertEquals(LexicalUnit.Whitespace, scanner.nextLexicalUnit());
            Assert.assertEquals(LexicalUnit.OpenBrace, scanner.nextLexicalUnit());
            Assert.assertEquals(LexicalUnit.NewLine, scanner.nextLexicalUnit());
            scanner.restore(rp);
            Assert.assertEquals(LexicalUnit.Keyword, scanner.nextLexicalUnit());
            Assert.assertEquals("interface", new String(scanner.Text, scanner.StartPosition, scanner.EndPosition - scanner.StartPosition));
            Assert.assertEquals(LexicalUnit.NewLine, scanner.nextLexicalUnit());
            Assert.assertEquals(LexicalUnit.Identifier, scanner.nextLexicalUnit());
            Assert.assertEquals(LexicalUnit.Whitespace, scanner.nextLexicalUnit());
            Assert.assertEquals(LexicalUnit.OpenBrace, scanner.nextLexicalUnit());
            Assert.assertEquals(LexicalUnit.NewLine, scanner.nextLexicalUnit());
            Assert.assertEquals(LexicalUnit.CloseBrace, scanner.nextLexicalUnit());
            Assert.assertEquals(LexicalUnit.NewLine, scanner.nextLexicalUnit());
            Assert.assertEquals(LexicalUnit.EndOfStream, scanner.nextLexicalUnit());
        }
        // Create restore point and exercise 'ExcludeDisk' functionality by excluding dataDisk.
        private RestorePoint CreateRestorePoint(string rgName, string rpcName,
                                                string rpName, string diskToExclude, string sourceRestorePointId)
        {
            RestorePoint inputRestorePoint = new RestorePoint();

            if (diskToExclude != null)
            {
                ApiEntityReference diskToExcludeEntityRef = new ApiEntityReference()
                {
                    Id = diskToExclude
                };
                List <ApiEntityReference> disksToExclude = new List <ApiEntityReference> {
                    diskToExcludeEntityRef
                };
                inputRestorePoint.ExcludeDisks = disksToExclude;
            }

            if (sourceRestorePointId != null)
            {
                inputRestorePoint.SourceRestorePoint = new ApiEntityReference()
                {
                    Id = sourceRestorePointId
                };
            }

            return(m_CrpClient.RestorePoints.Create(rgName, rpcName, rpName, inputRestorePoint));
        }
Esempio n. 7
0
 public PSRestorePoint(RestorePoint restorePoint)
 {
     this.Location                 = restorePoint.Location;
     this.RestorePointType         = restorePoint.RestorePointType;
     this.EarliestRestoreDate      = restorePoint.EarliestRestoreDate;
     this.RestorePointCreationDate = restorePoint.RestorePointCreationDate;
     this.RestorePointLabel        = restorePoint.RestorePointLabel;
 }
Esempio n. 8
0
        public bool IsRemovable(Backup backup, RestorePoint restorePoint)
        {
            int pos = backup.RestorePoints.IndexOf(restorePoint);

            if (backup.RestorePoints.Count > 1 && backup.RestorePoints[pos + 1] is IncRestorePoint)
            {
                return(false);
            }

            return(true);
        }
Esempio n. 9
0
        public RestorePoint restorePoint;       //if it's a Save and Exit situation, player given option to return to game after saving. This tells where to return to. Optional

        public ModalConfirmDetails()
        {
            bottomText   = "Are you sure?";
            buttonFalse  = "No";
            buttonTrue   = "Yes";
            modalLevel   = 1;
            modalState   = ModalSubState.None;
            eventFalse   = EventType.None;
            eventTrue    = EventType.None;
            restorePoint = RestorePoint.None;
        }
Esempio n. 10
0
        public void CreateLocalRestorePointWithSecurityProfile()
        {
            string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION");

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                string location = "southcentralus";
                Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", location);
                EnsureClientsInitialized(context);
                var            rgName   = ComputeManagementTestUtilities.GenerateName(TestPrefix);
                ImageReference imageRef = new ImageReference(publisher: "MICROSOFTWINDOWSDESKTOP", offer: "WINDOWS-10", version: "latest", sku: "20H2-ENT-G2");
                VirtualMachine inputVM;
                string         storageAccountForDisks = TestUtilities.GenerateName(TestPrefix);
                string         availabilitySetName    = TestUtilities.GenerateName(TestPrefix);

                try
                {
                    // PUT VM with SecurityType = TrustedLaunch
                    VirtualMachine createdVM = CreateVM(rgName, availabilitySetName, storageAccountForDisks, imageRef, out inputVM, hasManagedDisks: true,
                                                        vmSize: VirtualMachineSizeTypes.StandardD2sV3, securityType: "TrustedLaunch");

                    string rpcName = ComputeManagementTestUtilities.GenerateName("rpcClientTest");
                    string rpName  = ComputeManagementTestUtilities.GenerateName("rpClientTest");

                    // Create Restore Point Collection
                    string vmId   = createdVM.Id;
                    string vmSize = createdVM.HardwareProfile.VmSize;
                    Dictionary <string, string> tags = new Dictionary <string, string>()
                    {
                        { "testTag", "testTagValue" }
                    };
                    RestorePointCollection createdRpc = CreateRpc(vmId, rpcName, rgName, location, tags);

                    // Create Restore Point
                    RestorePoint createdRP = CreateRestorePoint(rgName, rpcName, rpName, diskToExclude: null, sourceRestorePointId: null);

                    // GET Disk Restore Point
                    IPage <DiskRestorePoint> listDiskRestorePoint = m_CrpClient.DiskRestorePoint.ListByRestorePoint(rgName, rpcName, rpName);
                    var getDrp = m_CrpClient.DiskRestorePoint.Get(rgName, rpcName, rpName, listDiskRestorePoint.First().Name);

                    Assert.Equal("TrustedLaunch", getDrp.SecurityProfile.SecurityType);
                }
                catch (Exception e)
                {
                    throw e;
                }
                finally
                {
                    m_ResourcesClient.ResourceGroups.Delete(rgName);
                    Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation);
                }
            }
        }
        public long CountLeftPoints(RestorePoint lastPoint)
        {
            var k     = LastNPoints - 1;
            var point = lastPoint;

            while (point != null && (k > 0 || point is IncrementalBackupPoint))
            {
                point = point.PreviousPoint;
                --k;
            }

            return(LastNPoints - k);
        }
Esempio n. 12
0
        public void SeparateStorageTest()
        {
            Backup backup = new Backup(new SeparateStorageAlgorithm(), new CountCleanAlgorithm(1), _fileRepository, new DateTimeProvider());

            backup.Add(_files[0].Path);
            backup.Add(_files[1].Path);
            backup.CreateRestorePoint(RestoreType.Full);

            RestorePoint restorePoint = backup.RestorePoints.First();

            Assert.That(restorePoint.StorageAlgorithmType, Is.EqualTo(StorageAlgorithmType.Separate));
            Assert.That(_archiveWrites, Is.EqualTo(0));
            Assert.That(_separateWrites, Is.EqualTo(2));
        }
Esempio n. 13
0
    /// <summary>
    /// AutoSave file (TurnManager.cs -> ProcessNewTurn)
    /// </summary>
    public void ProcessAutoSave(GameState state, RestorePoint restore = RestorePoint.None)
    {
        //Debug -> time load game process
        GameManager.i.testScript.StartTimer();
        GameManager.i.fileScript.WriteSaveData(new LoadGameState()
        {
            gameState = state, restorePoint = restore
        }, SaveType.AutoSave);
        GameManager.i.fileScript.SaveGame(SaveType.AutoSave, true);
        //how long did it take?
        long timeElapsed = GameManager.i.testScript.StopTimer();

        Debug.LogFormat("[Per] ControlManager.cs -> ProcessSaveGame: SAVE GAME took {0} ms", timeElapsed);
    }
Esempio n. 14
0
        public bool IsWithin(RestorePoint rp)
        {
            if (rp.GetType() == 1)
            {
                return(true);
            }
            var length = 0;

            while (rp != null)
            {
                length++;
                rp = rp.GetDepend();
            }

            return(length <= _count);
        }
Esempio n. 15
0
        public void IncrementTest()
        {
            Backup backup = new Backup(new SeparateStorageAlgorithm(), new CountCleanAlgorithm(1), _fileRepository, new DateTimeProvider());

            backup.Add(_files[0].Path);
            backup.Add(_files[1].Path);
            backup.CreateRestorePoint(RestoreType.Full);
            backup.Add(_files[2].Path);
            backup.CreateRestorePoint(RestoreType.Increment);

            RestorePoint restorePoint = backup.RestorePoints.Last();

            Assert.That(restorePoint.RestoreType, Is.EqualTo(RestoreType.Increment));
            Assert.That(restorePoint.Files.Count, Is.EqualTo(1));
            Assert.That(_separateWrites, Is.EqualTo(3));
        }
        // Verify restore point properties.
        // Verify disk exclusion by verifying that the returned restore point contains the id of the
        // excluded disk in 'ExcludeDisks' property and did not create diskRestorePoint
        // of the excluded data disk.
        void VerifyRestorePointDetails(RestorePoint restorePoint, string restorePointName, OSDisk osDisk,
                                       int excludeDisksCount, string excludeDiskId, string vmSize)
        {
            Assert.Equal(restorePointName, restorePoint.Name);
            Assert.NotNull(restorePoint.Id);
            Assert.Equal(ProvisioningState.Succeeded.ToString(), restorePoint.ProvisioningState);
            Assert.Equal(ConsistencyModeTypes.ApplicationConsistent, restorePoint.ConsistencyMode);
            RestorePointSourceVMStorageProfile storageProfile = restorePoint.SourceMetadata.StorageProfile;

            Assert.Equal(osDisk.Name, storageProfile.OsDisk.Name, ignoreCase: true);
            Assert.Equal(osDisk.ManagedDisk.Id, storageProfile.OsDisk.ManagedDisk.Id, ignoreCase: true);
            Assert.Equal(excludeDisksCount, restorePoint.ExcludeDisks.Count);
            Assert.Equal(excludeDiskId, restorePoint.ExcludeDisks[0].Id, ignoreCase: true);
            Assert.NotNull(restorePoint.SourceMetadata.VmId);
            Assert.Equal(vmSize, restorePoint.SourceMetadata.HardwareProfile.VmSize);
        }
Esempio n. 17
0
        private void PopulateApplicationServiceAndPartitionInfo(RestorePoint recoveryPoint, string metadataFile)
        {
            var tokens       = metadataFile.Split('/');
            var tokensLength = tokens.Length;

            if (tokensLength >= 4)
            {
                var partitionIdStr     = tokens[tokensLength - 2];
                var serviceNameStr     = tokens[tokensLength - 3];
                var applicationNameStr = tokens[tokensLength - 4];

                recoveryPoint.PartitionInformation.Id = Guid.Parse(partitionIdStr);
                recoveryPoint.ApplicationName         = new Uri(String.Format("fabric:/{0}", UtilityHelper.GetUriFromCustomUri(applicationNameStr)));
                recoveryPoint.ServiceName             =
                    new Uri(String.Format("{0}/{1}", recoveryPoint.ApplicationName, UtilityHelper.GetUriFromCustomUri(serviceNameStr)));
            }
        }
        void DoThisOnTaskFaulted(Task <List <RestorePoint> > faultedTask, List <RestorePoint> restorePoints, ref bool isSuccess)
        {
            // Only updating restorePoints[0] everytime to have the error.
            isSuccess = false;
            AggregateException aggregateException = faultedTask.Exception as AggregateException;

            if (aggregateException != null)
            {
                foreach (var exception in aggregateException.InnerExceptions)
                {
                    lock (restorePoints)
                    {
                        restorePoints[0] =
                            new RestorePoint
                                ()
                        {
                            FailureError =
                                new FabricError()
                            {
                                Code    = (NativeTypes.FABRIC_ERROR_CODE)faultedTask.Exception.HResult,
                                Message = exception.Message
                            }
                        };
                    }
                }
            }
            else if (faultedTask.Exception != null)
            {
                lock (restorePoints)
                {
                    restorePoints[0] =
                        new RestorePoint
                            ()
                    {
                        FailureError =
                            new FabricError()
                        {
                            Code =
                                (NativeTypes.FABRIC_ERROR_CODE)faultedTask.Exception.HResult,
                            Message = faultedTask.Exception.Message
                        }
                    };
                }
            }
        }
Esempio n. 19
0
        private async Task <List <RestorePoint> > GetRecoveryPointDetailsInternalAsync(IEnumerable <string> metadataFiles, CancellationToken cancellationToken)
        {
            var backupList = new List <RestorePoint>();

            foreach (var metadataFile in metadataFiles)
            {
                cancellationToken.ThrowIfCancellationRequested();

                using (MemoryStream ms = new MemoryStream())
                {
                    CloudBlockBlob blockBlob = AzureBlobStoreHelper.GetCloudBlockBlobRef(this.container, metadataFile);
                    await AzureBlobStoreHelper.DownloadToStreamAsync(blockBlob, ms, cancellationToken);

                    var recoveryPointMetadataFile =
                        await RecoveryPointMetadataFile.OpenAsync(ms, metadataFile, cancellationToken);

                    var recoveryPoint = new RestorePoint()
                    {
                        BackupChainId        = recoveryPointMetadataFile.BackupChainId,
                        BackupId             = recoveryPointMetadataFile.BackupId,
                        ParentRestorePointId = recoveryPointMetadataFile.ParentBackupId,
                        BackupLocation       = recoveryPointMetadataFile.BackupLocation,
                        CreationTimeUtc      = recoveryPointMetadataFile.BackupTime,
                        BackupType           =
                            recoveryPointMetadataFile.ParentBackupId == Guid.Empty ? BackupOptionType.Full : BackupOptionType.Incremental,
                        EpochOfLastBackupRecord = new BackupEpoch
                        {
                            ConfigurationNumber = recoveryPointMetadataFile.EpochOfLastBackupRecord.ConfigurationNumber,
                            DataLossNumber      = recoveryPointMetadataFile.EpochOfLastBackupRecord.DataLossNumber
                        },
                        LsnOfLastBackupRecord  = recoveryPointMetadataFile.LsnOfLastBackupRecord,
                        PartitionInformation   = this.GetBackupServicePartitionInformationFromServicePartitionInformation(recoveryPointMetadataFile.PartitionInformation),
                        ServiceManifestVersion = recoveryPointMetadataFile.ServiceManifestVersion,
                    };

                    PopulateApplicationServiceAndPartitionInfo(recoveryPoint, metadataFile);

                    backupList.Add(recoveryPoint);
                }
            }

            return(backupList);
        }
        // Create restore point and exercise 'ExcludeDisk' functionality by excluding dataDisk.
        private RestorePoint CreateRestorePoint(string rgName, string rpcName,
                                                string rpName, OSDisk osDisk, string diskToExclude)
        {
            string             osDiskId               = osDisk.ManagedDisk.Id;
            string             osDiskName             = osDisk.Name;
            ApiEntityReference diskToExcludeEntityRef = new ApiEntityReference()
            {
                Id = diskToExclude
            };
            List <ApiEntityReference> disksToExclude = new List <ApiEntityReference> {
                diskToExcludeEntityRef
            };
            RestorePoint inputRestorePoint = new RestorePoint()
            {
                ExcludeDisks = disksToExclude
            };

            return(m_CrpClient.RestorePoints.Create(rgName, rpcName, rpName, inputRestorePoint));
        }
Esempio n. 21
0
        public long CountLeftPoints(RestorePoint lastPoint)
        {
            long k           = 0;
            var  point       = lastPoint;
            long currentSize = 0;

            while (point != null && (currentSize < MaxSize || point is IncrementalBackupPoint))
            {
                if (point.Size() + currentSize <= MaxSize)
                {
                    k++;
                    currentSize += point.Size();
                    point        = point.PreviousPoint;
                    continue;
                }
                break;
            }

            return(k);
        }
Esempio n. 22
0
File: Backup.cs Progetto: s4xack/Oop
        public void CreateRestorePoint(RestoreType restoreType)
        {
            DateTime creationTime = _dateTimeProvider.GetUtcNow();
            IEnumerable <FileData> watchedFiles = _watchedFilePaths.Select(path => _fileRepository.Read(path));
            List <FileData>        files        = restoreType switch
            {
                RestoreType.Full => watchedFiles.ToList(),
                RestoreType.Increment =>
                _restorePoints.Count == 0
                        ? throw new ArgumentException()
                        : watchedFiles.Select(GetDiff).ToList(),
                      _ => throw new ArgumentException()
            };

            RestorePoint restorePoint = _storageAlgorithm.PackRestorePoint(BackupPath, files, restoreType, creationTime);

            _restorePoints.Add(restorePoint);
            _fileRepository.Write(restorePoint.ToPackedFileData());

            Clean();
        }
Esempio n. 23
0
    /// <summary>
    /// Save the current game and Exit. Special Save operation during gameState.MetaGame)
    /// </summary>
    private void ProcessSaveAndExit(RestorePoint restorePointInput)
    {
        Debug.LogFormat("[Ctrl] ControlManager.cs -> ProcessSaveAndExit: Save and Exit selected{0}", "\n");
        //save restore point in case user changes their mind (update InputManager.cs as save/load is keyed off this value)
        restorePoint = restorePointInput;

        /*GameManager.i.inputScript.RestorePoint = restorePointInput;*/

        //toggle on modal block
        GameManager.i.guiScript.SetIsBlocked(true);
        //Save Game -> open background
        GameManager.i.modalGUIScript.SetBackground(Background.SaveGame);
        //Close any open background
        GameManager.i.modalGUIScript.CloseBackgrounds(Background.SaveGame);
        //change game state
        GameManager.i.inputScript.GameState = GameState.SaveAndExit;
        //Debug -> time load game process
        GameManager.i.testScript.StartTimer();
        GameManager.i.fileScript.WriteSaveData(new LoadGameState()
        {
            gameState = GameState.MetaGame, restorePoint = restorePointInput
        }, SaveType.PlayerSave);
        GameManager.i.fileScript.SaveGame(SaveType.PlayerSave);
        //how long did it take?
        long timeElapsed = GameManager.i.testScript.StopTimer();

        Debug.LogFormat("[Per] ControlManager.cs -> ProcessSaveGame: SAVE GAME took {0} ms", timeElapsed);
        //Game saved, ask user if they want to exit
        ModalConfirmDetails details = new ModalConfirmDetails();

        details.topText     = string.Format("Your game has been {0}. You are about to Exit", GameManager.Formatt("SAVED", ColourType.neutralText));
        details.bottomText  = "Are you sure?";
        details.buttonFalse = "EXIT";
        details.buttonTrue  = "RESUME";
        details.eventFalse  = EventType.ExitGame;
        details.eventTrue   = EventType.ResumeMetaGame;
        details.modalState  = ModalSubState.MetaGame;
        //open confirm
        EventManager.i.PostNotification(EventType.ConfirmOpen, this, details, "MetaManager.cs -> ProcessMetaGame");
    }
        public RestorePoint Clean(RestorePoint lastPoint, out bool areMorePointsLeft)
        {
            areMorePointsLeft = false;
            var k     = LastNPoints - 1;
            var point = lastPoint;

            while (point != null && (k > 0 || point is IncrementalBackupPoint))
            {
                point = point.PreviousPoint;
                --k;
            }

            if (k <= 0 && point != null)
            {
                point.PreviousPoint = null;
            }
            if (k < 0)
            {
                areMorePointsLeft = true;
            }
            return(lastPoint);
        }
        /// <summary>
        /// Validates the RestorePointListResponse.
        /// </summary>
        /// <param name="restorePointsListResponse">Response to validate.</param>
        /// <param name="isDataWarehouseDatabase">Is this response from a data warehouse database? Data warehouse databases return different values than other databases.</param>
        /// <param name="expectedCount">Expected number of restore points.</param>
        private static void ValidateRestorePointListResponse(RestorePointListResponse restorePointsListResponse, bool isDataWarehouseDatabase, int expectedCount)
        {
            Assert.Equal(expectedCount, restorePointsListResponse.Count());
            int count = restorePointsListResponse.Count();

            if (count == expectedCount && count > 0)
            {
                RestorePoint selectedRestorePoint = restorePointsListResponse.RestorePoints.First();
                if (isDataWarehouseDatabase)
                {
                    Assert.Equal("DISCRETE", selectedRestorePoint.Properties.RestorePointType);
                    Assert.Null(selectedRestorePoint.Properties.EarliestRestoreDate);
                    Assert.NotNull(selectedRestorePoint.Properties.RestorePointCreationDate);
                }
                else
                {
                    Assert.Equal("CONTINUOUS", selectedRestorePoint.Properties.RestorePointType);
                    Assert.NotNull(selectedRestorePoint.Properties.EarliestRestoreDate);
                    Assert.Null(selectedRestorePoint.Properties.RestorePointCreationDate);
                }
            }
        }
Esempio n. 26
0
        // Module defining this command


        // Optional custom code for this activity


        /// <summary>
        /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
        /// </summary>
        /// <param name="context">The NativeActivityContext for the currently running activity.</param>
        /// <returns>A populated instance of Sytem.Management.Automation.PowerShell</returns>
        /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
        protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
        {
            System.Management.Automation.PowerShell invoker       = global::System.Management.Automation.PowerShell.Create();
            System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);

            // Initialize the arguments

            if (RestorePoint.Expression != null)
            {
                targetCommand.AddParameter("RestorePoint", RestorePoint.Get(context));
            }

            if (LastStatus.Expression != null)
            {
                targetCommand.AddParameter("LastStatus", LastStatus.Get(context));
            }


            return(new ActivityImplementationContext()
            {
                PowerShellInstance = invoker
            });
        }
Esempio n. 27
0
        private async Task <List <RestorePoint> > GetRecoveryPointDetailsInternalAsync(IEnumerable <string> metadataFiles, CancellationToken cancellationToken)
        {
            var backupList = new List <RestorePoint>();

            foreach (var metadataFile in metadataFiles)
            {
                cancellationToken.ThrowIfCancellationRequested();

                var recoveryPointMetadataFile =
                    await RecoveryPointMetadataFile.OpenAsync(Path.Combine(this.storeInformation.Path, metadataFile), cancellationToken);

                var recoveryPoint = new RestorePoint()
                {
                    BackupChainId        = recoveryPointMetadataFile.BackupChainId,
                    BackupId             = recoveryPointMetadataFile.BackupId,
                    ParentRestorePointId = recoveryPointMetadataFile.ParentBackupId,
                    BackupLocation       = recoveryPointMetadataFile.BackupLocation,
                    CreationTimeUtc      = recoveryPointMetadataFile.BackupTime,
                    BackupType           =
                        recoveryPointMetadataFile.ParentBackupId == Guid.Empty? BackupOptionType.Full : BackupOptionType.Incremental,
                    EpochOfLastBackupRecord = new BackupEpoch
                    {
                        ConfigurationNumber = recoveryPointMetadataFile.EpochOfLastBackupRecord.ConfigurationNumber,
                        DataLossNumber      = recoveryPointMetadataFile.EpochOfLastBackupRecord.DataLossNumber
                    },
                    LsnOfLastBackupRecord  = recoveryPointMetadataFile.LsnOfLastBackupRecord,
                    PartitionInformation   = this.GetBackupServicePartitionInformationFromServicePartitionInformation(recoveryPointMetadataFile.PartitionInformation),
                    ServiceManifestVersion = recoveryPointMetadataFile.ServiceManifestVersion,
                };

                PopulateApplicationServiceAndPartitionInfo(recoveryPoint, metadataFile);

                backupList.Add(recoveryPoint);
            }

            return(backupList);
        }
Esempio n. 28
0
    /// <summary>
    /// Load a saved game
    /// </summary>
    private void ProcessLoadGame(GameState state)
    {
        Debug.LogFormat("[Ctrl] ControlManager.cs -> ProcessLoadGame: LOAD game option selected{0}", "\n");
        //shutdown animations
        GameManager.i.animateScript.StopAnimations();
        //save existing game state
        gameState = state;
        //toggle on modal block
        GameManager.i.guiScript.SetIsBlocked(true);
        //Load Game -> open background
        GameManager.i.modalGUIScript.SetBackground(Background.LoadGame);
        //Close any open background
        GameManager.i.modalGUIScript.CloseBackgrounds(Background.LoadGame);
        //change game state (mid game load or start of session load?)
        if (GameManager.i.isSession == true)
        {
            GameManager.i.inputScript.GameState = GameState.LoadGame;
            //check node display and reset back to normal if not prior to save
            if (GameManager.i.nodeScript.NodeShowFlag > 0)
            {
                GameManager.i.nodeScript.ResetAll();
            }
            //check connection display and reset back to normal if not prior to save
            if (GameManager.i.connScript.resetConnections == true)
            {
                GameManager.i.connScript.RestoreConnections();
            }
        }
        else
        {
            //load game at start
            GameManager.i.inputScript.GameState = GameState.LoadAtStart;
        }
        //Debug -> time load game process
        GameManager.i.testScript.StartTimer();
        //read data from file
        if (GameManager.i.fileScript.ReadSaveData(SaveType.PlayerSave) == true)
        {
            //load data into game
            LoadGameState loadGameState = GameManager.i.fileScript.LoadSaveData(SaveType.PlayerSave);
            if (loadGameState != null)
            {
                //standard load game drops you straight into gameState.PlayGame
                if (loadGameState.gameState != GameState.PlayGame)
                {
                    //special cases
                    switch (loadGameState.gameState)
                    {
                    case GameState.MetaGame:
                        //MetaGame requires special handling
                        restorePoint = loadGameState.restorePoint;
                        ProcessResumeMetaGame();
                        break;

                    default: Debug.LogWarningFormat("Unrecognised gameState \"{0}\"", loadGameState.gameState); break;
                    }
                }
            }
            else
            {
                Debug.LogError("Invalid loadGameState (Null)");
            }
        }
        //how long did it take?
        long timeElapsed = GameManager.i.testScript.StopTimer();

        Debug.LogFormat("[Per] ControlManager.cs -> ProcessLoadGame: LOAD GAME took {0} ms", timeElapsed);
    }
Esempio n. 29
0
 /// <summary>
 /// The operation to create the restore point. Updating properties of an
 /// existing restore point is not allowed
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group.
 /// </param>
 /// <param name='restorePointCollectionName'>
 /// The name of the restore point collection.
 /// </param>
 /// <param name='restorePointName'>
 /// The name of the restore point.
 /// </param>
 /// <param name='parameters'>
 /// Parameters supplied to the Create restore point operation.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <RestorePoint> CreateAsync(this IRestorePointsOperations operations, string resourceGroupName, string restorePointCollectionName, string restorePointName, RestorePoint parameters, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.CreateWithHttpMessagesAsync(resourceGroupName, restorePointCollectionName, restorePointName, parameters, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
        private void MainDWSButton_Click(object sender, RoutedEventArgs e)
        {
            var createRestorePoint           = SwitchCreateRestorePoint.IsChecked != null && (bool)SwitchCreateRestorePoint.IsChecked;
            var removeDigTrack               = SwitchDigTrackThelemetry.IsChecked != null && (bool)SwitchDigTrackThelemetry.IsChecked;
            var addSpyToHosts                = SwitchAddSpyHosts.IsChecked != null && (bool)SwitchAddSpyHosts.IsChecked;
            var switchAddSpyIps              = SwitchAddSpyIps.IsChecked != null && (bool)SwitchAddSpyIps.IsChecked;
            var switchDisablePrivateSettings = SwitchDisablePrivateSettings.IsChecked != null && (bool)SwitchDisablePrivateSettings.IsChecked;
            var switchDisableWindowsDefender = SwitchDisableWindowsDefender.IsChecked != null && (bool)SwitchDisableWindowsDefender.IsChecked;
            var switchDefaultPhotoVierwer    = SwitchDefaultPhotoVierwer.IsChecked != null && (bool)SwitchDefaultPhotoVierwer.IsChecked;

            new Thread(() =>
            {
                EnableOrDisableWindow(false);
                if (createRestorePoint)
                {
                    RestorePoint.CreateRestorePoint($"Use Destroy Windows Spying on {DateTime.Now.Day}-{DateTime.Now.Month}-{DateTime.Now.Year}");
                }

                if (removeDigTrack)
                {
                    Logger.Log("Disable telemetry...");
                    DWSFunctions.DigTrackFullRemove();
                    Logger.Log("Delete keylogger...");
                    WindowsUtil.RunCmd("/c reg add \"HKEY_LOCAL_MACHINE\\SOFTWARE\\Policies\\Microsoft\\Windows\\Windows Search\" /v \"AllowCortana\" /t REG_DWORD /d 0 /f ");
                    Logger.Log("Disable cortana...");

                    foreach (var serviceName in DwsResources.ServicesList)
                    {
                        ServiceSC.DisableService(serviceName);
                    }
                    foreach (var currentTask in DwsResources.Disabletaskslist)
                    {
                        WindowsUtil.ProcStartargs("SCHTASKS", $"/Change /TN \"{currentTask}\" /disable");
                        Logger.Log($"Disabled task: {currentTask}", Logger.LogType.SUCCESS);
                    }
                }

                if (addSpyToHosts)
                {
                    foreach (var currHost in DwsResources.Hostsdomains)
                    {
                        HostsEditor.AddHostToHosts(currHost);
                    }
                }

                if (switchAddSpyIps)
                {
                    foreach (var currentIpAddr in DwsResources.IpAddr)
                    {
                        WindowsUtil.RunCmd($"/c route -p ADD {currentIpAddr} MASK 255.255.255.255 0.0.0.0");
                        WindowsUtil.RunCmd($"/c route -p change {currentIpAddr} MASK 255.255.255.255 0.0.0.0 if 1");
                        WindowsUtil.RunCmd($"/c netsh advfirewall firewall delete rule name=\"{currentIpAddr}_Block\"");
                        WindowsUtil.RunCmd(
                            string.Format(
                                "/c netsh advfirewall firewall add rule name=\"{0}_Block\" dir=out interface=any action=block remoteip={0}",
                                currentIpAddr));
                        Logger.Log($"Add Windows Firewall rule: \"{currentIpAddr}_Block\"");
                    }
                    WindowsUtil.RunCmd("/c netsh advfirewall firewall delete rule name=\"Explorer.EXE_BLOCK\"");
                    WindowsUtil.RunCmd(
                        $"/c netsh advfirewall firewall add rule name=\"Explorer.EXE_BLOCK\" dir=out interface=any action=block program=\"{System.IO.Path.GetPathRoot(Environment.SystemDirectory)}Windows\\explorer.exe\"");
                    WindowsUtil.RunCmd("/c netsh advfirewall firewall delete rule name=\"WSearch_Block\"");
                    WindowsUtil.RunCmd(
                        "/c netsh advfirewall firewall add rule name=\"WSearch_Block\" dir=out interface=any action=block service=WSearch");
                    Logger.Log("Add Windows Firewall rule: \"WSearch_Block\"", Logger.LogType.SUCCESS);
                    Logger.Log("Ip list blocked", Logger.LogType.SUCCESS);
                }

                if (switchDisablePrivateSettings)
                {
                    foreach (var currentRegKey in DwsResources.Regkeyvalandother)
                    {
                        WindowsUtil.SetRegValueHkcu(currentRegKey, "Value", "Deny", RegistryValueKind.String);
                    }
                    WindowsUtil.SetRegValueHkcu(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Search", "CortanaEnabled", "0",
                                                RegistryValueKind.DWord);
                    WindowsUtil.SetRegValueHkcu(@"SOFTWARE\Microsoft\InputPersonalization", "RestrictImplicitInkCollection", "1",
                                                RegistryValueKind.DWord);
                    WindowsUtil.SetRegValueHklm(@"SOFTWARE\Policies\Microsoft\Windows\Windows Search", "DisableWebSearch", "1",
                                                RegistryValueKind.DWord);
                    WindowsUtil.SetRegValueHklm(@"SOFTWARE\Policies\Microsoft\Windows\Windows Search", "ConnectedSearchUseWeb", "0",
                                                RegistryValueKind.DWord);
                    WindowsUtil.SetRegValueHklm(@"SOFTWARE\Policies\Microsoft\Windows\LocationAndSensors", "DisableLocation", "1",
                                                RegistryValueKind.DWord);
                    WindowsUtil.SetRegValueHklm(@"SOFTWARE\Policies\Microsoft\Windows\LocationAndSensors",
                                                "DisableWindowsLocationProvider", "1", RegistryValueKind.DWord);
                    WindowsUtil.SetRegValueHklm(@"SOFTWARE\Policies\Microsoft\Windows\LocationAndSensors", "DisableLocationScripting",
                                                "1", RegistryValueKind.DWord);
                    WindowsUtil.SetRegValueHklm(@"SOFTWARE\Policies\Microsoft\Windows\LocationAndSensors", "DisableSensors", "1",
                                                RegistryValueKind.DWord);
                    WindowsUtil.SetRegValueHklm(@"SYSTEM\CurrentControlSet\Services\lfsvc\Service\Configuration", "Status", "0",
                                                RegistryValueKind.DWord);
                    WindowsUtil.SetRegValueHklm(
                        @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Sensor\Overrides\{BFA794E4-F964-4FDB-90F6-51056BFE4B44}",
                        "SensorPermissionState", "0", RegistryValueKind.DWord);
                    WindowsUtil.SetRegValueHkcu(@"SOFTWARE\Microsoft\Siuf\Rules", "NumberOfSIUFInPeriod", "0", RegistryValueKind.DWord);
                    WindowsUtil.SetRegValueHkcu(@"SOFTWARE\Microsoft\Siuf\Rules", "PeriodInNanoSeconds", "0", RegistryValueKind.DWord);
                    WindowsUtil.SetRegValueHkcu(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Search", "BingSearchEnabled", "0",
                                                RegistryValueKind.DWord);
                    WindowsUtil.SetRegValueHklm(@"SOFTWARE\Policies\Microsoft\Windows\TabletPC", "PreventHandwritingDataSharing", "1",
                                                RegistryValueKind.DWord);
                    WindowsUtil.SetRegValueHklm(@"SOFTWARE\Policies\Microsoft\Windows\HandwritingErrorReports",
                                                "PreventHandwritingErrorReports", "1", RegistryValueKind.DWord);
                    WindowsUtil.SetRegValueHklm(@"SOFTWARE\Policies\Microsoft\Windows\AppCompat", "DisableInventory", "1",
                                                RegistryValueKind.DWord);
                    WindowsUtil.SetRegValueHklm(@"SOFTWARE\Policies\Microsoft\Windows\Personalization", "NoLockScreenCamera", "1",
                                                RegistryValueKind.DWord);
                    WindowsUtil.SetRegValueHklm(@"SOFTWARE\Microsoft\Windows\CurrentVersion\AdvertisingInfo", "Enabled", "0",
                                                RegistryValueKind.DWord);
                    WindowsUtil.SetRegValueHkcu(@"SOFTWARE\Microsoft\Windows\CurrentVersion\AdvertisingInfo", "Enabled", "0",
                                                RegistryValueKind.DWord);
                    WindowsUtil.SetRegValueHkcu(@"SOFTWARE\Microsoft\Input\TIPC", "Enabled", "0", RegistryValueKind.DWord);
                    WindowsUtil.SetRegValueHklm(@"SOFTWARE\Policies\Microsoft\Biometrics", "Enabled", "0", RegistryValueKind.DWord);
                    WindowsUtil.SetRegValueHklm(@"SOFTWARE\Policies\Microsoft\Windows\CredUI", "DisablePasswordReveal", "1",
                                                RegistryValueKind.DWord);
                    WindowsUtil.SetRegValueHkcu(@"SOFTWARE\Microsoft\Windows\CurrentVersion\SettingSync", "SyncPolicy", "5",
                                                RegistryValueKind.DWord);
                    WindowsUtil.SetRegValueHkcu(@"SOFTWARE\Microsoft\Windows\CurrentVersion\SettingSync\Groups\Personalization",
                                                "Enabled", "0", RegistryValueKind.DWord);
                    WindowsUtil.SetRegValueHkcu(@"SOFTWARE\Microsoft\Windows\CurrentVersion\SettingSync\Groups\BrowserSettings",
                                                "Enabled", "0", RegistryValueKind.DWord);
                    WindowsUtil.SetRegValueHkcu(@"SOFTWARE\Microsoft\Windows\CurrentVersion\SettingSync\Groups\Credentials", "Enabled",
                                                "0", RegistryValueKind.DWord);
                    WindowsUtil.SetRegValueHkcu(@"SOFTWARE\Microsoft\Windows\CurrentVersion\SettingSync\Groups\Language", "Enabled", "0",
                                                RegistryValueKind.DWord);
                    WindowsUtil.SetRegValueHkcu(@"SOFTWARE\Microsoft\Windows\CurrentVersion\SettingSync\Groups\Accessibility", "Enabled",
                                                "0", RegistryValueKind.DWord);
                    WindowsUtil.SetRegValueHkcu(@"SOFTWARE\Microsoft\Windows\CurrentVersion\SettingSync\Groups\Windows", "Enabled", "0",
                                                RegistryValueKind.DWord);
                    Logger.Log("Private settings disabled", Logger.LogType.SUCCESS);
                }

                if (switchDisableWindowsDefender)
                {
                    try
                    {
                        // REG FILE IMPORT
                        WindowsUtil.ProcStartargs("regedit.exe", $"/s \"{WindowsUtil.ExtractResourceToTemp(Encoding.ASCII.GetBytes(Properties.Resources.windowsdefender_disable), "windowsdefender_disable.reg")}\"");
                        Logger.Log("Disable Windows Defender complete.", Logger.LogType.SUCCESS);
                        WindowsUtil.SetRegValueHklm(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer",
                                                    "SmartScreenEnabled", "Off",
                                                    RegistryValueKind.String);
                        Logger.Log("Disable Smart Screen complete.", Logger.LogType.SUCCESS);
                    }
                    catch (Exception ex)
                    {
                        Logger.Log($"Error disable Windows Defender or Smart Screen. Exception: {ex}",
                                   Logger.LogType.ERROR);
                    }
                }

                if (switchDefaultPhotoVierwer)
                {
                    WindowsUtil.SetRegValueHkcu(@"Software\Classes\.ico", null, "PhotoViewer.FileAssoc.Tiff", RegistryValueKind.String);
                    WindowsUtil.SetRegValueHkcu(@"Software\Classes\.tiff", null, "PhotoViewer.FileAssoc.Tiff", RegistryValueKind.String);
                    WindowsUtil.SetRegValueHkcu(@"Software\Classes\.bmp", null, "PhotoViewer.FileAssoc.Tiff", RegistryValueKind.String);
                    WindowsUtil.SetRegValueHkcu(@"Software\Classes\.png", null, "PhotoViewer.FileAssoc.Tiff", RegistryValueKind.String);
                    WindowsUtil.SetRegValueHkcu(@"Software\Classes\.gif", null, "PhotoViewer.FileAssoc.Tiff", RegistryValueKind.String);
                    WindowsUtil.SetRegValueHkcu(@"Software\Classes\.jpeg", null, "PhotoViewer.FileAssoc.Tiff", RegistryValueKind.String);
                    WindowsUtil.SetRegValueHkcu(@"Software\Classes\.jpg", null, "PhotoViewer.FileAssoc.Tiff", RegistryValueKind.String);
                    Logger.Log("Set Default PhotoViewer complete.", Logger.LogType.SUCCESS);
                }
                Logger.Log("COMPLETE.", Logger.LogType.SUCCESS);
                EnableOrDisableWindow(true);
                if (MessageBox.Show("Complete.\r\nRestart system now?", "Ask", MessageBoxButton.YesNo,
                                    MessageBoxImage.Question) == MessageBoxResult.Yes)
                {
                    Process.Start("shutdown.exe", "-r -t 0");
                }
            }).Start();
        }