public static async Task <ReturnedSaveFuncInfo> BackUpLogAsync(Guid guid, EnBackUpType type, EnBackUpStatus status, string path, string desc) { var res = new ReturnedSaveFuncInfo(); try { var fi = new FileInfo(path); var size = (long)0; try { if (File.Exists(path)) { size = fi.Length; size /= 1000000; } } catch { } var log = await BackUpLogBussines.GetAsync(guid) ?? new BackUpLogBussines() { Guid = guid, Modified = DateTime.Now, Status = true, InsertedDate = DateTime.Now }; log.BackUpStatus = status; log.Path = path; log.Type = type; log.StatusDesc = desc; log.Size = (short)size; await log.SaveAsync(); } catch (Exception ex) { WebErrorLog.ErrorInstence.StartErrorLog(ex); res.AddReturnedValue(ex); } return(res); }
public static async Task <ReturnedSaveFuncInfoWithValue <string> > BackupDbAsync(string connectionString, ENSource source, EnBackUpType type, string path = "") { var line = 0; var res = new ReturnedSaveFuncInfoWithValue <string>(); bool IsAutomatic = string.IsNullOrEmpty(path); string DatabaseName = ""; var guid = Guid.NewGuid(); try { OnCreateBackup?.Invoke(null, new CreateBackupArgs() { Message = "", State = CreateBackupState.Start }); if (IsAutomatic) { path = CreateFileName(connectionString); } if (!string.IsNullOrEmpty(path) && Directory.Exists(path)) { //در نرم افزار حسابداری آدرس پوشه پشتیبان گیری اتوماتیک داده شده است //باید فایل پشتیبان در این پوشه ایجاد گردد path = CreateFileName(connectionString, path); IsAutomatic = true; } await BackUpLogAsync(guid, type, EnBackUpStatus.Pending, path, "آغاز فرآیند تهیه فایل پشتیبان"); //تهیه اولین نسخه بکاپ توسط سرویس اس کیو ال var CreateSqlBackuResult = await CreateSqlServerBackupFileAsync(path, connectionString, guid, type); DatabaseName = CreateSqlBackuResult.value; res.AddReturnedValue(CreateSqlBackuResult); var PathForZipDirectory = await Zip.Move2Temp(path, guid, type); res.AddReturnedValue(PathForZipDirectory); try { //please dont remove this try //اگر به خطا خورد باید تابع ادامه پیدا کند و پشتیبان با پسوند .بک تهیه شود res.AddReturnedValue( await CompressFile.CompressFileInstance.CompressFileAsync(PathForZipDirectory.value, path, guid, type)); } catch (Exception ex) { WebErrorLog.ErrorInstence.StartErrorLog(ex); res.AddReturnedValue(ex); } res.value = path.ToLower().Replace(".npz2", ".np").Replace(".npz", ".np").Replace(".np", ".npz2"); //بنا به هر دلیلی امکان فشرده کردن فایل وجود نداشته است //باید همان بکاپ فشرده نشده به آدرس مقصد درخواستی مشتری متقل گردد if (res.HasError) { var file = Directory.GetFiles(PathForZipDirectory.value).FirstOrDefault(); File.Move(file, path.ToLower().Replace(".npz2", ".np").Replace(".npz", ".np")); } OnCreateBackup?.Invoke(null, new CreateBackupArgs() { Message = "", State = CreateBackupState.End }); await BackUpLogAsync(guid, type, EnBackUpStatus.Success, path.ToLower(), "عملیات پشتیبان گیری با موفقیت انجام شد"); } catch (OperationCanceledException ex) { res.AddReturnedValue(ex); } catch (Exception ex) { await BackUpLogAsync(guid, type, EnBackUpStatus.Error, path.ToLower().Replace(".npz2", ".np").Replace(".npz", ".np"), ex.Message); WebErrorLog.ErrorInstence.StartErrorLog(ex, $"Error in Line {line}"); res.AddReturnedValue(ex); } finally { Task.Run(DeleteTempsAsync); } return(res); }
private static async Task <ReturnedSaveFuncInfoWithValue <string> > CreateSqlServerBackupFileAsync(string path, string connectionString, Guid guid, EnBackUpType type) { var ret = new ReturnedSaveFuncInfoWithValue <string>(); string commandText = ""; try { var inf = new FileInfo(path); if (string.IsNullOrEmpty(path) || string.IsNullOrEmpty(inf.Name) || !Directory.Exists(inf.DirectoryName)) { var msg = $"آدرس {path} موجود یا معتبر نیست."; await BackUpLogAsync(guid, type, EnBackUpStatus.Error, path, msg); ret.AddReturnedValue(ReturnedState.Error, msg); return(ret); } var cn = new SqlConnection(connectionString); ret.value = new SqlConnectionStringBuilder(connectionString).InitialCatalog; var cmd = new SqlCommand($"Backup database [{ret.value }] to disk='{path}'", cn) { CommandType = CommandType.Text }; commandText = cmd.CommandText; //تنها جای مجاز برای افزایش تایم اوت هست cmd.CommandTimeout = 5 * 60 * 1000;//5 minutes await cn.OpenAsync(); await cmd.ExecuteNonQueryAsync(); cn.Close(); await BackUpLogAsync(guid, type, EnBackUpStatus.Success, path, "پشتیبان اولیه با پسوند .bak تهیه شد"); commandText = ""; } catch (SqlException ex) { var msg = $"خطا در تهیه نسخه پشتیبان اطلاعات \r\nحساب کاربری SQL دسترسی به مسیر نصب برنامه ندارد\r\n{ex.Message}//{ex?.InnerException?.Message ?? ""}"; await BackUpLogAsync(guid, type, EnBackUpStatus.Error, path, msg); WebErrorLog.ErrorInstence.StartErrorLog(ex); ret.AddReturnedValue(ReturnedState.Error, msg); } catch (Exception ex) { await BackUpLogAsync(guid, type, EnBackUpStatus.Error, path, ex.Message); WebErrorLog.ErrorInstence.StartErrorLog(ex); ret.AddReturnedValue(ex); } return(ret); }
public static async Task <ReturnedSaveFuncInfo> BackUpStartAsync(IWin32Window owner, string connectionString, ENSource source, EnBackUpType type, string path = "") { var ret = new ReturnedSaveFuncInfo(); try { if (path == "") { var dlg = new SaveFileDialog { Title = @"پشتیبان گیری اطلاعات آراد" }; var file = Path.GetFileName(System.Reflection.Assembly.GetEntryAssembly()?.Location) ?.Replace(".exe", "__"); var d = Calendar.MiladiToShamsi(DateTime.Now).Replace("/", "_"); d += "__" + DateTime.Now.Hour + " - " + DateTime.Now.Minute; file += d; file = file.Replace(" ", ""); dlg.FileName = file; dlg.Filter = "*.NPZ2|*.NPZ2"; if (dlg.ShowDialog(owner) != DialogResult.OK) { ret.AddReturnedValue(ReturnedState.Warning, "لغو توسط کاربر. عدم انتخاب آدرس ذخیره سازی."); return(ret); } path = dlg.FileName; } ret.AddReturnedValue(await DatabaseAction.BackupDbAsync(connectionString, source, type, path)); } catch (ThreadAbortException ex) { ret.AddReturnedValue(ex); } catch (OperationCanceledException ex) { ret.AddReturnedValue(ex); } catch (Exception ex) { WebErrorLog.ErrorInstence.StartErrorLog(ex); Finish_Event = true; ret.AddReturnedValue(ex); } return(ret); }
/// <summary> /// ورودی آدرس فایل خروجی آدرس پوشه ای که باید فشرده سازی شود /// </summary> /// <param name="filePath"></param> /// <returns></returns> public static async Task <ReturnedSaveFuncInfoWithValue <string> > Move2Temp(string filePath, Guid guid, EnBackUpType type) { var ret = new ReturnedSaveFuncInfoWithValue <string>(); try { string tempDIR = TempDirName(); FileInfo tempInfor = new FileInfo(filePath); if (!File.Exists(filePath)) { var msg = $"path not exists : {filePath}"; await DatabaseAction.BackUpLogAsync(guid, type, EnBackUpStatus.Error, filePath, msg); ret.AddReturnedValue(ReturnedState.Error, msg); return(ret); } var retFilePath = Path.Combine(tempDIR, tempInfor.Name); File.Move(filePath, retFilePath); ret.value = tempDIR; await DatabaseAction.BackUpLogAsync(guid, type, EnBackUpStatus.Success, filePath, "انتقال فایل به پوشه Temp انجام شد"); } catch (Exception ex) { await DatabaseAction.BackUpLogAsync(guid, type, EnBackUpStatus.Error, filePath, ex.Message); WebErrorLog.ErrorInstence.StartErrorLog(ex); ret.AddReturnedValue(ex); } return(ret); }
private async Task BackUpAsync(string path, bool isAuto, EnBackUpType type) { try { if (!isAuto) { if (string.IsNullOrEmpty(clsBackUp.BackUpOpen) || !clsBackUp.BackUpOpen.ParseToBoolean()) { return; } path = Path.Combine(path, "AradBackUp"); } if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } var file = Path.GetFileName(Assembly.GetEntryAssembly()?.Location) ?.Replace(".exe", "__"); var d = Calendar.MiladiToShamsi(DateTime.Now).Replace("/", "_"); d += "__" + DateTime.Now.Hour + " - " + DateTime.Now.Minute; file += d; file = file.Replace(" ", ""); var newPath = Path.Combine(path, file + ".NPZ2"); await DataBaseUtilities.DataBase.BackUpStartAsync(this, AppSettings.DefaultConnectionString, ENSource.Building, type, newPath); if (isAuto) { if (!string.IsNullOrEmpty(clsBackUp.BackUpSms) && clsBackUp.BackUpSms.ParseToBoolean() && VersionAccess.Sms) { if (string.IsNullOrEmpty(Settings.Classes.Payamak.DefaultPanelGuid)) { return; } var text = $"مدیریت محترم مجموعه {clsEconomyUnit.EconomyName ?? ""} \r\n" + $"{clsEconomyUnit.ManagerName ?? ""} عزیز \r\n" + $"در تاریخ {Calendar.MiladiToShamsi(DateTime.Now)} \r\n" + $"و در ساعت {DateTime.Now.ToShortTimeString()} \r\n" + $"پشتیبان گیری خودکار از داده ها انجام شد \r\n" + $"باتشکر \r\n" + $"گروه مهندسی آراد"; var panel = SmsPanelsBussines.Get(Guid.Parse(Settings.Classes.Payamak.DefaultPanelGuid)); if (panel == null) { return; } var sApi = new Sms.Api(panel.API.Trim()); var result = sApi.Send(panel.Sender, clsEconomyUnit.ManagerMobile ?? "", text); var smsLog = new SmsLogBussines() { Guid = Guid.NewGuid(), UserGuid = UserBussines.CurrentUser?.Guid ?? Guid.Empty, Cost = result.Cost, Message = result.Message, MessageId = result.Messageid, Reciver = result.Receptor, Sender = result.Sender, StatusText = result.StatusText }; await smsLog.SaveAsync(); } } } catch (Exception ex) { WebErrorLog.ErrorInstence.StartErrorLog(ex); } }
public async Task <ReturnedSaveFuncInfo> CompressFileAsync(string pathForZipDirectory, string zipFilePath, Guid guid, EnBackUpType type) { var ret = new ReturnedSaveFuncInfo(); int line = 0; try { line = 1; zipFilePath = zipFilePath.ToLower(); line = 2; var inf = new FileInfo(zipFilePath); line = 3; zipFilePath = inf.FullName.Replace(inf.Extension, ".npz2"); using (var archive = ArchiveFactory.Create(ArchiveType.GZip)) { line = 48; archive.AddAllFromDirectory(pathForZipDirectory); line = 51; archive.SaveTo(zipFilePath, CompressionType.GZip); } line = 52; line = 53; Directory.Delete(pathForZipDirectory, true); await DatabaseAction.BackUpLogAsync(guid, type, EnBackUpStatus.Success, zipFilePath, "فایل فشره شده ایجاد شد"); } catch (OperationCanceledException ex) { ret.AddReturnedValue(ex); } catch (Exception ex) { await DatabaseAction.BackUpLogAsync(guid, type, EnBackUpStatus.Error, zipFilePath, ex.Message); WebErrorLog.ErrorInstence.StartErrorLog(ex, $"Line:{line}"); ret.AddReturnedValue(ex); } return(ret); }