public void StartCustomScan(string dir) { _scanPauseEvent.Set(); _scanCancellationTokenSource = new CancellationTokenSource(); _scanTask = Task.Factory.StartNew(() => { if (_scanProgressReport != null) { ScanProgress npro = new ScanProgress(); npro.Percentage = 0; npro.TargetFilePath = null; npro.Description = "正在准备自定义扫描"; _scanProgressReport.Report(npro); } PercentageOffset = 0; PercentageRatio = 100; CustomLocalScan(dir, _scanCancellationTokenSource.Token, _scanPauseEvent, _scanProgressReport); }); _scanTask.ContinueWith(atask => { if (ScanComplete != null) { ScanComplete(this, EventArgs.Empty); } }, TaskScheduler.FromCurrentSynchronizationContext()); }
void AnalysisFile(string file, CancellationToken ct, ManualResetEvent pauseEvent, IProgress <ScanProgress> progress, int num, int tcount, bool onlyImage) { log.Info("Scan: " + file); Exception classifyException; PornDatabase.PornItemType itype = PornDatabase.PornItemType.Undefined; if (onlyImage || ActiveFileMonitor.IsFileExtWith(file, ActiveFileMonitor.ImageExts)) { if (PornClassifier.Instance.Classify(file, out classifyException) == PornClassifier.ImageType.P**n) { itype = PornDatabase.PornItemType.LocalImage; } } else if (ActiveFileMonitor.IsFileExtWith(file, ActiveFileMonitor.VideoExts)) { if (PornClassifier.Instance.ClassifyVideoFile(file, out classifyException)) { itype = PornDatabase.PornItemType.LocalVideo; } } if (progress != null) { ScanProgress npro = new ScanProgress(); npro.Percentage = PercentageOffset + PercentageRatio * num / tcount; npro.TargetFilePath = file; npro.Description = "正在扫描:" + npro.TargetFilePath; npro.ItemType = itype; progress.Report(npro); } pauseEvent.WaitOne(); if (ct.IsCancellationRequested) { ct.ThrowIfCancellationRequested(); } }
private void ProgressChanged(object sender, ScanProgress e) { var wrappedFileName = e.File.WrapIfLengthIsLongerThan(35, "..."); CurrentFileLabel.Content = $"{wrappedFileName} ({e.Index}/{e.TotalIndex})"; ScanTotalProgress.ProgressBar.Value = e.ProgressPercentage; TaskbarItemInfo.ProgressValue = (e.ProgressPercentage / 100); }
private void UpdateProjectName(ScanProgress value) { if (value.ProjectName == _notReadyText) { lblProjectName.Text = _notReadyText; } else { lblProjectName.Text = string.Format(_lblProjectNameFormat, value.ProjectName); } }
private void ProgressChanged(object sender, ScanProgress e) { try { lbl_ProgressTitle.Text = e.File; pB_GlobalProgress.Value = (int)e.ProgressPercentage; lbl_GlobalProgress.Text = $@"{e.Index}/{e.TotalIndex}"; } catch (Exception) { // } }
private void ScanArduino_DataReceived(object sender, SerialDataReceivedEventArgs e) { try { ArduinoMessage += ArduinoSerialPort.ReadExisting(); ArduinoReadText.Invoke(new MethodInvoker(delegate { ArduinoReadText.Text += ArduinoMessage; })); if (ArduinoMessage.Contains("\n")) { measurementData.Add(Convert.ToInt32(ArduinoMessage)); ArduinoMessage = ""; ScanProgress.Invoke(new MethodInvoker(delegate { ScanProgress.Value = 1 / scanLength; })); if (measurementData.Count < scanLength) { SDMC1SerialPort.Write("+1\r"); } else { SDMC1SerialPort.DataReceived -= ScanSDMC1_DataReceived; SDMC1SerialPort.DataReceived += SDMC1SerialPort_DataReceived; ArduinoSerialPort.DataReceived -= ScanArduino_DataReceived; ArduinoSerialPort.DataReceived += ArduinoSerialPort_DataReceived; SDMC1SerialPort.Write("R" + scanStartPosition + "\r"); HomeButton.Invoke(new MethodInvoker(delegate { HomeButton.Enabled = true; })); ScanButton.Invoke(new MethodInvoker(delegate { ScanButton.Enabled = true; })); } moves++; } } catch (Exception error) { MessageText.Invoke(new MethodInvoker(delegate { MessageText.Text = error.Message; })); ArduinoMessage = ""; } }
public void StartAllScan(bool incremental) { DateTime lastDateTime; if (incremental) { lastDateTime = Properties.Settings.Default.lastAllLocalScanDateTime; } else { lastDateTime = DateTime.MinValue; } _scanPauseEvent.Set(); _scanCancellationTokenSource = new CancellationTokenSource(); _scanTask = Task.Factory.StartNew(() => { if (_scanProgressReport != null) { ScanProgress npro = new ScanProgress(); npro.Percentage = 0; npro.TargetFilePath = null; npro.Description = "正在准备全盘扫描"; _scanProgressReport.Report(npro); } PercentageOffset = 0; PercentageRatio = 30; FastLocalScan(_scanCancellationTokenSource.Token, _scanPauseEvent, _scanProgressReport, lastDateTime); PercentageOffset = 30; PercentageRatio = 70; AllLocalFileScan(_scanCancellationTokenSource.Token, _scanPauseEvent, _scanProgressReport, lastDateTime); }); _scanTask.ContinueWith(atask => { //如果正常结束,则记录时间 if (_scanCancellationTokenSource != null && !_scanCancellationTokenSource.IsCancellationRequested) { //浏览器缓存和全盘文件都记录当前时间 Properties.Settings.Default.lastAllLocalScanDateTime = DateTime.Now; Properties.Settings.Default.Save(); } if (ScanComplete != null) { ScanComplete(this, EventArgs.Empty); } }, TaskScheduler.FromCurrentSynchronizationContext()); }
private async void btnScan_Click(object sender, EventArgs e) { if (scanner == null) { var section = cbbSection.SelectedItem as ImageSection; scanner = new MultithreadedScanner(); var settings = new ScanSettings( section != null ? section.Address : 0, section != null ? section.Size : file.Length, patternTable.CodeText.Pattern); var progress = new ScanProgress(settings); progress.MadeProgressPercent += (_o, _e) => this.Invoke((MethodInvoker) delegate { progressBar1.Value = progress.ProgressPercent; }); progress.PatternFound += (_o, _e) => this.Invoke((MethodInvoker) delegate { this.lblOccurences.Text = progress.Findings.ToString("N0"); }); var watch = new Stopwatch(); watch.Start(); await ClearResults(); btnScan.Text = "Cancel"; progressBar1.Visible = true; lastResults = await scanner.PerformScan(file.OpenRead(), settings, progress); watch.Stop(); lblOccurences.Text = lastResults.Length.ToString("N0"); lblTime.Text = watch.Elapsed.ToString(@"hh\:mm\:ss\.fff"); ltvOccurences.BeginUpdate(); ltvOccurences.VirtualListSize = lastResults.Length; ltvOccurences.EndUpdate(); btnScan.Text = "Scan"; progressBar1.Visible = false; scanner = null; } else { scanner.Cancel(); } }
private void UpdateProgress(object sender, ScanProgress e) { if (e.IsUpdateStatus) { ScanningStatus = $"Scanning... {e.CurrentDirectory}"; return; } if (stopwatch.IsRunning) { var timeElapsed = stopwatch.Elapsed; ScanningStatus = $"Running... {timeElapsed:c}"; } if (e.IsFile) { FlaggedFiles.Add(e.File); } else { FlaggedDirectories.Add(e.File); } }
public void AddImageMultiSourceTemplate(CompressionType compType, string wimFileName, AddFlags addFlags = AddFlags.None) { string destDir = TestHelper.GetTempDir(); try { bool[] _checked = new bool[5]; for (int i = 0; i < _checked.Length; i++) { _checked[i] = false; } CallbackStatus ProgressCallback(ProgressMsg msg, object info, object progctx) { switch (msg) { case ProgressMsg.ScanBegin: { ScanProgress m = (ScanProgress)info; Assert.IsNotNull(m); _checked[0] = true; } break; case ProgressMsg.ScanEnd: { ScanProgress m = (ScanProgress)info; Assert.IsNotNull(m); _checked[1] = true; } break; case ProgressMsg.WriteMetadataBegin: Assert.IsNull(info); _checked[2] = true; break; case ProgressMsg.WriteStreams: { WriteStreamsProgress m = (WriteStreamsProgress)info; Assert.IsNotNull(m); _checked[3] = true; } break; case ProgressMsg.WriteMetadataEnd: Assert.IsNull(info); _checked[4] = true; break; } return(CallbackStatus.Continue); } string srcDir1 = Path.Combine(TestSetup.SampleDir, "Src01"); string srcDir3 = Path.Combine(TestSetup.SampleDir, "Src03"); string wimFile = Path.Combine(destDir, wimFileName); using (Wim wim = Wim.CreateNewWim(compType)) { wim.RegisterCallback(ProgressCallback); CaptureSource[] srcs = new CaptureSource[] { new CaptureSource(srcDir1, @"\A"), new CaptureSource(srcDir3, @"\Z"), }; wim.AddImageMultiSource(srcs, "UnitTest", null, addFlags); wim.Write(wimFile, Wim.AllImages, WriteFlags.None, Wim.DefaultThreads); WimInfo wi = wim.GetWimInfo(); Assert.IsTrue(wi.ImageCount == 1); Assert.IsTrue(wim.DirExists(1, "A")); Assert.IsTrue(wim.DirExists(1, "Z")); } for (int i = 0; i < _checked.Length; i++) { Assert.IsTrue(_checked[i]); } } finally { if (Directory.Exists(destDir)) { Directory.Delete(destDir, true); } } }
private StatusScanResult UpdateScanStatus(ref bool bCancel, bool backgroundMode, IScanView view, BackgroundWorkerHelper bg, CxWebServiceClient client, ref bool isIISStoped) { // Get current scan status CxWSResponseScanStatus cxWSResponseScanStatus = null; StatusScanResult statusScan = null; bg.DoWorkFunc = delegate(object obj) { cxWSResponseScanStatus = client.ServiceClient.GetStatusOfSingleScan(_scan.LoginResult.SessionId, _scan.RunScanResult.ScanId); statusScan = new StatusScanResult(); statusScan.CurrentStage = cxWSResponseScanStatus.CurrentStage; statusScan.CurrentStagePercent = cxWSResponseScanStatus.CurrentStagePercent; statusScan.Details = cxWSResponseScanStatus.StepDetails; statusScan.IsSuccesfull = cxWSResponseScanStatus.IsSuccesfull; statusScan.QueuePosition = cxWSResponseScanStatus.QueuePosition; statusScan.RunId = cxWSResponseScanStatus.RunId; statusScan.RunStatus = cxWSResponseScanStatus.CurrentStatus; statusScan.StageMessage = cxWSResponseScanStatus.StageMessage; statusScan.StageName = cxWSResponseScanStatus.StageName; statusScan.StepMessage = cxWSResponseScanStatus.StepMessage; statusScan.TimeFinished = cxWSResponseScanStatus.TimeFinished != null?cxWSResponseScanStatus.TimeFinished.ToString() : null; statusScan.TimeStarted = cxWSResponseScanStatus.TimeScheduled != null?cxWSResponseScanStatus.TimeScheduled.ToString() : null; statusScan.TotalPercent = cxWSResponseScanStatus.TotalPercent; }; bCancel = !bg.DoWork(null); if (!BackgroundWorkerHelper.IsReloginInvoked) { isIISStoped = !_scan.LoginResult.AuthenticationData.SaveSastScan; } else { BackgroundWorkerHelper.IsReloginInvoked = false; } if (!bCancel && cxWSResponseScanStatus != null && !isIISStoped) { ScanProgress progress = new ScanProgress( _scan.UploadSettings.ProjectName, statusScan.RunStatus.ToString(), statusScan.StageName, statusScan.StepMessage, statusScan.CurrentStagePercent, 0, 100, statusScan.TotalPercent); if (!backgroundMode) { view.Progress = progress; } try { CommonActionsInstance.getInstance().ScanProgressView.Progress = progress; } catch (Exception ex) { Logger.Create().Error(ex.ToString()); } if (statusScan.RunStatus == CurrentStatusEnum.Failed) { TopMostMessageBox.Show(statusScan.StageMessage, "Scan Error"); bCancel = true; } if (_scan.ScanView == null || _scan.ScanView.Visibility == false) { var scanStatusBar = new ScanStatusBar(true, string.Format("Scaning project {0}: {1} {2}", _scan.UploadSettings.ProjectName, statusScan.StepMessage, statusScan.RunStatus), statusScan.TotalPercent, 100); CommonActionsInstance.getInstance().UpdateScanProgress(scanStatusBar); } } return(statusScan); }
public void ScanLibrary(Guid userId, Guid?collectionId, bool clear, CancellationToken cancellationToken) { if (ScanInProgress) { return; } Task.Run(async() => { ScanProgress = new ScanProgress(); ScanInProgress = true; _metadataRepositoryCache.UseCache = false; try { var collections = await _settingsRepository.GetCollectionsAsync(cancellationToken).ConfigureAwait(false); var collectionCount = 0; var collectionsToScan = collections.Where(c => c.Enabled).ToList(); if (collectionId.HasValue) { collectionsToScan = collectionsToScan.Where(c => c.Id == collectionId).ToList(); } ScanProgress.TotalCollectionCount = collectionsToScan.Count; foreach (var collection in collectionsToScan) { collectionCount++; ScanProgress.CurrentCollection = collectionCount; ScanProgress.CurrentCollectionId = collection.Id; if (!Directory.Exists(collection.Path)) { throw new Exception(); } if (clear) { collection.DateModified = DateTime.MinValue; await _metadataRepository.InsertOrUpdateCollectionAsync(collection, cancellationToken).ConfigureAwait(false); } var files = Directory.GetFiles(collection.Path, collection.Filter, SearchOption.AllDirectories); var fileCount = 0; ScanProgress.TotalFileCount = files.Length; foreach (var file in files) { fileCount++; ScanProgress.CurrentFile = fileCount; ScanProgress.CurrentFilename = file; if (fileCount == 1 || fileCount % 250 == 0) { _metadataRepository.EndTransaction(true, cancellationToken); _metadataRepository.BeginTransaction(cancellationToken); } await _metadataRepositoryCache.GetTrackAsync(userId, file, collection.Id, false, true, cancellationToken).ConfigureAwait(false); if (!ScanInProgress) { break; } } if (!ScanInProgress) { break; } _metadataRepository.EndTransaction(true, cancellationToken); foreach (var track in await _metadataRepository.GetTracksAsync(userId, collection.Id, cancellationToken).ConfigureAwait(false)) { var fileExists = File.Exists(track.Media.Path); if (track.Media.Visible == fileExists) { continue; } track.Media.Visible = fileExists; await _metadataRepository.InsertOrUpdateFileInfoAsync(track.Media, cancellationToken).ConfigureAwait(false); if (!fileExists) { await _metadataRepository.DeleteTrackReferencesAsync(track.Media, cancellationToken).ConfigureAwait(false); } } await _metadataRepository.DeleteAlbumReferencesAsync(cancellationToken).ConfigureAwait(false); } } catch (Exception ex) { _metadataRepository.EndTransaction(false, cancellationToken); File.WriteAllText($"{Guid.NewGuid():n}.txt", ex.ToString()); } finally { ScanProgress = null; ScanInProgress = false; _metadataRepositoryCache.UseCache = true; } }, cancellationToken); }
/// <summary> /// Update project name delegate function. Used for async calls /// </summary> /// <param name="value"></param> private void UpdateProjectName(ScanProgress value) { lblProjectName.Text = string.Format(PROJECT_NAME, value.ProjectName); }
private void UpdateCurrentIterationProgress(ScanProgress value) { lblCurrentIterationProgress.Text = string.Format(_lblCurrentIterationProgressFormat, value.RunStatus, value.CurrentStageMessage); }
/// <summary> /// Clear progress. Fill by empty values /// </summary> public void Clear() { Progress = new ScanProgress(NOT_READY_TEXT, string.Empty, string.Empty, 0, 100, 0); }
/// <summary> /// Update progress status delegate function. Used for async calls /// </summary> /// <param name="value"></param> private void UpdateProgress(ScanProgress value) { progressTotal.Minimum = value.StartPosition; progressTotal.Maximum = value.EndPosition; progressTotal.Value = value.CurrentPosition; }
/// <summary> /// Update current iteration progress status delegate function. Used for async calls /// </summary> /// <param name="value"></param> private void UpdateCurrentIterationProgress(ScanProgress value) { lblCurrentIterationProgress.Text = string.Format(CURRENT_ITERATION_PROGRESS_FORMAT, value.CurrentStagePercent, value.CurrentStageMessage); }
/// <summary> /// Update current iteration name delegate function. Used for async calls /// </summary> /// <param name="value"></param> private void UpdateCurrentIterationName(ScanProgress value) { lblCurrentIterationName.Text = string.Format(CURRENT_ITERATION_NAME_FORMAT, value.RunStatus, value.CurrentStageName); }
/// <summary> /// Update project project scan progress delegate function. Used for async calls /// </summary> /// <param name="value"></param> private void UpdateProjectScanTotalTopProgress(ScanProgress value) { lblProgressTotalTop.Text = string.Format(PROJECT_SCAN_TOTAL_PROGRESS, value.CurrentPosition); }
public void SetOutputChunkSizeTemplate(string wimFileName, CompressionType compType, uint chunkSize, bool success) { string destDir = TestHelper.GetTempDir(); try { Directory.CreateDirectory(destDir); bool[] _checked = new bool[5]; for (int i = 0; i < _checked.Length; i++) { _checked[i] = false; } CallbackStatus ProgressCallback(ProgressMsg msg, object info, object progctx) { switch (msg) { case ProgressMsg.ScanBegin: { ScanProgress m = (ScanProgress)info; Assert.IsNotNull(info); _checked[0] = true; } break; case ProgressMsg.ScanEnd: { ScanProgress m = (ScanProgress)info; Assert.IsNotNull(info); _checked[1] = true; } break; case ProgressMsg.WriteMetadataBegin: Assert.IsNull(info); _checked[2] = true; break; case ProgressMsg.WriteStreams: { WriteStreamsProgress m = (WriteStreamsProgress)info; Assert.IsNotNull(m); _checked[3] = true; } break; case ProgressMsg.WriteMetadataEnd: Assert.IsNull(info); _checked[4] = true; break; } return(CallbackStatus.Continue); } // Capture Wim string srcDir = Path.Combine(TestSetup.SampleDir, "Src01"); string wimFile = Path.Combine(destDir, wimFileName); using (Wim wim = Wim.CreateNewWim(compType)) { wim.RegisterCallback(ProgressCallback); try { wim.SetOutputChunkSize(chunkSize); } catch (WimLibException) { if (success) { Assert.Fail(); } else { return; } } wim.AddImage(srcDir, "UnitTest", null, AddFlags.None); wim.Write(wimFile, Wim.AllImages, WriteFlags.None, Wim.DefaultThreads); WimInfo wi = wim.GetWimInfo(); Assert.IsTrue(wi.ImageCount == 1); } TestHelper.CheckWimPath(SampleSet.Src01, wimFile); } finally { if (Directory.Exists(destDir)) { Directory.Delete(destDir, true); } } }
private static void Progress_ProgressChanged(object sender, ScanProgress e) { Console.WriteLine($"{e.File} ({e.Index}/{e.TotalIndex}):"); }
private void UpdateCurrentIterationName(ScanProgress value) { }
public bool CaptureImage( string wimFile, string imageName, string imageDescription, string imageFlag, string InputDirectory, string imageDisplayName = null, string imageDisplayDescription = null, WimCompressionType compressionType = WimCompressionType.Lzx, IImaging.ProgressCallback progressCallback = null, int UpdateFrom = -1, bool PreserveACL = true) { string title = $"Creating {imageName} ({wimFile.Split('\\').Last()})"; try { CallbackStatus ProgressCallback(ProgressMsg msg, object info, object progctx) { switch (msg) { case ProgressMsg.ScanBegin: { ScanProgress m = (ScanProgress)info; progressCallback?.Invoke($"Scanning files ({m.NumBytesScanned} bytes scanned, {m.NumDirsScanned} Directories, {m.NumNonDirsScanned} Files, Current directory: {m.CurPath})", 0, true); } break; case ProgressMsg.ScanDEntry: { ScanProgress m = (ScanProgress)info; progressCallback?.Invoke($"Scanning files ({m.NumBytesScanned} bytes scanned, {m.NumDirsScanned} Directories, {m.NumNonDirsScanned} Files, Current directory: {m.CurPath})", 0, true); } break; case ProgressMsg.ScanEnd: { ScanProgress m = (ScanProgress)info; progressCallback?.Invoke($"Scanning files ({m.NumBytesScanned} bytes scanned, {m.NumDirsScanned} Directories, {m.NumNonDirsScanned} Files, Current directory: {m.CurPath})", 0, true); } break; case ProgressMsg.WriteMetadataBegin: break; case ProgressMsg.WriteStreams: { WriteStreamsProgress m = (WriteStreamsProgress)info; progressCallback?.Invoke(title, (int)Math.Round((double)m.CompletedBytes / m.TotalBytes * 100), false); } break; case ProgressMsg.WriteMetadataEnd: break; } return(CallbackStatus.Continue); } if (File.Exists(wimFile)) { using (Wim wim = Wim.OpenWim(wimFile, OpenFlags.WriteAccess)) { wim.RegisterCallback(ProgressCallback); wim.AddImage(InputDirectory, imageName, null, PreserveACL ? AddFlags.StrictAcls : AddFlags.NoAcls); if (!string.IsNullOrEmpty(imageDescription)) { wim.SetImageDescription((int)wim.GetWimInfo().ImageCount, imageDescription); } if (!string.IsNullOrEmpty(imageDisplayName)) { wim.SetImageProperty((int)wim.GetWimInfo().ImageCount, "DISPLAYNAME", imageDisplayName); } if (!string.IsNullOrEmpty(imageDisplayDescription)) { wim.SetImageProperty((int)wim.GetWimInfo().ImageCount, "DISPLAYDESCRIPTION", imageDisplayDescription); } if (!string.IsNullOrEmpty(imageFlag)) { wim.SetImageFlags((int)wim.GetWimInfo().ImageCount, imageFlag); } if (UpdateFrom != -1) { wim.ReferenceTemplateImage((int)wim.GetWimInfo().ImageCount, UpdateFrom); } wim.Overwrite(WriteFlags.None, Wim.DefaultThreads); } } else { var compression = CompressionType.None; switch (compressionType) { case WimCompressionType.Lzms: { compression = CompressionType.LZMS; break; } case WimCompressionType.Lzx: { compression = CompressionType.LZX; break; } case WimCompressionType.None: { compression = CompressionType.None; break; } case WimCompressionType.Xpress: { compression = CompressionType.XPRESS; break; } } using (Wim wim = Wim.CreateNewWim(compression)) { wim.RegisterCallback(ProgressCallback); string config = @"[ExclusionList] \$ntfs.log \hiberfil.sys \pagefile.sys \swapfile.sys \System Volume Information"; var configpath = Path.GetTempFileName(); File.Delete(configpath); File.WriteAllText(configpath, config); wim.AddImage(InputDirectory, imageName, configpath, PreserveACL ? AddFlags.StrictAcls : AddFlags.NoAcls); if (!string.IsNullOrEmpty(imageDescription)) { wim.SetImageDescription((int)wim.GetWimInfo().ImageCount, imageDescription); } if (!string.IsNullOrEmpty(imageDisplayName)) { wim.SetImageProperty((int)wim.GetWimInfo().ImageCount, "DISPLAYNAME", imageDisplayName); } if (!string.IsNullOrEmpty(imageDisplayDescription)) { wim.SetImageProperty((int)wim.GetWimInfo().ImageCount, "DISPLAYDESCRIPTION", imageDisplayDescription); } if (!string.IsNullOrEmpty(imageFlag)) { wim.SetImageFlags((int)wim.GetWimInfo().ImageCount, imageFlag); } wim.Write(wimFile, Wim.AllImages, WriteFlags.None, Wim.DefaultThreads); File.Delete(configpath); } } } catch (Exception ex) { return(false); } return(ReseatWIMXml(wimFile)); }
public bool AddFileToImage(string wimFile, int imageIndex, string fileToAdd, string destination, IImaging.ProgressCallback progressCallback = null) { string title = $"Adding {destination} to {wimFile.Split('\\').Last()}..."; try { CallbackStatus ProgressCallback(ProgressMsg msg, object info, object progctx) { switch (msg) { case ProgressMsg.ScanBegin: { ScanProgress m = (ScanProgress)info; progressCallback?.Invoke($"Scanning files ({m.NumBytesScanned} bytes scanned, Current directory: {m.CurPath})", 0, true); } break; case ProgressMsg.ScanEnd: { ScanProgress m = (ScanProgress)info; progressCallback?.Invoke($"Scanning files ({m.NumBytesScanned} bytes scanned, Current directory: {m.CurPath})", 0, true); } break; case ProgressMsg.WriteMetadataBegin: break; case ProgressMsg.UpdateBeginCommand: break; case ProgressMsg.UpdateEndCommand: break; case ProgressMsg.WriteStreams: { WriteStreamsProgress m = (WriteStreamsProgress)info; progressCallback?.Invoke(title, (int)Math.Round((double)m.CompletedBytes / m.TotalBytes * 100), false); } break; case ProgressMsg.WriteMetadataEnd: break; } return(CallbackStatus.Continue); } using (Wim wim = Wim.OpenWim(wimFile, OpenFlags.WriteAccess)) { wim.RegisterCallback(ProgressCallback); wim.UpdateImage( imageIndex, UpdateCommand.SetAdd(fileToAdd, destination, null, AddFlags.None), UpdateFlags.SendProgress); wim.Overwrite(WriteFlags.None, Wim.DefaultThreads); } } catch { return(false); } return(ReseatWIMXml(wimFile)); }
public void Clear() { Progress = new ScanProgress(_notReadyText, string.Empty, string.Empty, 0, 100, 0); }
/// <summary> /// Scans the folders and adds/updates media. /// </summary> /// <param name="background">Set if it should be backgrounded or not</param> /// <param name="prog">Delegate to recieve scan progress events</param> public void ScanForNewFiles(bool background,ScanProgress prog) { //Calculate the size of the sub_progress for each folder. float prog_folderSLength = 100f/_musicDir.Length; //Scan all the music library directories for (int i = 0; i < _musicDir.Length; i++) { List<FileInfo> files = new List<FileInfo>(); //Get all supported music format extensions ReadOnlyCollection<FileType> musicTypes = FileType.MusicFileTypes ; try { #if DEBUG if (prog != null) prog(i * prog_folderSLength, "Finding files in: " + _musicDir[i].Name + "."); #endif //Get all the files with the supported extensions in the current folder for (int a = 0; a < musicTypes.Count; a++) { files.AddRange(_musicDir[i].GetFiles("*." + musicTypes[a].FileExt, SearchOption.AllDirectories)); } //Make sures the progress shows up in a logical order files.Sort(delegate(FileInfo x, FileInfo y) { return x.FullName.CompareTo(y.FullName); }); float prog_fileSLength = prog_folderSLength / (float)files.Count; for (int c = 0; c < files.Count; c++) { c++; FileInfo current = files[c]; float prog_current = i * prog_folderSLength + c * prog_fileSLength; if (prog != null) prog(prog_current, "Analyzing file: " + current.Name); #if DEBUG else System.Console.WriteLine(prog_current + " Analyzing file: " + current.Name); #endif try { //Get the database object for the file path. MediaItem item = _lib.GetItemByFilePath(null, current.FullName); //If file isn't already in database add it. if (item == null) { item = AnayalizeFile(current, null); _lib.AddItem(item); } //Check if the file has been modified since last time. else if (((DateTime)item[CategoryField.DateModified]) != current.LastWriteTime) { item = AnayalizeFile(current, item); _lib.UpdateItem(item); } } catch (Exception ex) { if (prog != null) prog(prog_current, "Error: " + ex.Message); Util.Log.LogMsg(ex.Message); } } if (prog != null) prog(100, "Finished."); } catch (DirectoryNotFoundException) { if (prog != null) prog(-2, "Could not find directory: " + _musicDir[i].FullName + "!"); } catch (Exception ex) { if (prog != null) prog(-2, "Error in searching for files: "+ex.Message); } } }