public async void LogActivity(string backupId, string message, string error, string status) { try { LanBackupsAPI api = getApi(); // submit activity status var log = new BackupLog() { ClientIP = DI.Container.GetInstance <Network>().GetLocalIPAddress(), Status = status, Description = message, LogError = error, DateTime = DateTime.UtcNow }; var result = await api.ApiLogsPostAsync(log); logger.Info($"Log sent to WebApi, response ID: {result}"); } catch (HttpRequestException hex) { if (hex.InnerException is WebException) { WebException wex = hex.InnerException as WebException; if (wex.Status == WebExceptionStatus.ConnectFailure) { //ignore this err } else { logger.Error($"ERR WebException HResult: {wex.HResult}"); logger.Error($"ERR WebException Status: {wex.Status}"); logger.Error($"ERR WebException Message: {wex.Message}"); } } } catch (Exception ex) { logger.Error($"WebApi ERROR: {ex}"); } }
public ActionResult DeleteConfirmed( Int32?BackupLogID ) { BackupLog BackupLog = new BackupLog(); BackupLog.BackupLogID = System.Convert.ToInt32(BackupLogID); BackupLog = BackupLogData.Select_Record(BackupLog); bool bSucess = false; bSucess = BackupLogData.Delete(BackupLog); if (bSucess == true) { return(RedirectToAction("Index")); } else { ModelState.AddModelError("", "Can Not Delete"); } return(null); }
public ActionResult Create([Bind(Include = "BackupDate" + "," + "FilePath" + "," + "Remarks" )] BackupLog BackupLog) { if (ModelState.IsValid) { bool bSucess = false; bSucess = BackupLogData.Add(BackupLog); if (bSucess == true) { return(RedirectToAction("Index")); } else { ModelState.AddModelError("", "Can Not Insert"); } } return(View(BackupLog)); }
// GET: /BackupLog/Delete/<id> public ActionResult Delete( Int32?BackupLogID ) { if ( BackupLogID == null ) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } BackupLog BackupLog = new BackupLog(); BackupLog.BackupLogID = System.Convert.ToInt32(BackupLogID); BackupLog = BackupLogData.Select_Record(BackupLog); if (BackupLog == null) { return(HttpNotFound()); } return(View(BackupLog)); }
public ActionResult Edit(BackupLog BackupLog) { BackupLog oBackupLog = new BackupLog(); oBackupLog.BackupLogID = System.Convert.ToInt32(BackupLog.BackupLogID); oBackupLog = BackupLogData.Select_Record(BackupLog); if (ModelState.IsValid) { bool bSucess = false; bSucess = BackupLogData.Update(oBackupLog, BackupLog); if (bSucess == true) { return(RedirectToAction("Index")); } else { ModelState.AddModelError("", "Can Not Update"); } } return(View(BackupLog)); }
public static BackupLog Select_Record(BackupLog BackupLogPara) { BackupLog BackupLog = new BackupLog(); SqlConnection connection = PMMSData.GetConnection(); string selectProcedure = "[BackupLogSelect]"; SqlCommand selectCommand = new SqlCommand(selectProcedure, connection); selectCommand.CommandType = CommandType.StoredProcedure; selectCommand.Parameters.AddWithValue("@BackupLogID", BackupLogPara.BackupLogID); try { connection.Open(); SqlDataReader reader = selectCommand.ExecuteReader(CommandBehavior.SingleRow); if (reader.Read()) { BackupLog.BackupLogID = System.Convert.ToInt32(reader["BackupLogID"]); BackupLog.BackupDate = System.Convert.ToDateTime(reader["BackupDate"]); BackupLog.FilePath = System.Convert.ToString(reader["FilePath"]); BackupLog.Remarks = reader["Remarks"] is DBNull ? null : reader["Remarks"].ToString(); } else { BackupLog = null; } reader.Close(); } catch (SqlException) { return(BackupLog); } finally { connection.Close(); } return(BackupLog); }
/// <summary> /// Create an entry in the logs /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='log'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task <object> ApiLogsPostAsync(this ILanBackupsAPI operations, BackupLog log = default(BackupLog), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ApiLogsPostWithHttpMessagesAsync(log, null, cancellationToken).ConfigureAwait(false)) { return(_result.Body); } }
/// <summary> /// Create an entry in the logs /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='log'> /// </param> public static object ApiLogsPost(this ILanBackupsAPI operations, BackupLog log = default(BackupLog)) { return(Task.Factory.StartNew(s => ((ILanBackupsAPI)s).ApiLogsPostAsync(log), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult()); }
public void SendBackupDirectory(string directory, string remoteDirectory, DbOperations db, int devicePlanId, IPlatform platform, BackupLog bc) { string[] deviceInfo = Common.SecurityKey().Split('|'); BackupJobModel model = new BackupJobModel(); var result = Common.ApiAndSecretKey(); model.apiAccessKey = result.Key; model.apiSecretKey = result.Value; model.cpuId = deviceInfo[0]; model.diskVolume = deviceInfo[1]; model.macAddress = deviceInfo[2]; bc.apiAccessKey = model.apiAccessKey; bc.apiSecretKey = model.apiSecretKey; bc.cpuId = model.cpuId; bc.diskVolume = model.diskVolume; bc.macAddress = model.macAddress; List <CloudFile> cfList = db.GetFileList(devicePlanId, directory); DirectoryInfo d = new DirectoryInfo(directory); //Assuming Test is your Folder FileInfo[] Files = d.GetFiles(); //Getting Text files string str = ""; foreach (FileInfo file in Files) { CloudFile currentFile = cfList.Where(f => f.FullName == file.FullName && f.ResultStatus == Enum.ResultStatus.Success).FirstOrDefault(); if (currentFile != null) { if (file.LastWriteTime > currentFile.ProccessDate.Value && !String.IsNullOrEmpty(currentFile.CloudId)) { if (platform.CheckAccessTokenExpire()) { TokenResponse resp = ResetGoogleToken(devicePlanId); platform.UpdateAccessToken(resp.AccessToken, DateTime.Now.AddSeconds(resp.ExpiresInSeconds.Value)); } string fileId = platform.UpdateFile(file.Name, file.FullName, file.GetType().ToString(), remoteDirectory, currentFile.CloudId);// UpdateFile(file.Name, file.FullName, file.GetType().ToString(), accessToken, s, remoteDirectory, currentFile.CloudId); if (!String.IsNullOrEmpty(fileId) && !fileId.StartsWith("error-")) { currentFile.CloudId = fileId; bc.ProccessCount++; bc.UpdatedCount++; bc.TotalSize += GetFileSize(file); } if (!String.IsNullOrEmpty(fileId) && fileId.StartsWith("error-")) { currentFile.ErrorMessage = fileId.Replace("error-", ""); bc.FailedCount++; bc.ProccessCount++; } currentFile.Length = GetFileSize(file); currentFile.ProccessDate = DateTime.Now; if (!String.IsNullOrEmpty(fileId) && !fileId.StartsWith("error-")) { currentFile.ResultStatus = Enum.ResultStatus.Success; } else { currentFile.ResultStatus = Enum.ResultStatus.Error; } db.UpdateData(currentFile); } } else { if (platform.CheckAccessTokenExpire()) { TokenResponse resp = ResetGoogleToken(devicePlanId); platform.UpdateAccessToken(resp.AccessToken, DateTime.Now.AddSeconds(resp.ExpiresInSeconds.Value)); bc.ProccessCount++; } string fileId = platform.UploadFile(file.Name, file.FullName, file.GetType().ToString(), remoteDirectory); CloudFile ff = new CloudFile(); if (!String.IsNullOrEmpty(fileId) && !fileId.StartsWith("error-")) { ff.CloudId = fileId; } ff.DevicePlanId = devicePlanId; if (!String.IsNullOrEmpty(fileId) && fileId.StartsWith("error-")) { ff.ErrorMessage = fileId.Replace("error-", ""); } ff.Length = GetFileSize(file); ff.FullName = file.FullName; ff.ProccessDate = DateTime.Now; if (!String.IsNullOrEmpty(fileId) && !fileId.StartsWith("error-")) { ff.ResultStatus = Enum.ResultStatus.Success; bc.ProccessCount++; bc.CreateFileCount++; bc.TotalSize += GetFileSize(file); } else { ff.ResultStatus = Enum.ResultStatus.Error; bc.FailedCount++; bc.ProccessCount++; } ff.SubDirectory = file.DirectoryName; ff.Type = Enum.FileType.File; db.InsertData(ff); } } List <string> fileFullPaths = Files.Select(f => f.FullName).ToList(); foreach (var deleteFile in cfList.Where(f => !fileFullPaths.Contains(f.FullName) && f.Type == Enum.FileType.File && f.ResultStatus == Enum.ResultStatus.Success)) { if (!String.IsNullOrEmpty(deleteFile.CloudId)) { if (platform.CheckAccessTokenExpire()) { bc.ProccessCount++; TokenResponse resp = ResetGoogleToken(devicePlanId); platform.UpdateAccessToken(resp.AccessToken, DateTime.Now.AddSeconds(resp.ExpiresInSeconds.Value)); } platform.DeleteFile(deleteFile.CloudId); bc.ProccessCount++; bc.DeletedCount++; deleteFile.ProccessDate = DateTime.Now; db.DeleteData(deleteFile); } } foreach (var item in Directory.GetDirectories(directory)) { CloudFile currentFile = cfList.Where(f => f.SubDirectory + @"\" + f.FullName == item && f.ResultStatus == Enum.ResultStatus.Success).FirstOrDefault(); if (currentFile != null && currentFile.SubDirectory + @"\" + currentFile.FullName == item) { SendBackupDirectory(item, currentFile.CloudId, db, devicePlanId, platform, bc); } else { if (platform.CheckAccessTokenExpire()) { TokenResponse resp = ResetGoogleToken(devicePlanId); platform.UpdateAccessToken(resp.AccessToken, DateTime.Now.AddSeconds(resp.ExpiresInSeconds.Value)); bc.ProccessCount++; } DirectoryInfo df = new DirectoryInfo(item); string directoryId = platform.CreateDirectory(df.Name, remoteDirectory); CloudFile ff = new CloudFile(); if (!String.IsNullOrEmpty(directoryId) && !directoryId.StartsWith("error-")) { ff.CloudId = directoryId; } ff.DevicePlanId = devicePlanId; if (!String.IsNullOrEmpty(directoryId) && directoryId.StartsWith("error-")) { ff.ErrorMessage = directoryId.Replace("error-", ""); } ff.FullName = df.Name; ff.ProccessDate = DateTime.Now; if (!String.IsNullOrEmpty(directoryId) && !directoryId.StartsWith("error-")) { ff.ResultStatus = Enum.ResultStatus.Success; bc.CreateDirectoryCount++; bc.ProccessCount++; } else { ff.ResultStatus = Enum.ResultStatus.Error; bc.FailedCount++; bc.ProccessCount++; } ff.SubDirectory = directory; ff.Type = Enum.FileType.Directory; db.InsertData(ff); SendBackupDirectory(item, directoryId, db, devicePlanId, platform, bc); } } }
public void SendFile(string model) { BackupLog bc = new BackupLog(); string localDirectory = ""; string remoteDirectory = ""; string devicePlanId = ""; dynamic platformDetail = JObject.Parse(model); localDirectory = platformDetail.localDirectory; remoteDirectory = platformDetail.remoteDirectory; devicePlanId = platformDetail.devicePlanId; bc.DevicePlanId = Convert.ToInt32(devicePlanId); bc.CreateDirectoryCount = 0; bc.CreateFileCount = 0; bc.FailedCount = 0; bc.ProccessCount = 0; bc.TotalSize = 0; bc.DeletedCount = 0; bc.UpdatedCount = 0; DbOperations db = new DbOperations(); IPlatform platf = null; if (platformDetail.planType.ToString() == "1") { DriveService s = new Google.Apis.Drive.v3.DriveService(); var services = new DriveService(new BaseClientService.Initializer() { ApiKey = platformDetail.googleApiCode, // from https://console.developers.google.com (Public API access) ApplicationName = "ECloud Backup", }); platf = new PlatformGoogle(s, platformDetail.googleAccessToken.ToString(), platformDetail.googleApiCode.ToString(), Common.ConvertDatabaseDateTime(platformDetail.googleTokenExpired.ToString())); } else if (platformDetail.planType.ToString() == "2") { platf = new AmazonS3(platformDetail.apiAccessKey.ToString(), platformDetail.apiSecretKey.ToString(), platformDetail.region.ToString()); } DateTime dtStartBackup = DateTime.Now; SendBackupDirectory(localDirectory, remoteDirectory, db, Convert.ToInt32(devicePlanId), platf, bc); var list = db.GetErrorFileList(Convert.ToInt32(devicePlanId), dtStartBackup); List <string> errorList = new List <string>(); foreach (var k in list) { errorList.Add(k.FullName + " - " + k.ErrorMessage); } LogDeviceModel mdl = new LogDeviceModel { apiAccessKey = bc.apiAccessKey, apiSecretKey = bc.apiSecretKey, cpuId = bc.cpuId, deviceId = bc.deviceId, devicePlanId = Convert.ToInt32(devicePlanId), diskVolume = bc.diskVolume, errorList = errorList, macAddress = bc.macAddress }; IRestRequest request = new RestRequest("api/device/deviceplanid/{deviceplanid}/finish", Method.POST); request.RequestFormat = RestSharp.DataFormat.Json; request.AddParameter("deviceplanid", devicePlanId, ParameterType.UrlSegment); request.AddBody(bc); TaskCompletionSource <IRestResponse> taskCompletion = new TaskCompletionSource <IRestResponse>(); RestRequestAsyncHandle handle = client.ExecuteAsync(request, r => { taskCompletion.SetResult(r); }); IRestResponse response = taskCompletion.Task.Result; IRestRequest request1 = new RestRequest("api/device/log", Method.POST); request1.RequestFormat = RestSharp.DataFormat.Json; request1.AddBody(mdl); TaskCompletionSource <IRestResponse> taskCompletion1 = new TaskCompletionSource <IRestResponse>(); RestRequestAsyncHandle handle1 = client.ExecuteAsync(request1, r => { taskCompletion1.SetResult(r); }); IRestResponse response1 = taskCompletion1.Task.Result; }