Ejemplo n.º 1
0
        private void btn_SaveSettings_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txt_BackupFrom.Text))
            {
                MessageBox.Show(Constants.BackupFromErrorMessage, Constants.InformativeMessage);
            }
            else if (string.IsNullOrEmpty(txt_BackupTo.Text))
            {
                MessageBox.Show(Constants.BackupToErrorMessage, Constants.InformativeMessage);
            }
            else
            {
                BackupModel backupModel = new BackupModel();
                backupModel.BackupFrom    = txt_BackupFrom.Text;
                backupModel.BackupTo      = txt_BackupTo.Text;
                backupModel.Description   = txt_Description.Text;
                backupModel.BackupDetails = txt_BackupDetails.Text;
                backupModel.BackupTime    = txt_BackupTime.Text;

                Persistence persistence = new Persistence();
                persistence.SaveBackupFormInfo(backupModel);

                Close();

                Service service = new Service();
                service.CreateTaskScheduler();
            }
        }
Ejemplo n.º 2
0
        public JsonResult GetBackupFiles()
        {
            string backupFolder = ConfigurationManager.AppSettings["BackupFolder"];
            string path         = Path.Combine(Server.MapPath("~"), backupFolder);
            //var files = Directory.GetFiles(path,"*");

            DirectoryInfo info  = new DirectoryInfo(path);
            var           files = info.GetFiles().OrderByDescending(p => p.LastWriteTime);

            var result = new BackupModel();

            result.RelativeUrl = backupFolder;
            result.Files       = new List <BackupFileModel>();
            foreach (FileInfo file in files)
            {
                if (file.Extension == ".bak")
                {
                    result.Files.Add(new BackupFileModel {
                        FileName = file.Name, Created = file.CreationTime, Modified = file.LastWriteTime
                    });
                }
            }

            var jsonResult = new JsonResult {
                JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = result
            };

            return(jsonResult);
        }
Ejemplo n.º 3
0
        public bool Create(string currentDirectory, BackupModel model)
        {
            GlobalConfig.Database = model.Database;

            string fullFileInfoPath = $"{currentDirectory}\\{GlobalConfig.BackupAppFileInfo}";

            if (File.Exists(fullFileInfoPath))
            {
                int nextBackup = model.CurrentFile + 1;
                TextProcessor.UpdateCurrentFile(nextBackup, fullFileInfoPath);

                string backupFolder = model.SourceDir + "\\";
                GlobalConfig.Connection.CreateBackup(model.Database, backupFolder);

                _compression.Create(model, GlobalConfig.BackupPassword);

                string filePath = $@"{model.DestinationDir}\{model.Name}_{model.CurrentFile}.{model.CompressionType}";

                if (!_compression.CheckCompressedFile(filePath))
                {
                    throw new Exception("Compressed file corrupted!");
                }

                return(true);
            }
            else
            {
                throw new Exception($"{GlobalConfig.BackupAppFileInfo} file doesn't exist!");
            }
        }
 public ActionResult Index()
 {
     try
     {
         string FilePathXML = HttpContext.Server.MapPath("~/App_Data/config.xml");
         var    doc         = XDocument.Load(FilePathXML);
         bool   isAdmin     = CurrentUser.UserName.Equals(UserDAL.ADMIN);
         ViewBag.ShowBackupMenu = IsFunctionInRole(ActionName.BACKUPDATABASE.ToString()) || isAdmin;
         ViewBag.ShowDeleteMenu = ViewBag.ShowRestoreMenu = IsFunctionInRole(ActionName.RESTOREDATABASE.ToString()) || isAdmin;
         string        folderName = doc.Element("system.config").Element("path-backup").Value;
         string[]      files      = Directory.GetFiles(folderName);
         var           list       = new List <BackupModel>();
         DirectoryInfo di         = new DirectoryInfo(folderName);
         foreach (FileInfo item in di.GetFiles())
         {
             BackupModel tmp = new BackupModel()
             {
                 Name = item.Name,
                 Date = item.LastWriteTime.ToShortDateString(),
             };
             list.Add(tmp);
         }
         list = list.OrderByDescending(m => m.Date).ToList();
         if (Request.IsAjaxRequest())
         {
             return(PartialView("_RestorePartial", list));
         }
         return(View(list));
     }
     catch { return(View()); }
 }
Ejemplo n.º 5
0
        public async Task Execute(IJobExecutionContext context)
        {
            var tasks         = (List <TaskModel>)context.JobDetail.JobDataMap["tasks"];
            var backupService = (BackupService)context.JobDetail.JobDataMap["backupService"];

            foreach (var task in tasks)
            {
                task.BackupResult = "";
                var progress = new Progress <string>(status =>
                {
                    logger.Info(status);
                });
                BackupModel model = new BackupModel()
                {
                    PathToBackup      = task.SelectedPath,
                    DatabasesToBackup = task.SelectedDatabases
                };
                try
                {
                    await backupService.BackupDatabases(model, progress, null, task.SQLServer);

                    task.BackupResult = model.BackupResult;
                }
                catch (Exception ex)
                {
                    logger.Error(ex.StackTrace);
                    task.BackupResult = model.BackupResult;
                }
            }
            SendEmailNotifications(tasks);
        }
Ejemplo n.º 6
0
        private bool BackupStatus()
        {
            string      filePath    = $"{_currentDirectory}\\{GlobalConfig.BackupAppFileInfo}";
            BackupModel backupModel = filePath.LoadFile().ConvertToBackUpModel();

            Backup backup = new Backup(new SharpCompression());
            bool   status = backup.Create(_currentDirectory, backupModel);

            return(status);
        }
        private void DisplayInfo_Load(object sender, EventArgs e)
        {
            string      filePath    = $"{_currentDirectory}\\{GlobalConfig.BackupAppFileInfo}";
            BackupModel backupModel = filePath.LoadFile().ConvertToBackUpModel();

            Backup backup = new Backup(new SharpCompression());
            bool   status = backup.Create(_currentDirectory, backupModel);

            //this.notifyIcon.Icon = (status == true) ?
            //    new Icon(_backupIcon[BackupIconType.SUCCESSFUL]) :
            //    new Icon(_backupIcon[BackupIconType.ERROR]);

            //this.notifyIcon.Text = (status == true) ?
            //    $"Backup OK - {DateTime.Now}" :
            //    $"Backup Error - {DateTime.Now}";
            string messageContent = "";

            if (status == true)
            {
                this.notifyIcon.Icon = new Icon(_backupIcon[BackupIconType.SUCCESSFUL]);
                this.notifyIcon.Text = $"Backup OK - {DateTime.Now}";
                messageContent       = $"Backup successful - Date: {DateTime.Now}";
            }
            else
            {
                this.notifyIcon.Icon = new Icon(_backupIcon[BackupIconType.ERROR]);
                this.notifyIcon.Text = $"Backup Error - {DateTime.Now}";
                messageContent       = $"Backup unsuccessful - Date: {DateTime.Now}";
            }

            string emailConfigFilePath  = $"{_currentDirectory}\\{GlobalConfig.EmailConfig}";
            string notificationFilePath = $"{_currentDirectory}\\{GlobalConfig.BackupAppNotifFileInfo}";

            Notification notification = new Notification();

            if (File.Exists(emailConfigFilePath))
            {
                EmailModel emailModel = emailConfigFilePath.LoadFile().ConvertToEmailModel();
                emailModel.Body = messageContent;
                notification.Add(new Email(emailModel));
            }

            if (File.Exists(emailConfigFilePath))
            {
                notification.Add(new Text(messageContent, notificationFilePath));
            }

            notification.Send();

            Thread.Sleep(60 * 1000);
            this.Close();
        }
Ejemplo n.º 8
0
        private void Compress(string destinationFile, BackupModel model)
        {
            using (ZipFile zip = new ZipFile(destinationFile))
            {
                if (!String.IsNullOrEmpty(_password))
                {
                    zip.Password = _password;
                }

                zip.Encryption = EncryptionAlgorithm.WinZipAes256;
                zip.AddSelectedFiles(SelectedFileQuery(model.BackupFiles), model.SourceDir, model.Name, true);
                zip.Save();
            }
        }
Ejemplo n.º 9
0
        private void InitializeCompression(BackupModel model)
        {
            _format = GetCompressionExtension(model.CompressionType);

            if (!String.IsNullOrEmpty(_format))
            {
                _destinationFile = $@"{model.DestinationDir}\{model.Name}_{model.CurrentFile}{_format}";
                Compress(_destinationFile, model);
            }
            else
            {
                throw new Exception("Please insert correct compression type format!");
            }
        }
Ejemplo n.º 10
0
 private void Initialize(Model origin)
 {
     if (origin.IsInitialized)
     {
         _origin = origin;
         var originChildModels = origin.ChildModels;
         for (int i = 0; i < originChildModels.Count; i++)
         {
             var childBackupModel = new BackupModel();
             childBackupModel.Construct(this, this.GetType(), "ChildModel" + i.ToString(CultureInfo.InvariantCulture));
             childBackupModel.Initialize(originChildModels[i]);
         }
     }
 }
Ejemplo n.º 11
0
 private Action <DataRow> Backup()
 {
     if (Model.EditingRow == null && !HasChild)
     {
         Model.BeginEdit(this);
         return(dataRow => dataRow.Model.EndEdit(true));
     }
     else
     {
         var backupDataSet = BackupModel.Backup(Model);
         var backupDataRow = backupDataSet.AddRow(dataRow => dataRow.Backup(this));
         return(dataRow => dataRow.Restore(backupDataRow));
     }
 }
Ejemplo n.º 12
0
        public static BackupModel ConvertToBackUpModel(this List <string> lines)
        {
            BackupModel model = new BackupModel();

            model.SourceDir       = ValueExtraction(lines[0]);
            model.DestinationDir  = ValueExtraction(lines[1]);
            model.Database        = ValueExtraction(lines[2]);
            model.Name            = ValueExtraction(lines[3]);
            model.CompressionType = ValueExtraction(lines[4]);
            model.BackupFiles     = ValueExtraction(lines[5]).Split(',').ToList();
            model.CurrentFile     = Convert.ToInt32(ValueExtraction(lines[6]));

            return(model);
        }
Ejemplo n.º 13
0
        private void InsertCategoriesFromJsonBackup()
        {
            var jsonBackup = File.ReadAllText(HostingEnvironment.ApplicationPhysicalPath + @"/Data/backup.json");

            var serializer = new DataContractJsonSerializer(typeof(BackupModel));
            var stream     = new MemoryStream(Encoding.UTF8.GetBytes(jsonBackup));

            BackupModel backupData = serializer.ReadObject(stream) as BackupModel;

            backupData.CategoryList.ToList().ForEach(c =>
            {
                CategoryModel category = new CategoryModel(c.RowKey, c.Name, c.Description, c.Depth, c.ParentID);
                new CategoryRepository().Save(category);
            });
        }
Ejemplo n.º 14
0
        public async Task <BackupModel> ConnectToSqlServer(LoginModel model)
        {
            var SystemDatabases = new List <string>()
            {
                "master", "msdb", "model", "resource", "tempdb"
            };
            var list = new List <String>();
            var IntegratedSecurity = "False";

            if (loginTypesReadableList.GetEnumItem(model.LoginType) == LoginTypesEnumeration.Windows)
            {
                IntegratedSecurity = "True";
            }
            var connectionString = $"Data Source={model.Servername}; User ID={model.Username}; Password={model.Password}; Integrated Security={IntegratedSecurity};";

            using (SqlConnection con = new SqlConnection(connectionString))
            {
                try
                {
                    await con.OpenAsync();

                    SetSqlServerConnection(connectionString, model);
                    //await Task.Run(() => databaseController.Initialize());
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                using (SqlCommand cmd = new SqlCommand("SELECT name from sys.databases", con))
                {
                    using (SqlDataReader dr = cmd.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            var name = dr[0].ToString();
                            if (!SystemDatabases.Contains(name))
                            {
                                list.Add(dr[0].ToString());
                            }
                        }
                    }
                }
                var backupModel = new BackupModel();
                backupModel.AllDatabases = list;
                Context.backupModel      = backupModel;
                return(backupModel);
            }
        }
Ejemplo n.º 15
0
        public void SaveBackupFormInfo(BackupModel backupModel)
        {
            CheckIfJsonFileExist();

            var jsonText = File.ReadAllText(_persistancePath);
            var request  = JsonConvert.DeserializeObject <JsonRequestModel>(jsonText);

            if (request == null)
            {
                request = new JsonRequestModel();
            }

            request.BackupModel = backupModel;
            var json = JsonConvert.SerializeObject(request);

            File.WriteAllText(_persistancePath, json);
        }
Ejemplo n.º 16
0
        public ActionResult Backup()
        {
            BackupModel   model = new BackupModel();
            StringBuilder sb    = new StringBuilder();

            model.Drzave             = drzavaRepository.List().ToList();
            model.Gradovi            = gradRepository.List().ToList();
            model.Vozaci             = vozacRepository.List().ToList();
            model.Vozila             = voziloRepository.List().ToList();
            model.PutniNalozi        = putniNalogRepository.List().ToList();
            model.Relacije           = relacijaRepository.List().ToList();
            model.KategorijeTroskova = kategorijaTroska.List().ToList();
            model.KategorijeServisa  = kategorijaServisRepository.List().ToList();
            model.Servisi            = servisRepository.List().ToList();
            sb.Append(Server.MapPath("/")).Append("DBBackup-").Append(DateTime.Now.ToLongDateString()).Append(".xml");
            model.Save(sb.ToString());
            return(View());
        }
Ejemplo n.º 17
0
        private void SetBackupModelInfo(BackupModel backupModel, Persistence persistence, Service service)
        {
            backupModel.BackupFrom    = txt_BackupFrom.Text;
            backupModel.BackupTo      = txt_BackupTo.Text;
            backupModel.Description   = txt_Description.Text;
            backupModel.BackupDetails = txt_BackupDetails.Text;
            backupModel.BackupTime    = txt_BackupTime.Text;
            _backupModelList.Add(backupModel);

            persistence.SaveBackupFormInfo(_backupModelList, _isNewTask);

            Hide();

            service.CreateTaskScheduler(backupModel.BackupName, false);

            var tmBackupTasksForm = new TMBackupTasksForm();

            tmBackupTasksForm.ShowDialog();
        }
Ejemplo n.º 18
0
        public void SaveBackupModel(BackupModel backupModel)
        {
            var jsonText = File.ReadAllText(_persistancePath);
            var request  = JsonConvert.DeserializeObject <JsonRequestModel>(jsonText);

            if (backupModel != null && request.BackupModelList != null)
            {
                foreach (var item in request.BackupModelList)
                {
                    if (item.BackupName.Equals(backupModel.BackupName))
                    {
                        request.BackupModelList.Remove(item);
                        break;
                    }
                }
                request.BackupModelList.Add(backupModel);
                WriteJsonRequestModel(request);
            }
        }
Ejemplo n.º 19
0
        private void btn_SaveSettings_Click(object sender, EventArgs e)
        {
            BackupModel backupModel = new BackupModel();

            backupModel.BackupFrom    = txt_BackupFrom.Text;
            backupModel.BackupTo      = txt_BackupTo.Text;
            backupModel.Description   = txt_Description.Text;
            backupModel.BackupDetails = txt_BackupDetails.Text;
            backupModel.BackupTime    = txt_BackupTime.Text;

            Persistence persistence = new Persistence();

            persistence.SaveBackupFormInfo(backupModel);

            this.Close();

            Service service = new Service();

            service.CreateTaskScheduler(false);
        }
 public List <BackupModel> ListRestoreOnline()
 {
     try
     {
         var ftpFiles = FTPUtilities.GetFiles("/db");
         var lst      = new List <BackupModel>();
         foreach (var item in ftpFiles)
         {
             var obj = new BackupModel();
             obj.Name = item.Name;
             if (item.LastWriteTime != null)
             {
                 obj.Date = item.LastWriteTime.Value.ToShortDateString();
             }
             lst.Add(obj);
         }
         return(lst);
     }
     catch { return(null); }
 }
Ejemplo n.º 21
0
        //
        // GET: /Backup/

        public JsonResult Index()
        {
            var buyerRequestList        = new BuyerRequestRepository().GetAll();
            var categoryList            = new CategoryRepository().GetAll();
            var companyList             = new CompanyRepository().GetAll();
            var companySubscriptionList = new CompanySubscriptionRepository().GetAll();
            var productList             = new ProductRepository().GetAll();
            var transactionList         = new TransactionRepository().GetAll();

            var backupResult =
                new BackupModel
            {
                BuyerRequestList        = buyerRequestList,
                CategoryList            = categoryList,
                CompanyList             = companyList,
                CompanySubscriptionList = companySubscriptionList,
                ProductList             = productList,
                TransactionList         = transactionList
            };

            return(Json(backupResult, JsonRequestBehavior.AllowGet));
        }
Ejemplo n.º 22
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="backupModel"></param>
        /// <param name="stagesProgress">Этапы, которые попадают в лог</param>
        /// <param name="detailProgress">Детальная информация о выполнении бэкапа</param>
        /// <returns></returns>
        public async Task <string> BackupDatabases(BackupModel backupModel, IProgress <string> stagesProgress, IProgress <string> detailProgress, string ServerName = "")
        {
            string connectionString = "";

            if (string.IsNullOrWhiteSpace(ServerName))
            {
                connectionString = Context.GetDBConnectionString();
            }
            else
            {
                connectionString = $"Data Source={ServerName}; Integrated Security=True;";
            }
            int stepCount = backupModel.DatabasesToBackup.Count();

            if (detailProgress != null)
            {
                detailProgress.Report($"Всего баз данных - {stepCount}. Начали...");
            }
            if (!string.IsNullOrWhiteSpace(connectionString))
            {
                foreach (var database in backupModel.DatabasesToBackup)
                {
                    var    dateNow          = DateTime.Now.ToString("dd'.'MM'.'yyyy");
                    var    timeNow          = DateTime.Now.ToLongTimeString();
                    string path             = backupModel.PathToBackup + "\\" + dateNow + "\\" + database;
                    var    databaseFileName = database + " " + timeNow.Replace(":", ".");
                    try
                    {
                        Directory.CreateDirectory(path);
                    }
                    catch (NotSupportedException ex)
                    {
                        stagesProgress.Report($"{database} - {ex.Message}");
                        if (!string.IsNullOrWhiteSpace(backupModel.BackupResult))
                        {
                            backupModel.BackupResult += "<br />";
                        }
                        backupModel.BackupResult += $"База {database} - {ex.Message}";
                        throw ex;
                    }
                    await Task.Run(() =>
                    {
                        try
                        {
                            if (!string.IsNullOrWhiteSpace(Context.GetServerInstanceName()))
                            {
                                ServerName = Context.GetServerInstanceName();
                            }
                            BackupDatabase(ServerName, database, path, detailProgress);
                            stagesProgress.Report($"База {database} - успех");
                            if (!string.IsNullOrWhiteSpace(backupModel.BackupResult))
                            {
                                backupModel.BackupResult += "<br />";
                            }
                            backupModel.BackupResult += $"База {database} - успех";
                        }
                        catch (Exception ex)
                        {
                            stagesProgress.Report($"База {database} - {ex.Message}");
                            if (!string.IsNullOrWhiteSpace(backupModel.BackupResult))
                            {
                                backupModel.BackupResult += "<br />";
                            }
                            backupModel.BackupResult += $"База {database} - {ex.Message}";
                            throw ex;
                        }
                    });
                }
            }
            return("Бэкап удачно завершен!");
        }
Ejemplo n.º 23
0
        public void ImportBaza(HttpPostedFileBase file)
        {
            if (file.ContentLength > 0)
            {
                using (Stream stream = file.InputStream)
                {
                    using (XmlReader reader = XmlReader.Create(stream))
                    {
                        XmlSerializer serializer = new XmlSerializer(typeof(BackupModel));
                        try
                        {
                            BackupModel m = serializer.Deserialize(reader) as BackupModel;

                            //insert drzava
                            foreach (Drzava drzava in m.Drzave)
                            {
                                drzavaRepository.Delete(drzava.IDDrzava);
                                drzavaRepository.Add(drzava);
                            }
                            //insert gradova
                            foreach (Grad grad in m.Gradovi)
                            {
                                gradRepository.Delete(grad.IDGrad);
                                gradRepository.Add(grad);
                            }
                            //insert vozaca
                            foreach (Vozac vozac in m.Vozaci)
                            {
                                vozacRepository.Delete(vozac.IDVozac);
                                vozacRepository.Add(vozac);
                            }
                            //insert vozila
                            foreach (Vozilo vozilo in m.Vozila)
                            {
                                voziloRepository.Delete(vozilo.IDVozilo);
                                voziloRepository.Add(vozilo);
                            }
                            //insert putnog naloga
                            foreach (PutniNalog nalog in m.PutniNalozi)
                            {
                                putniNalogRepository.Delete(nalog.IDPutniNalog);
                                putniNalogRepository.Add(nalog);
                            }
                            //insert relacije
                            foreach (Relacija relacija in m.Relacije)
                            {
                                relacijaRepository.Delete(relacija.IDRelacija);
                                relacijaRepository.Add(relacija);
                            }
                            //insert kategorija troskova
                            foreach (KategorijaTroska kategorija in m.KategorijeTroskova)
                            {
                                kategorijaTrosakRepository.Delete(kategorija.IDKategorijaTrosak);
                                kategorijaTrosakRepository.Add(kategorija);
                            }
                            // insert kategorija servisa
                            foreach (KategorijaServis kategorijaServis in m.KategorijeServisa)
                            {
                                kategorijaServisRepository.Delete(kategorijaServis.IDKategorijaServis);
                                kategorijaServisRepository.Add(kategorijaServis);
                            }
                            //insert servisa
                            foreach (Servis servis in m.Servisi)
                            {
                                servisRepository.Delete(servis.IDServis);
                                servisRepository.Add(servis);
                            }
                        }
                        catch (InvalidOperationException e)
                        {
                            Console.WriteLine(e.Message);
                        }
                    }
                }
            }
        }
Ejemplo n.º 24
0
 public IResponse PostBackup(BackupModel backup)
 {
     return(Request.Post("/api/ClientSettings/Backup").AddJsonBody(backup)
            .Build().Execute());
 }
Ejemplo n.º 25
0
 public void Create(BackupModel model)
 {
     InitializeCompression(model);
 }
Ejemplo n.º 26
0
        public string getrestore(string token)
        {
            string message = "";

            token = TokenManager.readToken(HttpContext.Current.Request);
            var strP = TokenManager.GetPrincipal(token);

            if (strP != "0") //invalid authorization
            {
                return(TokenManager.GenerateToken(strP));
            }
            else
            {
                int logId = 0;

                UsersLogsController logcntrlr    = new UsersLogsController();
                usersLogs           logITEM      = new usersLogs();
                BackupModel         restoremodel = new BackupModel();

                IEnumerable <Claim> claims = TokenManager.getTokenClaims(token);
                foreach (Claim c in claims)
                {
                    if (c.Type == "logId")
                    {
                        logId = int.Parse(c.Value);
                    }
                    if (c.Type == "fileName")
                    {
                        restoreFilename = c.Value;
                    }
                }
                //get log row befor restore operation
                logITEM = logcntrlr.GetByID(logId);



                try
                {
                    //decode
                    string sourcpath = "";
                    string destpath  = "";

                    bool   decres   = false;
                    string direpath = System.Web.Hosting.HostingEnvironment.MapPath("~\\images\\temp\\");
                    string destfile = "file" + DateTime.Now.ToFileTime() + ".bak";

                    sourcpath = Path.Combine(direpath, restoreFilename);
                    destpath  = Path.Combine(direpath, destfile);
                    //  var files = Directory.GetFiles(System.Web.Hosting.HostingEnvironment.MapPath("~\\images\\temp\\"), filename);


                    if (File.Exists(sourcpath))
                    {
                        //decode file
                        //   decres=decodefile()
                        decres = decodefile(sourcpath, destpath);
                        // delete after decode
                        File.Delete(sourcpath);

                        if (File.Exists(destpath) && decres == true)
                        {
                            //restore
                            message = restoreDB(destpath);
                            // delete after restore
                            File.Delete(destpath);
                            if (message == "1")
                            {
                                logITEM.logId = 0;
                                //save newlog row and return the logId
                                logId = int.Parse(logcntrlr.Save(logITEM));
                            }
                        }
                        else
                        {
                            message = "0";
                        }
                    }
                    else
                    {
                        message = "0";
                    }

                    restoremodel.logId  = logId;
                    restoremodel.result = message;
                    //restoremodel.fileName = filename;

                    return(TokenManager.GenerateToken(restoremodel));
                }
                catch (Exception ex)
                {
                    restoremodel.logId  = logId;
                    restoremodel.result = ex.ToString();
                    //  restoremodel.fileName = filename;
                    return(TokenManager.GenerateToken(restoremodel));
                }
            }
        }
Ejemplo n.º 27
0
        private void btn_SaveSettings_Click(object sender, EventArgs e)
        {
            var persistence      = new Persistence();
            var service          = new Service();
            var jsonRequestModel = persistence.ReadFormInformation();

            if (_isNewTask)
            {
                var changeSettingsList = new List <ChangeSettingsModel>();
                var backupDetailsList  = new List <BackupDetailsModel>();

                if (!string.IsNullOrEmpty(_oldTaskName) && !_oldTaskName.Equals(txt_BackupName.Text) && jsonRequestModel != null && jsonRequestModel.ChangeSettingsModelList != null)
                {
                    foreach (var changeSettingModel in jsonRequestModel.ChangeSettingsModelList)
                    {
                        if (changeSettingModel.BackupName.Equals(_oldTaskName))
                        {
                            changeSettingModel.BackupName        = txt_BackupName.Text;
                            changeSettingModel.TrimmedBackupName = string.Concat(txt_BackupName.Text.Where(c => !char.IsWhiteSpace(c)));

                            changeSettingsList.Add(changeSettingModel);
                        }
                    }
                    persistence.SaveChangeSettings(changeSettingsList, txt_BackupName.Text);

                    foreach (var backupDetail in jsonRequestModel.BackupDetailsModelList)
                    {
                        if (backupDetail.BackupName.Equals(_oldTaskName))
                        {
                            backupDetail.BackupName        = txt_BackupName.Text;
                            backupDetail.TrimmedBackupName = string.Concat(txt_BackupName.Text.Where(c => !char.IsWhiteSpace(c)));

                            backupDetailsList.Add(backupDetail);
                        }
                    }
                    persistence.SaveDetailsFormInfo(backupDetailsList, txt_BackupName.Text);
                }

                _oldTaskName = txt_BackupName.Text;

                txt_TaskNameError.Visible     = CheckTask(txt_BackupName.Text);
                txt_BackupFromError.Visible   = string.IsNullOrEmpty(txt_BackupFrom.Text) ? true : false;
                txt_BackupToError.Visible     = string.IsNullOrEmpty(txt_BackupTo.Text) ? true : false;
                txt_BackupNameError.Visible   = string.IsNullOrEmpty(txt_BackupName.Text) ? true : false;
                txt_WhenToBackupError.Visible = string.IsNullOrEmpty(txt_BackupTime.Text) ? true : false;

                if (!txt_TaskNameError.Visible &&
                    !txt_BackupFromError.Visible &&
                    !txt_BackupToError.Visible &&
                    !txt_BackupNameError.Visible &&
                    !txt_WhenToBackupError.Visible)
                {
                    var backupModel = new BackupModel();
                    backupModel.BackupName        = (txt_BackupName.Text);
                    backupModel.TrimmedBackupName = string.Concat(txt_BackupName.Text.Where(c => !char.IsWhiteSpace(c)));

                    SetBackupModelInfo(backupModel, persistence, service);
                }
            }
            else
            {
                //update settings
                if (jsonRequestModel != null)
                {
                    var backupModel = jsonRequestModel.BackupModelList != null
                                                ? jsonRequestModel.BackupModelList.FirstOrDefault(b => b.BackupName.Equals(txt_BackupName.Text))
                                                : null;

                    if (backupModel != null)
                    {
                        SetBackupModelInfo(backupModel, persistence, service);
                    }
                }
            }
        }
        public ActionResult Backup(BackupModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    if (model.Name.Contains("\\"))
                    {
                        ModelState.AddModelError("Name", "File name must not contain one of the following characters /\\:*?\"<>|");
                        return(PartialView(model));
                    }
                    // Đường dẫn tới file xml.
                    string path = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + "/App_Data/config.xml";
                    // Tạo một đối tượng TextReader mới
                    var    xtr          = System.Xml.Linq.XDocument.Load(path);
                    string backupFolder = string.Format(xtr.Element("system.config").Element("path-backup").Value.Trim());   //Vuongj
                    // tạo folder backup neu chua co
                    if (!System.IO.Directory.Exists(backupFolder))
                    {
                        System.IO.Directory.CreateDirectory(backupFolder);
                    }

                    string fileName = model.Name;
                    if (fileName.IndexOf(".bak") <= 0)
                    {
                        fileName += ".bak";
                    }

                    var filePath = backupFolder;
                    if (filePath.LastIndexOf("\\") == filePath.Length - 1)
                    {
                        filePath += fileName;
                    }
                    else
                    {
                        filePath += "\\" + fileName;
                    }

                    String conStr = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
                    SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(conStr);
                    string databaseName = builder.InitialCatalog;

                    string query  = string.Format(@"BACKUP DATABASE {0} TO DISK = '{1}' WITH INIT", databaseName, filePath);
                    int    result = DB.Entities.ExecuteStoreCommand(query);
                    if (result != 0)
                    {
                        //add to Data.xml
                        var backupObj = new Models.BackupModel();
                        backupObj.Name     = model.Name;
                        backupObj.FilePath = filePath;
                        backupObj.Date     = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        return(RedirectToAction("Index"));
                    }
                }
                catch (Exception ex)
                {
                    if (ex.Message.Contains("Cannot open backup device"))
                    {
                        // Đường dẫn tới file xml.
                        string path = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + "/App_Data/config.xml";
                        // Tạo một đối tượng TextReader mới
                        var    xtr          = System.Xml.Linq.XDocument.Load(path);
                        string backupFolder = string.Format(xtr.Element("system.config").Element("path-backup").Value.Trim());
                        ModelState.AddModelError("", "<p class='field-validation-error'><b>Backup database unsuccessfully.</b></p><p class='field-validation-error'>Folder backup \"" + backupFolder + "\" not found. <br />Please check again system config!</p>");
                        return(View(model));
                    }
                    ModelState.AddModelError("", "<p class='field-validation-error'><b>Backup database unsuccessfully.</b></p><p class='field-validation-error'>Please try again in a few minutes</p>");
                }
            }
            return(View(model));
        }
Ejemplo n.º 29
0
 public void Create(BackupModel model, string password)
 {
     _password = password;
     InitializeCompression(model);
 }
Ejemplo n.º 30
0
        public async Task <ActionResult <BackupModel> > GetAsync(int serverId)
        {
            BackupModel backup = await _backupQueries.GetLatestServerBackupAsync(serverId);

            return(Ok(backup));
        }