public void Register(ProcessProgress progress) { progress.MinStep = 0; progress.MaxStep = 100; progress.CurrentStep = 0; progress.StatusText = string.Empty; }
private void StreamCopy(Stream dest, Stream source) { int byteRead; long onePercentage; long bytesReadFromLastProgressEvent; byte[] buffer = new byte[4 * 1024 + 1]; ProcessProgress <long> progress = new ProcessProgress <long>("FTP " + m_transferDirection + " File Transfer", "Transfering file \"" + m_remoteFile + "\"...", m_totalBytes, 0); onePercentage = m_totalBytes / 100; bytesReadFromLastProgressEvent = 0; byteRead = source.Read(buffer, 0, 4 * 1024); while (byteRead != 0) { m_totalBytesTransfered += byteRead; bytesReadFromLastProgressEvent += byteRead; if (bytesReadFromLastProgressEvent > onePercentage) { m_transferedPercentage = (int)(((float)m_totalBytesTransfered) / ((float)m_totalBytes) * 100); progress.Complete = m_totalBytesTransfered; m_session.Host.OnFileTransferProgress(progress, m_transferDirection); bytesReadFromLastProgressEvent = 0; } dest.Write(buffer, 0, byteRead); byteRead = source.Read(buffer, 0, 4 * 1024); } }
internal void OnFileTransferProgress(ProcessProgress <long> fileTransferProgress, TransferDirection transferDirection) { if ((object)FileTransferProgress != null) { FileTransferProgress(this, new EventArgs <ProcessProgress <long>, TransferDirection>(fileTransferProgress, transferDirection)); } }
protected void DoOverridePostData(object sender, MCS.Web.WebControls.PostProgressDoPostedDataEventArgs e) { // 先保存当前数据 try { ProcessProgress pg = ProcessProgress.Current; pg.CurrentStep = pg.MaxStep = 1; pg.MinStep = 0; var aclMembers = JSONSerializerExecute.Deserialize <SCAclMemberCollection>(e.Steps[0]); bool all = e.Steps[1].Equals("all"); bool inheritRight = e.Steps[2].Equals("inherit"); var obj = DbUtil.GetEffectiveObject(e.ClientExtraPostedData, null); InnerDoSave(aclMembers, obj, inheritRight); PC.Executors.SCObjectOperations.InstanceWithPermissions.ReplaceAclRecursively((ISCAclContainer)obj, all); pg.Output.WriteLine("完毕"); } catch (Exception ex) { ProcessProgress.Current.Output.WriteLine(ex.ToString()); ProcessProgress.Current.StatusText = "错误"; ProcessProgress.Current.Response(); } e.Result.CloseWindow = false; e.Result.ProcessLog = ProcessProgress.Current.GetDefaultOutput(); }
public void Register(ProcessProgress progress) { progress.MinStep = 0; progress.MaxStep = 100; progress.CurrentStep = 1; progress.StatusText = string.Empty; }
public Guid CreateProcess(Action <Action <TrainingJob>, CancellationToken> process) { var progress = new ProcessProgress <TrainingJob, float>(process, job => job.AvgError); _jobs.Add(progress.Id, progress); return(progress.Id); }
public void Response(ProcessProgress progress) { HttpResponse response = HttpContext.Current.Response; response.Write(string.Format("<script type=\"text/javascript\">top.document.getElementById(\"processInfo\").value=\"{0}\";\ntop.document.getElementById(\"processInfoChanged\").click();</script>", WebUtility.CheckScriptString(JSONSerializerExecute.Serialize(progress), false))); response.Flush(); }
public void Register(ProcessProgress progress) { JSONSerializerExecute.RegisterConverter(typeof(ProcessProgressConverter)); progress.MinStep = 0; progress.MaxStep = 100; progress.CurrentStep = 1; progress.StatusText = string.Empty; }
public void Response(ProcessProgress progress) { HttpResponse response = HttpContext.Current.Response; string script = SubmitButton.GetChangeParentProcessInfoScript(progress, true); response.Write(script); response.Flush(); }
public void Response(ProcessProgress progress) { HttpResponse response = HttpContext.Current.Response; string script = GetChangeProcessInfoScript(progress, "progressUpdate", true); response.Write(script); response.Flush(); }
/// <summary> /// 反序列化 /// </summary> /// <param name="dictionary"></param> /// <param name="type"></param> /// <param name="serializer"></param> /// <returns></returns> public override object Deserialize(IDictionary <string, object> dictionary, Type type, JavaScriptSerializer serializer) { ProcessProgress progress = (ProcessProgress)TypeCreator.CreateInstance(typeof(ProcessProgress)); progress.MinStep = dictionary.GetValue("MinStep", progress.MinStep); progress.MaxStep = dictionary.GetValue("MaxStep", progress.MaxStep); progress.CurrentStep = dictionary.GetValue("CurrentStep", progress.CurrentStep); progress.StatusText = dictionary.GetValue("StatusText", progress.StatusText); return(progress); }
private void Invoke(object stateInfo) { _progress.CurrentStep++; _progress.TimeSpentSeconds = (DateTime.Now - _timeStarted).Seconds; _callback(_progress); if (_progress.CurrentStep == _progress.TotalSteps) { this._progress = null; this._config = null; _timer.Dispose(); } }
/// <summary> /// 得到修改父窗口中状态变化的脚本 /// </summary> /// <param name="progress"></param> /// <param name="addScriptTag"></param> /// <returns></returns> public static string GetChangeParentProcessInfoScript(ProcessProgress progress, bool addScriptTag) { string script = "parent.document.getElementById('" + SubmitButton.ProgressInfoHiddenID + @"').value='" + JSONSerializerExecute.Serialize(progress) + "';\r\n parent.document.getElementById('" + SubmitButton.ProgressInfoChangedButtonID + "').click();"; if (addScriptTag) { script = "<script type=\"text/javascript\">" + script + "</script>"; } return(script); }
/// <summary> /// 序列化 /// </summary> /// <param name="obj"></param> /// <param name="serializer"></param> /// <returns></returns> public override IDictionary <string, object> Serialize(object obj, JavaScriptSerializer serializer) { Dictionary <string, object> dictionary = new Dictionary <string, object>(); ProcessProgress progress = (ProcessProgress)obj; dictionary.Add("MinStep", progress.MinStep); dictionary.Add("MaxStep", progress.MaxStep); dictionary.Add("CurrentStep", progress.CurrentStep); dictionary.Add("StatusText", progress.StatusText); return(dictionary); }
public void GenerateAllUserAndContainerSnapshotTest() { ProcessProgress.Clear(); ProcessProgress.Current.RegisterResponser(TestProgressResponser.Instance); TestRoleData roleData = SCObjectGenerator.PrepareTestRoleWithOrgAndGroup(); SCConditionCalculator calculator = new SCConditionCalculator(); calculator.GenerateAllUserAndContainerSnapshot(); Console.Error.WriteLine("Error: {0}", ProcessProgress.Current.GetDefaultError()); Console.WriteLine("Output: {0}", ProcessProgress.Current.GetDefaultOutput()); }
public void Response(ProcessProgress progress) { HttpResponse response = HttpContext.Current.Response; string script = string.Format("document.getElementById(\"statusText\").innerText=\"{0}\";document.getElementById(\"progressBar\").style[\"width\"] = \"{1}%\";", progress.StatusText, progress.CurrentStep * 100 / progress.MaxStep); script = string.Format("<script type=\"text/javascript\">{0}</script>", script); response.Write(script); response.Flush(); }
public void SetSubStatusAndLog(int currentStep, int maxStep, string message) { this.AppendLog(message); HttpResponse response = HttpContext.Current.Response; ProcessProgress progress = ProcessProgress.Current; progress.CurrentStep = currentStep; progress.MaxStep = maxStep; progress.StatusText = message; response.Write(string.Format("<script type=\"text/javascript\">top.document.getElementById(\"processInfo\").value=\"{0}\";\ntop.document.getElementById(\"subProcessInfoChanged\").click();</script>", WebUtility.CheckScriptString(JSONSerializerExecute.Serialize(progress), false))); response.Flush(); }
/// <summary> /// 得到修改父窗口中状态变化的脚本 /// </summary> /// <param name="progress"></param> /// <param name="addScriptTag"></param> /// <returns></returns> public static string GetChangeParentProcessInfoScript(ProcessProgress progress, bool addScriptTag) { string script = string.Format("parent.document.getElementById(\"{0}\").value=\"{1}\";\nparent.document.getElementById(\"{2}\").click();", SubmitButton.ProgressInfoHiddenID, WebUtility.CheckScriptString(JSONSerializerExecute.Serialize(progress), false), SubmitButton.ProgressInfoChangedButtonID); if (addScriptTag) { script = string.Format("<script type=\"text/javascript\">\n{0}\n</script>", script); } return(script); }
public void StartProcess(ProcessConfig config, Action <ProcessProgress> callback) { if (_progress != null) { throw new InvalidOperationException("The process is already started. Please, use another Service instance."); } _config = config; _callback = callback; _progress = new ProcessProgress() { ProcessId = Guid.NewGuid(), TotalSteps = Math.Abs(config.StepsCount), CurrentStep = 0, TimeSpentSeconds = 0 }; _progress.TotalSteps = config.StepsCount; _timer = new Timer(Invoke, config, 0, config.StepDelay * 1000); _timeStarted = DateTime.Now; }
protected override void UpdateProgress(ProcessProgress p) { base.UpdateProgress(p); if (!_enabled) { return; } if (canCancel) { if (EditorUtility.DisplayCancelableProgressBar(_label, string.Format("{0}/{1}", _progress.index, _progress.assetCount), _progress.progress)) { Cancel(); } } else { EditorUtility.DisplayProgressBar(_label, string.Format("{0}/{1}", _progress.index, _progress.assetCount), _progress.progress); } }
private static string GetChangeProcessInfoScript(ProcessProgress progress, string funcName, bool addScriptTag) { string json = JsonConvert.SerializeObject(new { minStep = progress.MinStep, maxStep = progress.MaxStep, currentStep = progress.CurrentStep, statusText = progress.StatusText }); json = ScriptHelper.CheckScriptString(json); string script = string.Format("{0}(\"{1}\")", funcName, json); if (addScriptTag) { script = string.Format("<script type=\"text/javascript\">\n parent.{0}\n</script>", script); } return(script); }
public void IsChildAllByIDBuiltInFunctionTest() { SchemaObjectAdapter.Instance.ClearAllData(); TestRoleData roleData = SCObjectGenerator.PrepareTestRoleWithOrgAndGroup(data => string.Format("IsChildAll(\"{0}\", \"{1}\")", "Guid", data.SidelineOrganization.ID)); SCConditionCalculator calculator = new SCConditionCalculator(); ProcessProgress.Clear(); ProcessProgress.Current.RegisterResponser(TestProgressResponser.Instance); calculator.GenerateUserAndContainerSnapshot(new List <ISCUserContainerObject>() { roleData.BuiltInFunctionRole }); SameContainerUserAndContainerSnapshotCollection snapshot = UserAndContainerSnapshotAdapter.Instance.LoadByContainerID(roleData.BuiltInFunctionRole.ID); Console.WriteLine(roleData.ToString()); Console.Error.WriteLine("Error: {0}", ProcessProgress.Current.GetDefaultError()); Console.WriteLine("Output: {0}", ProcessProgress.Current.GetDefaultOutput()); Assert.IsFalse(snapshot.ContainsKey(roleData.SidelineUserInOrg.ID)); }
public void DeleteObjectsRecursivelyTest() { // 调用SCObjectGenerator,准备测试数据,包括人员、组织群组、组织中包含子组织和人员 SCObjectGenerator.PreareTestOguObjectForDelete(); SCOrganization parent = (SCOrganization)SchemaObjectAdapter.Instance.Load("91841971-44CB-4895-8B31-D9EA7432A74A"); // cityCompany SchemaObjectCollection objectsToDelete = new SchemaObjectCollection() { SchemaObjectAdapter.Instance.Load("471F24D5-962E-46B9-849B-639D0AEB2B16") // beijingYuanlian }; ProcessProgress.Clear(); ProcessProgress.Current.RegisterResponser(TestProgressResponser.Instance); // 执行删除,过程中会输出状态信息 SCObjectOperations.Instance.DeleteObjectsRecursively(objectsToDelete, parent); // 输出 Console.Error.WriteLine("Error: {0}", ProcessProgress.Current.GetDefaultError()); Console.WriteLine("Output: {0}", ProcessProgress.Current.GetDefaultOutput()); // 验证结果 Assert.IsFalse(this.ObjectDeleted("2B67F7D0-9362-401F-977F-3E267E87298B")); // wangfaping Assert.IsFalse(this.ObjectDeleted("3729DAC3-80E0-476C-8C4A-264E0F67BBC2")); // liumh Assert.IsTrue(this.ObjectDeleted("066352AA-8349-4D21-B83F-C909BA5B8352")); // beijingYuanlianExecutives Assert.IsTrue(this.ObjectDeleted("2F28C437-BBF9-4969-9C07-639BD9716B1E")); // yuanyangAobei Assert.IsFalse(this.ObjectDeleted("16903BF9-74B5-4B58-9204-8BB20F341D88")); // beijingZhonglian Assert.IsTrue(this.ObjectDeleted("CA093A1E-B207-48DB-B3B2-B085A81DA36A")); // groupA Assert.IsTrue(this.ObjectDeleted("A465FFC8-A742-41F3-A1B6-0D40FC5EA3D5")); // groupB Assert.IsFalse(this.ObjectDeleted("D1C28431-DD5D-496E-865B-85C6D89ED3D6")); // zhaolin1 }
internal void OnFileTransferProgress(ProcessProgress<long> fileTransferProgress, TransferDirection transferDirection) { if (FileTransferProgress != null) FileTransferProgress(this, new EventArgs<ProcessProgress<long>,TransferDirection>(fileTransferProgress, transferDirection)); }
/// <summary> /// Raises the <see cref="ReplicationProgress"/> event. /// </summary> /// <param name="replicationProgress"><see cref="ProcessProgress{T}"/> to send to <see cref="ReplicationProgress"/> event.</param> protected virtual void OnReplicationProgress(ProcessProgress<int> replicationProgress) { if (ReplicationProgress != null) ReplicationProgress(this, new EventArgs<ProcessProgress<int>>(replicationProgress)); }
private void StreamCopy(Stream dest, Stream source) { int byteRead; long onePercentage; long bytesReadFromLastProgressEvent; byte[] buffer = new byte[4 * 1024 + 1]; ProcessProgress<long> progress = new ProcessProgress<long>("FTP " + m_transferDirection + " File Transfer", "Transferring file \"" + m_remoteFile + "\"...", m_totalBytes, 0); onePercentage = m_totalBytes / 100; bytesReadFromLastProgressEvent = 0; byteRead = source.Read(buffer, 0, 4 * 1024); while (byteRead != 0) { m_totalBytesTransfered += byteRead; bytesReadFromLastProgressEvent += byteRead; if (bytesReadFromLastProgressEvent > onePercentage) { m_transferedPercentage = (int)(((float)m_totalBytesTransfered) / ((float)m_totalBytes) * 100); progress.Complete = m_totalBytesTransfered; m_session.Host.OnFileTransferProgress(progress, m_transferDirection); bytesReadFromLastProgressEvent = 0; } dest.Write(buffer, 0, byteRead); byteRead = source.Read(buffer, 0, 4 * 1024); } }
/// <summary>Uncompress a stream onto given output stream.</summary> public static void Decompress(this Stream source, Stream destination, Action<ProcessProgress<long>> progressHandler) { ProcessProgress<long>.Handler progress = null; byte[] inBuffer; byte[] outBuffer; byte[] lengthBuffer = BitConverter.GetBytes((int)0); int read, size; long total = 0, length = -1; // Send initial progress event if (progressHandler != null) { try { if (source.CanSeek) length = source.Length; } catch { length = -1; } // Create a new progress handler to track compression progress progress = new ProcessProgress<long>.Handler(progressHandler, "Uncompress", length); progress.Complete = 0; } // Read compression version from stream byte[] versionBuffer = new byte[1]; if (source.Read(versionBuffer, 0, 1) > 0) { if (versionBuffer[0] != CompressionVersion) throw new InvalidOperationException("Invalid compression version encountered in compressed stream - decompression aborted."); // Read initial buffer read = source.Read(lengthBuffer, 0, lengthBuffer.Length); while (read > 0) { // Convert the byte array containing the buffer size into an integer size = BitConverter.ToInt32(lengthBuffer, 0); if (size > 0) { // Create and read the next buffer inBuffer = new byte[size]; read = source.Read(inBuffer, 0, size); if (read > 0) { // Uncompress buffer outBuffer = Decompress(inBuffer, BufferSize); destination.Write(outBuffer, 0, outBuffer.Length); } // Update decompression progress if (progressHandler != null) { total += (read + lengthBuffer.Length); progress.Complete = total; } } // Read the size of the next buffer from the stream read = source.Read(lengthBuffer, 0, lengthBuffer.Length); } } }
/// <summary>Compress a stream onto given output stream using specified compression strength.</summary> public static void Compress(this Stream source, Stream destination, CompressionStrength strength, Action<ProcessProgress<long>> progressHandler) { ProcessProgress<long>.Handler progress = null; byte[] inBuffer = new byte[BufferSize]; byte[] outBuffer; byte[] lengthBuffer; int read; long total = 0, length = -1; // Send initial progress event if (progressHandler != null) { try { if (source.CanSeek) length = source.Length; } catch { length = -1; } // Create a new progress handler to track compression progress progress = new ProcessProgress<long>.Handler(progressHandler, "Compress", length); progress.Complete = 0; } // Read initial buffer read = source.Read(inBuffer, 0, BufferSize); // Write compression version into stream byte[] version = new byte[1]; version[0] = CompressionVersion; destination.Write(version, 0, 1); while (read > 0) { // Compress buffer - note that we are only going to compress used part of buffer, // we don't want any left over garbage to end up in compressed stream... outBuffer = Compress(inBuffer, 0, read, strength); // The output stream is hopefully smaller than the input stream, so we prepend the final size of // each compressed buffer into the destination output stream so that we can safely uncompress // the stream in a "chunked" fashion later... lengthBuffer = BitConverter.GetBytes(outBuffer.Length); destination.Write(lengthBuffer, 0, lengthBuffer.Length); destination.Write(outBuffer, 0, outBuffer.Length); // Update compression progress if (progressHandler != null) { total += read; progress.Complete = total; } // Read next buffer read = source.Read(inBuffer, 0, BufferSize); } }
private void WriteToHistoricArchiveFile(ArchiveData[] items) { if (m_buildHistoricFileListThread.IsAlive) // Wait until the historic file list has been built. m_buildHistoricFileListThread.Join(); OnHistoricDataWriteStart(); Dictionary<int, List<ArchiveData>> sortedPointData = new Dictionary<int, List<ArchiveData>>(); // First we'll seperate all point data by ID. for (int i = 0; i < items.Length; i++) { if (!sortedPointData.ContainsKey(items[i].HistorianID)) { sortedPointData.Add(items[i].HistorianID, new List<ArchiveData>()); } sortedPointData[items[i].HistorianID].Add(items[i]); } ProcessProgress<int> historicWriteProgress = new ProcessProgress<int>("HistoricWrite"); historicWriteProgress.Total = items.Length; foreach (int pointID in sortedPointData.Keys) { // We'll sort the point data for the current point ID by time. sortedPointData[pointID].Sort(); ArchiveFile historicFile = null; ArchiveDataBlock historicFileBlock = null; try { for (int i = 0; i < sortedPointData[pointID].Count; i++) { if (historicFile == null) { // We'll try to find a historic file when the current point data belongs. Info historicFileInfo; m_writeSearchTimeTag = sortedPointData[pointID][i].Time; lock (m_historicArchiveFiles) { historicFileInfo = m_historicArchiveFiles.Find(FindHistoricArchiveFileForWrite); } if (historicFileInfo != null) { // Found a historic file where the data can be written. historicFile = new ArchiveFile(); historicFile.FileName = historicFileInfo.FileName; historicFile.StateFile = m_stateFile; historicFile.IntercomFile = m_intercomFile; historicFile.MetadataFile = m_metadataFile; historicFile.Open(); } } if (historicFile != null) { if (sortedPointData[pointID][i].Time.CompareTo(historicFile.Fat.FileStartTime) >= 0 && sortedPointData[pointID][i].Time.CompareTo(historicFile.Fat.FileEndTime) <= 0) { // The current point data belongs to the current historic archive file. if (historicFileBlock == null || historicFileBlock.SlotsAvailable == 0) { // Request a new or previously used data block for point data. historicFileBlock = historicFile.Fat.RequestDataBlock(pointID, sortedPointData[pointID][i].Time, -1); } historicFileBlock.Write(sortedPointData[pointID][i]); historicFile.Fat.DataPointsReceived++; historicFile.Fat.DataPointsArchived++; if (i == sortedPointData[pointID].Count() - 1) { // Last piece of data for the point, so we close the currently open file. historicFile.Save(); historicFile.Dispose(); historicFile = null; historicFileBlock = null; } historicWriteProgress.Complete++; } else { // The current point data doesn't belong to the current historic archive file, so we have // to write all the point data we have so far for the current historic archive file to it. i--; historicFile.Dispose(); historicFile = null; historicFileBlock = null; } } } // Notify of progress per point. historicWriteProgress.ProgressMessage = string.Format("Wrote historic data for point id {0} ({1} of {2}).", pointID, "{0}", "{1}"); OnHistoricDataWriteProgress(historicWriteProgress); } catch (Exception ex) { // Free-up used memory. if (historicFile != null) { try { historicFile.Dispose(); historicFile = null; } catch { } } // Notify of the exception. OnHistoricDataWriteException(ex); } } OnHistoricDataWriteComplete(); }
/// <summary>Decrypts input stream onto output stream for the given parameters.</summary> public static void Decrypt(this Stream source, Stream destination, byte[] key, byte[] IV, CipherStrength strength, Action<ProcessProgress<long>> progressHandler) { ProcessProgress<long>.Handler progress = null; byte[] inBuffer, outBuffer; byte[] lengthBuffer = BitConverter.GetBytes(0); long total = 0; long length = -1; int size, read; // Sends initial progress event. if (progressHandler != null) { try { if (source.CanSeek) length = source.Length; } catch { length = -1; } // Create a new progress handler to track decryption progress progress = new ProcessProgress<long>.Handler(progressHandler, "Decrypt", length); progress.Complete = 0; } // When the source stream was encrypted, it was known that the encrypted stream length did not have to be same as // the input stream length. We prepended the final size of the each encrypted buffer onto the destination // ouput stream (now the input stream to this function), so that we could safely decrypt the stream in a // "chunked" fashion, hence the following: // Reads the size of the next buffer from the stream. read = source.Read(lengthBuffer, 0, lengthBuffer.Length); while (read > 0) { // Converts the byte array containing the buffer size into an integer. size = BitConverter.ToInt32(lengthBuffer, 0); if (size > 0) { // Creates and reads the next buffer. inBuffer = new byte[size]; read = source.Read(inBuffer, 0, size); if (read > 0) { // Decrypts buffer. outBuffer = inBuffer.Decrypt(key, IV, strength); destination.Write(outBuffer, 0, outBuffer.Length); // Updates decryption progress. if (progressHandler != null) { total += (read + lengthBuffer.Length); progress.Complete = total; } } } // Reads the size of the next buffer from the stream. read = source.Read(lengthBuffer, 0, lengthBuffer.Length); } }
/// <summary>Encrypts input stream onto output stream for the given parameters.</summary> public static void Encrypt(this Stream source, Stream destination, byte[] key, byte[] IV, CipherStrength strength, Action<ProcessProgress<long>> progressHandler) { ProcessProgress<long>.Handler progress = null; byte[] inBuffer = new byte[BufferSize]; byte[] outBuffer, lengthBuffer; long total = 0; long length = -1; int read; // Sends initial progress event. if (progressHandler != null) { try { if (source.CanSeek) length = source.Length; } catch { length = -1; } // Create a new progress handler to track encryption progress progress = new ProcessProgress<long>.Handler(progressHandler, "Encrypt", length); progress.Complete = 0; } // Reads initial buffer. read = source.Read(inBuffer, 0, BufferSize); while (read > 0) { // Encrypts buffer. outBuffer = inBuffer.CopyBuffer(0, read).Encrypt(key, IV, strength); // The destination encryption stream length does not have to be same as the input stream length, so we // prepend the final size of each encrypted buffer onto the destination ouput stream so that we can // safely decrypt the stream in a "chunked" fashion later. lengthBuffer = BitConverter.GetBytes(outBuffer.Length); destination.Write(lengthBuffer, 0, lengthBuffer.Length); destination.Write(outBuffer, 0, outBuffer.Length); // Updates encryption progress. if (progressHandler != null) { total += read; progress.Complete = total; } // Reads next buffer. read = source.Read(inBuffer, 0, BufferSize); } }
private void OffloadHistoricFiles() { if (Directory.Exists(m_archiveOffloadLocation)) { // Wait until the historic file list has been built. if (m_buildHistoricFileListThread.IsAlive) m_buildHistoricFileListThread.Join(); try { OnOffloadStart(); // The offload path that is specified is a valid one so we'll gather a list of all historic // files in the directory where the current (active) archive file is located. List<Info> newHistoricFiles; lock (m_historicArchiveFiles) { newHistoricFiles = m_historicArchiveFiles.FindAll(info => IsNewHistoricArchiveFile(info, m_fileName)); } // Sorting the list will sort the historic files from oldest to newest. newHistoricFiles.Sort(); // We'll offload the specified number of oldest historic files to the offload location if the // number of historic files is more than the offload count or all of the historic files if the // offload count is smaller the available number of historic files. ProcessProgress<int> offloadProgress = new ProcessProgress<int>("FileOffload"); offloadProgress.Total = (newHistoricFiles.Count < m_archiveOffloadCount ? newHistoricFiles.Count : m_archiveOffloadCount); for (int i = 0; i < offloadProgress.Total; i++) { // Don't attempt to offload active file if (string.Compare(newHistoricFiles[i].FileName, m_fileName, StringComparison.OrdinalIgnoreCase) != 0) { string destinationFileName = FilePath.AddPathSuffix(m_archiveOffloadLocation) + FilePath.GetFileName(newHistoricFiles[i].FileName); try { DeleteFile(destinationFileName); MoveFile(newHistoricFiles[i].FileName, destinationFileName); } catch (Exception ex) { OnOffloadException(new InvalidOperationException(string.Format("Failed to offload historic file \"{0}\": {1}", FilePath.GetFileName(newHistoricFiles[i].FileName), ex.Message), ex)); } offloadProgress.Complete++; offloadProgress.ProgressMessage = FilePath.GetFileName(newHistoricFiles[i].FileName); OnOffloadProgress(offloadProgress); } } OnOffloadComplete(); } catch (ThreadAbortException) { throw; } catch (Exception ex) { OnOffloadException(ex); } } else if (string.Compare(m_archiveOffloadLocation.ToNonNullString().Trim(), "*DELETE*", StringComparison.OrdinalIgnoreCase) == 0) { // Handle case where user has requested historic files be deleted instead of offloaded // Wait until the historic file list has been built. if (m_buildHistoricFileListThread.IsAlive) m_buildHistoricFileListThread.Join(); try { OnOffloadStart(); // Get a local copy of all the historic archive files. List<Info> allHistoricFiles; lock (m_historicArchiveFiles) { allHistoricFiles = new List<Info>(m_historicArchiveFiles); } // Determine total number of files to remove int filesToDelete = Common.Min(m_archiveOffloadCount, allHistoricFiles.Count); ProcessProgress<int> offloadProgress = new ProcessProgress<int>("FileOffload"); offloadProgress.Total = filesToDelete; // Start deleting historic files from oldest to newest. allHistoricFiles.Sort(); for (int i = 0; i < filesToDelete; i++) { // Don't attempt to offload active file if (string.Compare(allHistoricFiles[i].FileName, m_fileName, StringComparison.OrdinalIgnoreCase) != 0) { try { DeleteFile(allHistoricFiles[i].FileName); } catch (Exception ex) { OnOffloadException(new InvalidOperationException(string.Format("Failed to remove historic file \"{0}\": {1}", FilePath.GetFileName(allHistoricFiles[i].FileName), ex.Message), ex)); } } offloadProgress.Complete++; offloadProgress.ProgressMessage = FilePath.GetFileName(allHistoricFiles[i].FileName); OnOffloadProgress(offloadProgress); } OnOffloadComplete(); } catch (ThreadAbortException) { throw; } catch (Exception ex) { OnOffloadException(ex); } } }
public void Response(ProcessProgress progress) { Console.WriteLine("Current Step: {0}, Text: {1}", progress.CurrentStep, progress.StatusText); }
protected virtual void UpdateProgress(ProcessProgress p) { _progress = p; }
/// <summary> /// Raises the <see cref="OutOfSequenceDataWriteProgress"/> event. /// </summary> /// <param name="historicWriteProgress"><see cref="ProcessProgress{T}"/> to send to <see cref="OutOfSequenceDataWriteProgress"/> event.</param> protected virtual void OnOutOfSequenceDataWriteProgress(ProcessProgress<int> historicWriteProgress) { if (OutOfSequenceDataWriteProgress != null) OutOfSequenceDataWriteProgress(this, new EventArgs<ProcessProgress<int>>(historicWriteProgress)); }
/// <summary> /// Raises the <see cref="OffloadProgress"/> event. /// </summary> /// <param name="offloadProgress"><see cref="ProcessProgress{T}"/> to send to <see cref="OffloadProgress"/> event.</param> protected virtual void OnOffloadProgress(ProcessProgress<int> offloadProgress) { if (OffloadProgress != null) OffloadProgress(this, new EventArgs<ProcessProgress<int>>(offloadProgress)); }
/// <summary> /// Raises the <see cref="HistoricDataWriteProgress"/> event. /// </summary> /// <param name="historicWriteProgress"><see cref="ProcessProgress{T}"/> to send to <see cref="HistoricDataWriteProgress"/> event.</param> protected virtual void OnHistoricDataWriteProgress(ProcessProgress<int> historicWriteProgress) { if (HistoricDataWriteProgress != null) HistoricDataWriteProgress(this, new EventArgs<ProcessProgress<int>>(historicWriteProgress)); }
public void Register(ProcessProgress progress) { }
private void OffloadHistoricFiles() { if (Directory.Exists(m_fileOffloadLocation)) { if (m_buildHistoricFileListThread.IsAlive) { // Wait until the historic file list has been built. m_buildHistoricFileListThread.Join(); } try { OnOffloadStart(); // The offload path that is specified is a valid one so we'll gather a list of all historic // files in the directory where the current (active) archive file is located. List<Info> newHistoricFiles = null; lock (m_historicArchiveFiles) { newHistoricFiles = m_historicArchiveFiles.FindAll(IsNewHistoricArchiveFile); } // Sorting the list will sort the historic files from oldest to newest. newHistoricFiles.Sort(); // We'll offload the specified number of oldest historic files to the offload location if the // number of historic files is more than the offload count or all of the historic files if the // offload count is smaller the available number of historic files. ProcessProgress<int> offloadProgress = new ProcessProgress<int>("FileOffload"); offloadProgress.Total = (newHistoricFiles.Count < m_fileOffloadCount ? newHistoricFiles.Count : m_fileOffloadCount); for (int i = 0; i < offloadProgress.Total; i++) { string destinationFileName = FilePath.AddPathSuffix(m_fileOffloadLocation) + FilePath.GetFileName(newHistoricFiles[i].FileName); if (File.Exists(destinationFileName)) { // Delete the destination file if it already exists. File.Delete(destinationFileName); } File.Move(newHistoricFiles[i].FileName, destinationFileName); offloadProgress.Complete++; offloadProgress.ProgressMessage = string.Format("Offloaded historic file {0} ({1} of {2}).", FilePath.GetFileName(newHistoricFiles[i].FileName), "{0}", "{1}"); OnOffloadProgress(offloadProgress); } OnOffloadComplete(); } catch (ThreadAbortException) { throw; // Bubble up the ThreadAbortException. } catch (Exception ex) { OnOffloadException(ex); } } }
/// <summary> /// 得到修改父窗口中状态变化的脚本 /// </summary> /// <param name="progress"></param> /// <param name="addScriptTag"></param> /// <returns></returns> public static string GetChangeParentProcessInfoScript(ProcessProgress progress, bool addScriptTag) { string script = string.Format("parent.document.getElementById(\"{0}\").value=\"{1}\";\nparent.document.getElementById(\"{2}\").click();", SubmitButton.ProgressInfoHiddenID, WebUtility.CheckScriptString(JSONSerializerExecute.Serialize(progress), false), SubmitButton.ProgressInfoChangedButtonID); if (addScriptTag) script = string.Format("<script type=\"text/javascript\">\n{0}\n</script>", script); return script; }
/// <summary> /// 得到修改父窗口中状态变化的脚本 /// </summary> /// <param name="progress"></param> /// <param name="addScriptTag"></param> /// <returns></returns> public static string GetChangeParentProcessInfoScript(ProcessProgress progress, bool addScriptTag) { string script = "parent.document.getElementById('" + SubmitButton.ProgressInfoHiddenID + @"').value='" + JSONSerializerExecute.Serialize(progress) + "';\r\n parent.document.getElementById('" + SubmitButton.ProgressInfoChangedButtonID + "').click();"; if (addScriptTag) script = "<script type=\"text/javascript\">" + script + "</script>"; return script; }