예제 #1
0
        /// <summary>
        /// The main loop executes the following steps:<br />
        /// 1. Print start message, explain usage of application<br />
        /// 2. Let the user select a profile<br />
        /// 3. Do a backup according to the selected profile<br />
        /// 4. Ask if another backup run should be started<br />
        /// 5. Exit or repeat from step 1<br />
        /// <br />
        /// If an error occurs while executing the main loop, a BackupException will be thrown by the sub methods
        /// and is forwarded to the Main method for unifying the exit points of the application.
        /// </summary>
        /// <param name="profileSelector">an instance for selecting a backup profile</param>
        /// <param name="profileConverter">an instance for converting a backup profile from a xml file to an internal representation</param>
        /// <param name="excludeUtil">an instance for checking paths which should be excluded by the backup</param>
        private void DoMainLoop(BackupProfileSelector profileSelector, BackupProfileConverter profileConverter, ExcludeUtil excludeUtil)
        {
            // endless loop to enable multiple backup runs without restarting the program
            // => only stops if an error occurs or if the user does not want to do another run
            bool doAnotherRun = true;

            while (doAnotherRun)
            {
                // starting message to explain the usage of the application
                ConsoleWriter.WriteApplicationTitle();
                PrintStartingMessage();

                // let the user select a backup profile or cancel the application
                string profilePath = profileSelector.SelectBackupProfile();
                if (profilePath == null)
                {
                    break;
                }

                // load selected profile (might throw BackupException if invalid)
                BackupProfile profile = profileConverter.LoadBackupProfile(profilePath, profileSelector.IsDryRunSelected);

                // valid profile, do backup (might throw BackupException)
                BackupRunner backupRunner = new BackupRunner(profile, excludeUtil);
                backupRunner.RunBackup();

                // if reached here, the backup is completed without errors
                // => ask the user if another backup run should be done
                doAnotherRun = AskForAnotherRun();
            }
        }
예제 #2
0
        private void SetSourceFolderOnBackupProfile(Extension.IEnsoService service, Command command, string name, string sourceFolder)
        {
            string        filePath      = WorkItemsProviders.BackupProfiles.BackupProfiles.GetFilePath(name);
            BackupProfile backupProfile = null;

            if (File.Exists(filePath))
            {
                backupProfile = WorkItemsProviders.BackupProfiles.BackupProfiles.Load(name);
            }
            else
            {
                backupProfile      = new BackupProfile();
                backupProfile.Name = name;
            }
            backupProfile.SourceFolder = sourceFolder;
            WorkItemsProviders.BackupProfiles.BackupProfiles.Save(backupProfile);

            if (string.IsNullOrEmpty(backupProfile.DestinationFolder))
            {
                SuggestionsCache.DropCache(this.GetType());
                MessagesHandler.Display(string.Format("Profile created. Use 'set as backup destination...' command now.", command.Name));
            }
            else
            {
                MessagesHandler.Display(string.Format(string.Format("Profile updated. You can now use 'backup {0}' command to create backups quickly.", name)));
            }
        }
예제 #3
0
        public static List <BackupProfile> GetAll()
        {
            List <BackupProfile> items = new List <BackupProfile>();

            string backupProfilesFolder = Settings.Current.BackupProfilesFolder;

            CraftSynth.BuildingBlocks.IO.FileSystem.CreateFolderIfItDoesNotExist(backupProfilesFolder);

            string[] fileNames = Directory.GetFiles(backupProfilesFolder, "*.bp");
            foreach (string fileName in fileNames)
            {
                try
                {
                    string        filePath      = Path.Combine(backupProfilesFolder, fileName);
                    string        name          = Path.GetFileNameWithoutExtension(fileName).ToLower();
                    BackupProfile backupProfile = new BackupProfile();
                    backupProfile.Name = name;
                    items.Add(backupProfile);
                }
                catch (Exception exception)
                {
                    Logging.AddErrorLog("ExtensionMacro: Adding of backup profile '" + fileName + "' failed : " + exception.Message);
                    Common.Logging.AddExceptionLog(exception);
                }
            }



            return(items);
        }
예제 #4
0
        public IWorkItem GetParameterFromSelectedSuggestion(IWorkItem selectedSuggestion)
        {
            BackupProfile backupProfile = Load(selectedSuggestion.GetCaption());

            backupProfile.Provider = this;
            return(backupProfile);
        }
예제 #5
0
        /// <summary>
        /// Initiates the actual backup specified by the given backup profile. This includes adding new files/dirs,
        /// updating existing but newer files, removing not (anymore) existing files and directories.
        /// Writes on the console when the backup has finished successfully. Might throw exceptions which needs to be
        /// captured from the caller of this method.
        /// </summary>
        /// <param name="profile">the backup profile to run</param>
        private void DoBackup(BackupProfile profile)
        {
            // go through all BackupLocations in the BackupProfile to backup them
            bool atLeastOneNewer = false;

            foreach (BackupLocation backupLocation in profile.BackupLocations)
            {
                // show the backup location path as feedback to the user
                ConsoleWriter.WriteBackupLocationHeadline(Lang.CheckBackupLocation, backupLocation.Path);

                // do backup
                bool updated = false;
                if (File.Exists(backupLocation.Path))
                {
                    updated = BackupFileBackupLocation(backupLocation, backupLocation.Path, backupLocation.Destination, profile.DryRun);
                }
                else if (Directory.Exists(backupLocation.Path))
                {
                    // backup path is a directory, so backup this directory recursively
                    // => the return value marks if at least one file was updated (for better output to the user)
                    updated = BackupDirectoryRecursively(
                        backupLocation, backupLocation.Path, backupLocation.Destination,
                        backupLocation.ExcludePaths, profile.DryRun);
                }

                // set return flag if an file was changed and the flag is not yet set
                if (!atLeastOneNewer && updated)
                {
                    atLeastOneNewer = true;
                }
            }

            // feedback output to user
            if (profile.DryRun)
            {
                // output to the user after a dry run
                ConsoleWriter.WriteSuccessMessage(Lang.SuccessDryRun);
            }
            else
            {
                // output to the user after the backup (informs whether there was something updated or not)
                if (!atLeastOneNewer)
                {
                    ConsoleWriter.WriteSuccessMessage(Lang.SuccessNoUpdate);
                }
                else
                {
                    ConsoleWriter.WriteSuccessMessage(Lang.SuccessUpdate);
                }
            }
            ConsoleWriter.EmptyLine();
        }
예제 #6
0
        public static BackupProfile Load(string backupProfileName)
        {
            BackupProfile backupProfile = null;

            try
            {
                string   filePath = GetFilePath(backupProfileName);
                string[] lines    = File.ReadAllLines(filePath);
                backupProfile                   = new BackupProfile();
                backupProfile.Name              = backupProfileName;
                backupProfile.SourceFolder      = lines[0];
                backupProfile.DestinationFolder = lines[1];
            }
            catch (Exception exception)
            {
                Common.Logging.AddExceptionLog(exception);
            }
            return(backupProfile);
        }
예제 #7
0
 internal PhpWorkloadResourceData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, IDictionary <string, string> tags, AzureLocation location, WorkloadKind kind, WorkloadsSku sku, PhpWorkloadResourceIdentity identity, AzureLocation?appLocation, ManagedRGConfiguration managedResourceGroupConfiguration, UserProfile adminUserProfile, VmssNodesProfile webNodesProfile, NodeProfile controllerProfile, NetworkProfile networkProfile, DatabaseProfile databaseProfile, SiteProfile siteProfile, FileshareProfile fileshareProfile, PhpProfile phpProfile, SearchProfile searchProfile, CacheProfile cacheProfile, BackupProfile backupProfile, PhpWorkloadProvisioningState?provisioningState) : base(id, name, resourceType, systemData, tags, location)
 {
     Kind        = kind;
     Sku         = sku;
     Identity    = identity;
     AppLocation = appLocation;
     ManagedResourceGroupConfiguration = managedResourceGroupConfiguration;
     AdminUserProfile  = adminUserProfile;
     WebNodesProfile   = webNodesProfile;
     ControllerProfile = controllerProfile;
     NetworkProfile    = networkProfile;
     DatabaseProfile   = databaseProfile;
     SiteProfile       = siteProfile;
     FileshareProfile  = fileshareProfile;
     PhpProfile        = phpProfile;
     SearchProfile     = searchProfile;
     CacheProfile      = cacheProfile;
     BackupProfile     = backupProfile;
     ProvisioningState = provisioningState;
 }
예제 #8
0
        /// <summary>
        /// Loads the BackupProfile saved at the given path.
        /// <br />
        /// Does not check wheter the given path is valid so this must be verified before calling this
        /// method. However this method checks if the specification of the profile is correct and prints
        /// errors that might occur while parsing.
        /// <br />
        /// Returns the converted BackupProfile or throws/forwards a BackupException if an error occurs.
        /// So the Main method can handle the exception for unifying the exit point of the application.
        /// </summary>
        /// <param name="path">a valid path for a backup profile</param>
        /// <param name="dryRun">true if changes should only be shown but not actually be made</param>
        /// <exception cref="BackupException">thrown or forwarded if the backup profile has errors (not existing source,
        /// malformatted xml etc.)</exception>
        /// <returns>a valid backup profile or null</returns>
        public BackupProfile LoadBackupProfile(string path, bool dryRun)
        {
            /*
             * load XML
             */

            // load XML, might have errors
            XDocument doc;

            try
            {
                doc = XDocument.Load(path);
            }
            catch (Exception e)
            {
                // error while loading the xml (like syntax error), throw a BackupException
                IList <string> errorMessages = new List <string>()
                {
                    Lang.ErrorXmlMalformatted, Lang.ErrorMessage
                };
                throw new BackupException(errorMessages, e.Message);
            }

            /*
             * convert XML entries to BackupProfile,
             * check for errors while that
             */

            // parse backup locations inside the profile if valid (might throw a BackupException)
            IList <BackupLocation> xmlLocs = ParseBackupLocations(doc);

            // no errors occured while parsing, so create a BackupProfile from the BackupLocations
            string        name    = Path.GetFileNameWithoutExtension(path);
            BackupProfile profile = new BackupProfile(name, xmlLocs, dryRun);

            // control message
            //Logger.LogInfo(profile.ToString());

            // return the profile
            return(profile);
        }
예제 #9
0
        public void ExecuteCommand(Extension.IEnsoService service, Command command)
        {
            Logging.AddActionLog(string.Format("BackupManager: Executing command '{0}' ...", command.Name));
            if (command.Name == "set as backup source folder" && command.Postfix == "for profile [profile name] [folder]")
            {
                string name         = command.parametersOnExecute[0].GetValueAsText();
                string sourceFolder = command.parametersOnExecute[1].GetValueAsText();

                this.SetSourceFolderOnBackupProfile(service, command, name, sourceFolder);
            }
            else
            if (command.Name == "set as backup destination folder" && command.Postfix == "for profile [profile name] [folder]")
            {
                string name = command.parametersOnExecute[0].GetValueAsText();
                string destinationFolder = command.parametersOnExecute[1].GetValueAsText();

                this.SetDestinationFolderOnBackupProfile(service, command, name, destinationFolder);
            }
            else
            if (command.Name == "set as backup source folder" && command.Postfix == "[folder]")
            {
                string sourceFolder = command.parametersOnExecute[0].GetValueAsText();
                string name         = PromptProfileSelectionDialog();
                if (!string.IsNullOrEmpty(name))
                {
                    this.SetSourceFolderOnBackupProfile(service, command, name, sourceFolder);
                }
            }
            else
            if (command.Name == "set as backup destination folder" && command.Postfix == "[folder]")
            {
                string destinationFolder = command.parametersOnExecute[0].GetValueAsText();
                string name = PromptProfileSelectionDialog();
                if (!string.IsNullOrEmpty(name))
                {
                    this.SetDestinationFolderOnBackupProfile(service, command, name, destinationFolder);
                }
            }
            else
            if (command.Name == "backup")
            {
                BackupProfile backupProfile = command.parametersOnExecute[0].GetValue() as BackupProfile;
                throw new NotImplementedException();                                 //TODO: finish display async
                //string label = ParameterInput.Display("Label", new List<string>(), false, false, backupProfile.Name, false, false, null);
                //if (!string.IsNullOrEmpty(label))
                //{
                //	if(!Directory.Exists(backupProfile.SourceFolder))
                //	{
                //		MessagesHandler.Display( "Source folder does not exist.", backupProfile.SourceFolder);
                //	}else
                //	if(!Directory.Exists(backupProfile.DestinationFolder))
                //	{
                //		MessagesHandler.Display( "Destination folder does not exist.", backupProfile.DestinationFolder);
                //	}else
                //	{
                //		MessagesHandler.Display( string.Format("Backing up '{0}' to '{1}' ...", backupProfile.SourceFolder, backupProfile.DestinationFolder));
                //		//{EnsoPlusDataFolder}\7z.exe
                //		//a -r "{DestinationFolderPath}\{CurrentDateTime} {Label}\{SourceFolderName}" "{SourceFolderPath}";
                //		string parameters = Settings.Current.BackupManagerParameters;
                //		parameters = parameters.Replace("{DestinationFolderPath}", backupProfile.DestinationFolder);
                //		parameters = parameters.Replace("{CurrentDateTime}", CraftSynth.BuildingBlocks.Common.DateAndTime.GetCurrentDateAndTimeInSortableFormatForFileSystem());
                //		parameters = parameters.Replace("{Label}", label);
                //		parameters = parameters.Replace("{SourceFolderName}", Path.GetFileName(backupProfile.SourceFolder));
                //		parameters = parameters.Replace("{SourceFolderPath}", backupProfile.SourceFolder);

                //		CraftSynth.BuildingBlocks.WindowsNT.Misc.OpenFile(Settings.Current.BackupManagerExePath, parameters);
                //	}
                //}
            }
            else
            {
                throw new ApplicationException(string.Format("BackupManager: Command not found. Command: {0} {1}", command.Name, command.Postfix));
            }
        }
예제 #10
0
        internal static PhpWorkloadResourceData DeserializePhpWorkloadResourceData(JsonElement element)
        {
            WorkloadKind            kind = default;
            Optional <WorkloadsSku> sku  = default;
            Optional <PhpWorkloadResourceIdentity> identity     = default;
            IDictionary <string, string>           tags         = default;
            AzureLocation                           location    = default;
            ResourceIdentifier                      id          = default;
            string                                  name        = default;
            ResourceType                            type        = default;
            SystemData                              systemData  = default;
            Optional <AzureLocation>                appLocation = default;
            Optional <ManagedRGConfiguration>       managedResourceGroupConfiguration = default;
            Optional <UserProfile>                  adminUserProfile  = default;
            Optional <VmssNodesProfile>             webNodesProfile   = default;
            Optional <NodeProfile>                  controllerProfile = default;
            Optional <NetworkProfile>               networkProfile    = default;
            Optional <DatabaseProfile>              databaseProfile   = default;
            Optional <SiteProfile>                  siteProfile       = default;
            Optional <FileshareProfile>             fileshareProfile  = default;
            Optional <PhpProfile>                   phpProfile        = default;
            Optional <SearchProfile>                searchProfile     = default;
            Optional <CacheProfile>                 cacheProfile      = default;
            Optional <BackupProfile>                backupProfile     = default;
            Optional <PhpWorkloadProvisioningState> provisioningState = default;

            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("kind"))
                {
                    kind = new WorkloadKind(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("sku"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    sku = WorkloadsSku.DeserializeWorkloadsSku(property.Value);
                    continue;
                }
                if (property.NameEquals("identity"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    identity = PhpWorkloadResourceIdentity.DeserializePhpWorkloadResourceIdentity(property.Value);
                    continue;
                }
                if (property.NameEquals("tags"))
                {
                    Dictionary <string, string> dictionary = new Dictionary <string, string>();
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        dictionary.Add(property0.Name, property0.Value.GetString());
                    }
                    tags = dictionary;
                    continue;
                }
                if (property.NameEquals("location"))
                {
                    location = new AzureLocation(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("id"))
                {
                    id = new ResourceIdentifier(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("type"))
                {
                    type = new ResourceType(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("systemData"))
                {
                    systemData = JsonSerializer.Deserialize <SystemData>(property.Value.ToString());
                    continue;
                }
                if (property.NameEquals("properties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        if (property0.NameEquals("appLocation"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            appLocation = new AzureLocation(property0.Value.GetString());
                            continue;
                        }
                        if (property0.NameEquals("managedResourceGroupConfiguration"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            managedResourceGroupConfiguration = ManagedRGConfiguration.DeserializeManagedRGConfiguration(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("adminUserProfile"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            adminUserProfile = UserProfile.DeserializeUserProfile(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("webNodesProfile"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            webNodesProfile = VmssNodesProfile.DeserializeVmssNodesProfile(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("controllerProfile"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            controllerProfile = NodeProfile.DeserializeNodeProfile(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("networkProfile"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            networkProfile = NetworkProfile.DeserializeNetworkProfile(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("databaseProfile"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            databaseProfile = DatabaseProfile.DeserializeDatabaseProfile(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("siteProfile"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            siteProfile = SiteProfile.DeserializeSiteProfile(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("fileshareProfile"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            fileshareProfile = FileshareProfile.DeserializeFileshareProfile(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("phpProfile"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            phpProfile = PhpProfile.DeserializePhpProfile(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("searchProfile"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            searchProfile = SearchProfile.DeserializeSearchProfile(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("cacheProfile"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            cacheProfile = CacheProfile.DeserializeCacheProfile(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("backupProfile"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            backupProfile = BackupProfile.DeserializeBackupProfile(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("provisioningState"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            provisioningState = new PhpWorkloadProvisioningState(property0.Value.GetString());
                            continue;
                        }
                    }
                    continue;
                }
            }
            return(new PhpWorkloadResourceData(id, name, type, systemData, tags, location, kind, sku.Value, identity.Value, Optional.ToNullable(appLocation), managedResourceGroupConfiguration.Value, adminUserProfile.Value, webNodesProfile.Value, controllerProfile.Value, networkProfile.Value, databaseProfile.Value, siteProfile.Value, fileshareProfile.Value, phpProfile.Value, searchProfile.Value, cacheProfile.Value, backupProfile.Value, Optional.ToNullable(provisioningState)));
        }
예제 #11
0
 /// <summary>
 /// Creates an instance of BackupRunner which is responsible for doing the actual backup defined by the
 /// given profile.
 /// The profile should be validated since the BackupRunner does rely on it.
 /// </summary>
 /// <param name="profile">a valid backup profile</param>
 /// <param name="excludeUtil">an instance for checking paths which should be excluded by the backup</param>
 public BackupRunner(BackupProfile profile, ExcludeUtil excludeUtil)
 {
     _profile     = profile;
     _excludeUtil = excludeUtil;
 }
예제 #12
0
 public static void Save(BackupProfile backupProfile)
 {
     File.WriteAllLines(GetFilePath(backupProfile.Name), new string[] { backupProfile.SourceFolder, backupProfile.DestinationFolder });
 }