Beispiel #1
0
 ///<summary>Returns false if the backup, repair, or the optimze failed.
 ///Set isSilent to true to suppress the failure message boxes.  However, progress windows will always be shown.</summary>
 public static bool BackupRepairAndOptimize(bool isSilent, BackupLocation backupLocation, bool isSecurityLogged = true)
 {
     if (!MakeABackup(isSilent, backupLocation, isSecurityLogged))
     {
         return(false);
     }
     try {
         ODProgress.ShowAction(() => DatabaseMaintenances.RepairAndOptimize(),
                               eventType: typeof(MiscDataEvent),
                               odEventType: ODEventType.MiscData);
     }
     catch (Exception ex) {           //MiscData.MakeABackup() could have thrown an exception.
         //Show the user that something what went wrong when not in silent mode.
         if (!isSilent)
         {
             if (ex.Message != "")
             {
                 MessageBox.Show(ex.Message);
             }
             MsgBox.Show("FormDatabaseMaintenance", "Optimize and Repair failed.");
         }
         return(false);
     }
     return(true);
 }
        private void AssertSame(BackupLocation expected, BackupLocation given)
        {
            if (expected == null)
            {
                Assert.Null(given);
            }
            else
            {
                Assert.NotNull(given);

                // Resource properties
                Assert.Equal(expected.Id.ToLower(), given.Id.ToLower());
                Assert.Equal(expected.Type, given.Type);
                Assert.Equal(expected.Name, given.Name);
                Assert.Equal(expected.Location, given.Location);

                // Location properties
                Assert.Equal(expected.AvailableCapacity, given.AvailableCapacity);
                Assert.Equal(expected.BackupFrequencyInHours, given.BackupFrequencyInHours);
                Assert.Equal(expected.EncryptionCertBase64, given.EncryptionCertBase64);
                Assert.Equal(expected.IsBackupSchedulerEnabled, given.IsBackupSchedulerEnabled);
                Assert.Equal(expected.LastBackupTime, given.LastBackupTime);
                Assert.Equal(expected.NextBackupTime, given.NextBackupTime);
                Assert.Equal(expected.LastBackupTime, given.LastBackupTime);
                Assert.Equal(expected.Password, given.Password);
                Assert.Equal(expected.Path, given.Path);
                Assert.Equal(expected.UserName, given.UserName);
            }
        }
Beispiel #3
0
        private void bDelete_Click(object sender, EventArgs e)
        {
            if (cmbName.Items.Count == 0 || cmbName.SelectedIndex == -1)
            {
                return;
            }

            try
            {
                BackupLocation loc = new BackupLocation();
                loc.id = unchecked ((int)(Int64)cmbName.SelectedValue);

                loc.Tag = findRow(loc.id);

                DialogResult res = MessageBox.Show("Are you sure you want to delete save location: " + ((firedumpdbDataSet.backup_locationsRow)loc.Tag).name, "Delete Save Location", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (res != DialogResult.Yes)
                {
                    return;
                }

                onSaveLocationDeleted(loc);

                this.backup_locationsTableAdapter.DeleteQuery((Int64)cmbName.SelectedValue);
                this.backup_locationsTableAdapter.Fill(this.firedumpdbDataSet.backup_locations);

                onSaveLocationDeletedAfter(loc);

                reloadPath();
            }
            catch (Exception ex) { }
        }
Beispiel #4
0
        ///<summary>Returns false if the backup, repair, or the optimze failed.
        ///Set isSilent to true to suppress the failure message boxes.  However, progress windows will always be shown.</summary>
        public static bool BackupRepairAndOptimize(bool isSilent, BackupLocation backupLocation, bool isSecurityLogged = true)
        {
            if (!MakeABackup(isSilent, backupLocation, isSecurityLogged))
            {
                return(false);
            }
            //Create a thread that will show a window and then stay open until the closing phrase is thrown from this form.
            Action actionCloseRepairAndOptimizeProgress = ODProgressOld.ShowProgressStatus("RepairAndOptimizeProgress", null);

            try {
                DatabaseMaintenances.RepairAndOptimize();
                actionCloseRepairAndOptimizeProgress();
            }
            catch (Exception ex) {           //MiscData.MakeABackup() could have thrown an exception.
                actionCloseRepairAndOptimizeProgress();
                //Show the user that something what went wrong when not in silent mode.
                if (!isSilent)
                {
                    if (ex.Message != "")
                    {
                        MessageBox.Show(ex.Message);
                    }
                    MsgBox.Show("FormDatabaseMaintenance", "Optimize and Repair failed.");
                }
                return(false);
            }
            return(true);
        }
Beispiel #5
0
        public void deleteSaveLocation(BackupLocation loc)
        {
            ListViewItem item = findItemSaveLoc(loc);

            if (lbSaveLocations.Items.Contains(item))
            {
                lbSaveLocations.Items.Remove(item);
            }
        }
Beispiel #6
0
 private ListViewItem findItemSaveLoc(BackupLocation loc)
 {
     return(lbSaveLocations.Items.Cast <ListViewItem>()
            .Where(i => {
         ((firedumpdbDataSet.backup_locationsRow)i.Tag).BeginEdit();
         var res = ((firedumpdbDataSet.backup_locationsRow)i.Tag).id == loc.id;
         ((firedumpdbDataSet.backup_locationsRow)i.Tag).EndEdit();
         return res;
     }).DefaultIfEmpty(new ListViewItem()).First());
 }
Beispiel #7
0
        public override int GetHashCode()
        {
            unchecked
            {
                var hashCode = DefaultJournalRoot != null?DefaultJournalRoot.GetHashCode() : 0;

                hashCode = (hashCode * 397) ^ (BackupLocation != null ? BackupLocation.GetHashCode() : 0);
                hashCode = (hashCode * 397) ^ (BackupPassword != null ? BackupPassword.GetHashCode() : 0);
                return(hashCode);
            }
        }
        private void ValidateBackupLocation(BackupLocation location)
        {
            Assert.NotNull(location);

            // Resource properties
            Assert.NotNull(location.Id);
            Assert.NotNull(location.Type);
            Assert.NotNull(location.Name);
            Assert.NotNull(location.Location);

            // Backup location properties
            // TODO: Check with teams.
        }
Beispiel #9
0
        public void addToLbSaveLocation(BackupLocation loc)
        {
            firedumpdbDataSet.backup_locationsRow row = (firedumpdbDataSet.backup_locationsRow)loc.Tag;
            //row.service_type 0=local,1=ftp,2=dropbox,3=googledrive
            ListViewItem item = new ListViewItem(row.name, (int)row.service_type);

            item.SubItems.Add(loc.path);
            item.Tag = (firedumpdbDataSet.backup_locationsRow)loc.Tag;
            if (lbSaveLocations.Items.Contains(findItemSaveLoc(loc)))
            {
                return;
            }
            lbSaveLocations.Items.Add(item);
        }
Beispiel #10
0
        private void bAdd_Click(object sender, EventArgs e)
        {
            if (cmbName.Items.Count == 0 || cmbName.SelectedIndex == -1)
            {
                MessageBox.Show("There are no save locations. Please create a new save location and try again.", "Add save location", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            Console.WriteLine(cmbName.SelectedValue);
            BackupLocation loc = new BackupLocation();

            loc.id   = unchecked ((int)(Int64)cmbName.SelectedValue);
            loc.path = tbPath.Text;
            loc.Tag  = findRow(loc.id);
            onAddSaveLocation(loc);
        }
Beispiel #11
0
        ///<summary>This is a wrapper method for MiscData.MakeABackup() that will show a progress window so that the user can see progress.
        ///Set isSilent to true to suppress the failure message boxes.  However, the progress window will always be shown.
        ///Returns false if making a backup failed.</summary>
        public static bool MakeABackup(bool isSilent, BackupLocation backupLocation, bool isSecurityLogged = true)
        {
            if (DataConnection.DBtype == DatabaseType.Oracle)
            {
                return(false);               //Because MiscData.MakeABackup() is not yet Oracle compatible.
            }
#if DEBUG
            switch (MessageBox.Show("Would you like to make a backup of the DB?", "DEBUG ONLY", MessageBoxButtons.YesNoCancel))
            {
            case DialogResult.Cancel:
                return(false);

            case DialogResult.No:
                return(true);

            case DialogResult.Yes:
            default:
                //do nothing, make backup like usual.
                break;
            }
#endif
            //Create a thread that will show a window and then stay open until the closing action is called.
            Action actionCloseBackupProgress = ODProgressOld.ShowProgressStatus("BackupProgress", null);
            try {
                MiscData.MakeABackup();
                actionCloseBackupProgress(); //Close the progress window.
            }
            catch (Exception ex) {           //MiscData.MakeABackup() could have thrown an exception.
                actionCloseBackupProgress(); //Close the progress window.
                //Show the user that something what went wrong when not in silent mode.
                if (!isSilent)
                {
                    if (ex.Message != "")
                    {
                        MessageBox.Show(ex.Message);
                    }
                    //Reusing translation in ClassConvertDatabase, since it is most likely the only place a translation would have been performed previously.
                    MsgBox.Show("ClassConvertDatabase", "Backup failed. Your database has not been altered.");
                }
                return(false);
            }
            if (isSecurityLogged && PrefC.GetStringNoCache(PrefName.UpdateStreamLinePassword) != "abracadabra")
            {
                SecurityLogs.MakeLogEntryNoCache(Permissions.Backup, 0, Lan.g("Backups", "A backup was created when running the") + " " + backupLocation.ToString());
            }
            return(true);
        }
Beispiel #12
0
        private ListViewItem findItemSaveLoc(BackupLocation loc)
        {
            ListViewItem item      = new ListViewItem();
            int          i         = 0;
            bool         foundflag = false;


            while (!foundflag && i < lbSaveLocations.Items.Count)
            {
                firedumpdbDataSet.backup_locationsRow tag = (firedumpdbDataSet.backup_locationsRow)lbSaveLocations.Items[i].Tag;
                tag.BeginEdit();
                if (tag.id == loc.id)
                {
                    item      = lbSaveLocations.Items[i];
                    foundflag = true;
                }
                i++;
                tag.CancelEdit();
            }
            return(item);
        }
Beispiel #13
0
        public void addToLbSaveLocation(BackupLocation loc)
        {
            firedumpdbDataSet.backup_locationsRow row = (firedumpdbDataSet.backup_locationsRow)loc.Tag;
            int imageindex;

            switch (row.service_type)
            {
            case 0:     //local
                imageindex = 0;
                break;

            case 1:     //ftp
                imageindex = 1;
                break;

            case 2:     //dropbox
                imageindex = 2;
                break;

            case 3:     //google drive
                imageindex = 3;
                break;

            default:
                imageindex = 0;
                break;
            }
            ListViewItem item = new ListViewItem(row.name, imageindex);

            item.SubItems.Add(loc.path);
            item.Tag = (firedumpdbDataSet.backup_locationsRow)loc.Tag;
            ListViewItem saveItem = findItemSaveLoc(loc);

            if (lbSaveLocations.Items.Contains(saveItem))
            {
                return;
            }
            lbSaveLocations.Items.Add(item);
        }
Beispiel #14
0
        /// <summary>
        /// Update a backup location.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Name of the resource group.
        /// </param>
        /// <param name='location'>
        /// Name of the backup location.
        /// </param>
        /// <param name='backup'>
        /// Backup location object.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        public async Task <AzureOperationResponse <BackupLocation> > UpdateWithHttpMessagesAsync(string resourceGroupName, string location, BackupLocation backup, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            // Send Request
            AzureOperationResponse <BackupLocation> _response = await BeginUpdateWithHttpMessagesAsync(resourceGroupName, location, backup, customHeaders, cancellationToken).ConfigureAwait(false);

            return(await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false));
        }
Beispiel #15
0
        /// <summary>
        /// Mirrors the given source file to the given destination file. This means new files are added
        /// and newer files are updated.
        /// Returns true when at least one modification was done, else false.
        /// </summary>
        /// <param name="backupLocation">the backup location for which the backup is run</param>
        /// <param name="srcFile">the source file to be mirrored</param>
        /// <param name="destDir">the destination file to contain the backup</param>
        /// <param name="dryRun">true if changes should only be shown but not actually be made</param>
        /// <returns>true when modifications, else false</returns>
        private bool BackupFileIfNewer(BackupLocation backupLocation, string srcFile, string destDir, bool dryRun)
        {
            // get the file path without the path given in the BackupLocation
            // => that shortens the path for a clearer output to the user
            string pathWithoutLocationPrefix = srcFile.Remove(0, backupLocation.Path.Length);

            // combine the destination directory with the file name
            // => backup path for the file
            string destOfFile = Path.Combine(destDir, Path.GetFileName(srcFile));

            // backup the file if not existing yet
            if (!File.Exists(destOfFile))
            {
                // output to user
                ConsoleWriter.WriteBackupAddition(pathWithoutLocationPrefix);

                // backup
                if (!dryRun)
                {
                    File.Copy(srcFile, destOfFile, true);
                }

                // return true because a new file was added
                return(true);
            }

            // backup the file if newer on source path than in destination path
            if (File.GetLastWriteTime(srcFile) > File.GetLastWriteTime(destOfFile))
            {
                // control message
                //Logger.LogInfo("Backup: {0} => {1}", srcFile, destOfFile);

                // user output, show only the part of the source path after the BackupLocation-path for
                // a clearer output
                ConsoleWriter.WriteBackupUpdate(pathWithoutLocationPrefix);

                // if the destination part already exists and is readonly, mark it as writeable so that it
                // can be removed
                // => e.g. needed for git-files since they are read-only
                if (File.Exists(destOfFile) && !dryRun)
                {
                    FileInfo destFileInfo = new FileInfo(destOfFile);
                    if (destFileInfo.IsReadOnly)
                    {
                        new FileInfo(destOfFile).IsReadOnly = false;
                        //File.SetAttributes(destOfFile, FileAttributes.Normal);
                    }
                }

                // backup
                if (!dryRun)
                {
                    File.Copy(srcFile, destOfFile, true);
                }

                // return true because newer file
                return(true);
            }

            // false because no newer file
            return(false);
        }
Beispiel #16
0
 private void onAddSaveLocation(BackupLocation loc)
 {
     AddSaveLocation?.Invoke(loc);
 }
Beispiel #17
0
 private void onSaveLocationEdited(BackupLocation loc)
 {
     SaveLocationEdited?.Invoke(loc);
 }
Beispiel #18
0
 private void onSaveLocationDeletedAfter(BackupLocation loc)
 {
     SaveLocationDeletedAfter?.Invoke(loc);
 }
Beispiel #19
0
        /// <summary>
        /// Deletes files and subdirectories contained in the destination directory but not contained in the given
        /// source directory.
        /// Returns true when at least one modification was done, else false.
        /// </summary>
        /// <param name="backupLocation">the backup location for which the backup is run</param>
        /// <param name="srcDir">the source directory to be mirrored</param>
        /// <param name="destDir">the destination directory to contain the backup</param>
        /// <param name="dryRun">true if changes should only be shown but not actually be made</param>
        /// <returns>true when modifications, else false</returns>
        private bool DeleteFilesAndSubdirsNotContainedAnymore(BackupLocation backupLocation, string srcDir, string destDir, bool dryRun)
        {
            // result flag
            // => true if at least one change had been made
            bool atLeastOneDeleted = false;

            // if a dry run is done the destination directory might not exist since it might not be created before
            // because of the dry flag
            // => in this case the method cannot be executed without errors since no file and sub directory can be
            //    deleted in the destination directory when the destination directory does not exist itself
            if (dryRun && !Directory.Exists(destDir))
            {
                return(false);
            }

            // delete all files in the destination directory which are not (any more) in the source directory
            foreach (string destFile in Directory.GetFiles(destDir))
            {
                // determine the source path of each file in the destination path to check whether
                // the file exists on the source path
                string shouldBeSrcFile = Path.Combine(srcDir, Path.GetFileName(destFile));

                // get the file path without the path given in the BackupLocation
                // => that shortens the path for a clearer output to the user
                string pathWithoutLocationPrefix = shouldBeSrcFile.Remove(0, backupLocation.Path.Length);

                // remove the file in the destination path if there is no corresponding file in the source path
                if (!File.Exists(shouldBeSrcFile))
                {
                    // control message
                    //Logger.LogInfo("Deleted: {0}", shouldBeSrcFile);

                    // output for user
                    ConsoleWriter.WriteBackupRemove(pathWithoutLocationPrefix);

                    // mark the destination file as writeable if it is readonly so that it can be removed
                    // => e.g. needed for git-files since they are read-only
                    FileInfo destFileInfo = new FileInfo(destFile);
                    if (destFileInfo.IsReadOnly && !dryRun)
                    {
                        new FileInfo(destFile).IsReadOnly = false;
                        //File.SetAttributes(destOfFile, FileAttributes.Normal);
                    }

                    // remove file
                    if (!dryRun)
                    {
                        File.Delete(destFile);
                    }

                    // update change-flag
                    if (!atLeastOneDeleted)
                    {
                        atLeastOneDeleted = true;
                    }
                }
            }

            // remove all sub directories in the destination path which do not (any more) exist at the source path
            foreach (string destSubDir in Directory.GetDirectories(destDir))
            {
                // determine the source path of each sub directory in the destination path to check whether
                // the sub directory exists on the source path (needs to be asked as file name!)
                string shouldBeSrcDir = Path.Combine(srcDir, Path.GetFileName(destSubDir));

                // get the sub directory path without the path given in the BackupLocation
                // => that shortens the path for a clearer output to the user
                string pathWithoutLocationPrefix = shouldBeSrcDir.Remove(0, backupLocation.Path.Length);

                // remove the sub directory if there is no corresponding sub directory at the source path
                if (!Directory.Exists(shouldBeSrcDir))
                {
                    // control message
                    //Logger.LogInfo("Removed sub dir: {0}", shouldBeSrcDir);

                    // output to user
                    ConsoleWriter.WriteBackupRemove(pathWithoutLocationPrefix);

                    // delete this sub directory recursively
                    // => own method because read only attributes might be changed
                    DeleteDirectoryRecursively(destSubDir, dryRun);

                    // update change-flag
                    if (!atLeastOneDeleted)
                    {
                        atLeastOneDeleted = true;
                    }
                }
            }

            // return the change flag
            // => true if some file or folder was updated
            return(atLeastOneDeleted);
        }
Beispiel #20
0
        /// <summary>
        /// Mirrors the given source directory to the given destination directory. This means new files are added,
        /// not anymore existing files at the source will be deleted at the destination and newer files or
        /// subdirectories are updated. Returns true when at least one modification was done, else false.
        /// </summary>
        /// <param name="backupLocation">the backup location for which the backup is run</param>
        /// <param name="srcDir">the source directory to be mirrored</param>
        /// <param name="destDir">the destination directory to contain the backup</param>
        /// <param name="excludePaths">maybe defined exclude paths which are not to consider when doing the backup</param>
        /// <param name="dryRun">true if changes should only be shown but not actually be made</param>
        /// <returns>true when modifications, else false</returns>
        private bool BackupDirectoryRecursively(BackupLocation backupLocation, string srcDir, string destDir,
                                                IList <string> excludePaths, bool dryRun)
        {
            // return flag
            // => true, if at least one file or folder was updated/added/removed
            bool atLeastOneUpdated = false;

            // create the destination directory if it does not yet exist
            if (!Directory.Exists(destDir) && !dryRun)
            {
                Directory.CreateDirectory(destDir);
                atLeastOneUpdated = true;
            }

            // backup all newer files from the source to the destination path if not excluded
            foreach (string srcFile in Directory.GetFiles(srcDir))
            {
                if (!_excludeUtil.ShouldFileBeExcluded(srcFile, excludePaths))
                {
                    // control message
                    //Logger.LogInfo("Check {0}", srcFile);

                    // backup
                    bool saved = BackupFileIfNewer(backupLocation, srcFile, destDir, dryRun);

                    // update change-flag if necessary
                    if (!atLeastOneUpdated && saved)
                    {
                        atLeastOneUpdated = true;
                    }
                }
            }

            // remove all files and directories that are no longer contained at the source path
            bool atLeastOneDeleted = DeleteFilesAndSubdirsNotContainedAnymore(backupLocation, srcDir, destDir, dryRun);

            // update change-flag
            if (!atLeastOneUpdated && atLeastOneDeleted)
            {
                atLeastOneUpdated = true;
            }

            // repeat backup at all sub directories if not excluded
            foreach (string subDir in Directory.GetDirectories(srcDir))
            {
                if (!_excludeUtil.ShouldDirectoryBeExcluded(subDir, excludePaths))
                {
                    // combine destination path with sub directory name (must be got as file name!)
                    // => backup path for sub folder
                    string destOfSubDir = Path.Combine(destDir, Path.GetFileName(subDir));

                    // backup the sub directory
                    bool atLeastOneNewerInSubDir = BackupDirectoryRecursively(
                        backupLocation, subDir, destOfSubDir, excludePaths, dryRun);

                    // update change-flag if necessary
                    if (!atLeastOneUpdated && atLeastOneNewerInSubDir)
                    {
                        atLeastOneUpdated = true;
                    }
                }
            }

            // return if at least one file/folder was updated
            return(atLeastOneUpdated);
        }
Beispiel #21
0
        /// <summary>
        /// Update a backup location.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Name of the resource group.
        /// </param>
        /// <param name='location'>
        /// Name of the backup location.
        /// </param>
        /// <param name='backup'>
        /// Backup location object.
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <AzureOperationResponse <BackupLocation> > BeginUpdateWithHttpMessagesAsync(string resourceGroupName, string location, BackupLocation backup, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (Client.SubscriptionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
            }
            if (resourceGroupName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
            }
            if (location == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "location");
            }
            if (Client.ApiVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
            }
            if (backup == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "backup");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("location", location);
                tracingParameters.Add("backup", backup);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "BeginUpdate", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Backup.Admin/backupLocations/{location}").ToString();

            _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
            _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
            _url = _url.Replace("{location}", System.Uri.EscapeDataString(location));
            List <string> _queryParameters = new List <string>();

            if (Client.ApiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
            }
            if (_queryParameters.Count > 0)
            {
                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("PUT");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
            }


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            if (backup != null)
            {
                _requestContent      = Rest.Serialization.SafeJsonConvert.SerializeObject(backup, Client.SerializationSettings);
                _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            }
            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200 && (int)_statusCode != 202)
            {
                var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <CloudError>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex      = new CloudException(_errorBody.Message);
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_httpResponse.Headers.Contains("x-ms-request-id"))
                {
                    ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                }
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationResponse <BackupLocation>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <BackupLocation>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            // Deserialize Response
            if ((int)_statusCode == 202)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <BackupLocation>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
 /// <summary>
 /// Update a backup location.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Name of the resource group.
 /// </param>
 /// <param name='location'>
 /// Name of the backup location.
 /// </param>
 /// <param name='backup'>
 /// Backup location object.
 /// </param>
 public static BackupLocation BeginUpdate(this IBackupLocationsOperations operations, string resourceGroupName, string location, BackupLocation backup)
 {
     return(operations.BeginUpdateAsync(resourceGroupName, location, backup).GetAwaiter().GetResult());
 }
Beispiel #23
0
 private void onSaveLocationDeletedHandler(BackupLocation loc)
 {
     this.backup_locationsTableAdapter.Fill(this.firedumpdbDataSet.backup_locations);
     //EDW NA KANEI SELECT OTI ALLAKSE TELEUTAIO
 }
Beispiel #24
0
 ///<summary>This is a wrapper method for MiscData.MakeABackup() that will show a progress window so that the user can see progress.
 ///Returns false if making a backup failed.</summary>
 public static bool MakeABackup(BackupLocation backupLocation)
 {
     return(MakeABackup(false, backupLocation));
 }
 /// <summary>
 /// Update a backup location.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Name of the resource group.
 /// </param>
 /// <param name='location'>
 /// Name of the backup location.
 /// </param>
 /// <param name='backup'>
 /// Backup location object.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <BackupLocation> BeginUpdateAsync(this IBackupLocationsOperations operations, string resourceGroupName, string location, BackupLocation backup, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.BeginUpdateWithHttpMessagesAsync(resourceGroupName, location, backup, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
 public VerifiedBackupLocation(BackupLocation backupLocation) : base(backupLocation.FilePath, backupLocation.BackupFileName)
 {
     this.DirectoryInfo = new DirectoryInfo(backupLocation.FilePath);
 }
Beispiel #27
0
        /// <summary>
        /// Backups the given source file into the given destination directory.
        /// This method is to be used only for files which are given as src attribute inside backup profiles.
        /// Returns true if the file was created or modified, else false.
        /// </summary>
        /// <param name="backupLocation">the backup location for which the backup is run</param>
        /// <param name="srcFile">the source file to be backed up</param>
        /// <param name="destDir">the destination directory to contain the backup</param>
        /// <param name="dryRun">true if changes should only be shown but not actually be made</param>
        /// <returns>true if the file was created or modified, else false</returns>
        private bool BackupFileBackupLocation(BackupLocation backupLocation, string srcFile, string destDir, bool dryRun)
        {
            // create the destination directory if it does not yet exist
            // => is not yet created because the backup location is a file and not a directory
            if (!Directory.Exists(destDir) && !dryRun)
            {
                Directory.CreateDirectory(backupLocation.Destination);
            }

            // combine the destination directory with the file name
            // => backup path for the file
            string destOfFile = Path.Combine(destDir, Path.GetFileName(srcFile));

            // backup the file if not existing yet
            if (!File.Exists(destOfFile))
            {
                // output to user
                ConsoleWriter.WriteBackupAddition(srcFile);

                // backup
                if (!dryRun)
                {
                    File.Copy(srcFile, destOfFile, true);
                }

                // return true because a new file was added
                return(true);
            }

            // backup the file if newer on source path than in destination path
            if (File.GetLastWriteTime(srcFile) > File.GetLastWriteTime(destOfFile))
            {
                // control message
                //Logger.LogInfo("Backup: {0} => {1}", srcFile, destOfFile);

                // user output, show only the part of the source path after the BackupLocation-path for
                // a clearer output
                ConsoleWriter.WriteBackupUpdate(srcFile);

                // if the destination part already exists and is readonly, mark it as writeable so that it
                // can be removed
                // => e.g. needed for git-files since they are read-only
                if (File.Exists(destOfFile) && !dryRun)
                {
                    FileInfo destFileInfo = new FileInfo(destOfFile);
                    if (destFileInfo.IsReadOnly)
                    {
                        new FileInfo(destOfFile).IsReadOnly = false;
                        //File.SetAttributes(destOfFile, FileAttributes.Normal);
                    }
                }

                // backup
                if (!dryRun)
                {
                    File.Copy(srcFile, destOfFile, true);
                }

                // return true because newer file
                return(true);
            }

            // false because no newer file
            return(false);
        }