private void FindByIdSoundfingerprinting(int queryId) { if (queryId != -1) { Track track = databaseService.ReadTrackById(queryId); if (track != null) { if (track.FilePath != null && File.Exists(track.FilePath)) { // create background worker arugment BackgroundWorkerArgument bgWorkerArg = new BackgroundWorkerArgument { QueryFile = new FileInfo(track.FilePath), ThresholdTables = (int)ThresholdTablesCombo.SelectedValue, OptimizeSignatureCount = LessAccurateCheckBox.Checked, DoSearchEverything = SearchAllFilesCheckbox.Checked }; // and do the search DoSoundfingerprintingsSearch(bgWorkerArg); } else { MessageBox.Show("File does not exist!"); } } else { MessageBox.Show("File-id does not exist!"); } } }
/// <summary> /// The main method call to print an array of files in a specified folder /// </summary> /// <param name="ACaller">The calling screen. This must implement the IPrintProgress interface</param> /// <param name="APrinterName">Name of the printer to print to</param> /// <param name="AFolderPath">Full path to the folder containing the files</param> /// <param name="AFiles">The files to print</param> public void StartPrintingAsync(IPrintProgress ACaller, string APrinterName, string AFolderPath, string[] AFiles) { FCallerForm = ACaller; BackgroundWorkerArgument args = new BackgroundWorkerArgument(APrinterName, AFolderPath, AFiles); FBackgroundWorker.RunWorkerAsync(args); }
private void FBackgroundWorker_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorkerArgument args = (BackgroundWorkerArgument)e.Argument; int countFiles = args.Files.GetLength(0); int countDone = 0; // Get the print delay from client config. The default is 2000 ms. // A value can be specified for a specific printer or as a general value int printDelay = TAppSettingsManager.GetInt32(string.Format("{0}.PrintQueueDelay", args.PrinterName), 0); if (printDelay <= 0) { // There was no printer-specific delay, so check the blanket value. Default is 2000 ms. printDelay = TAppSettingsManager.GetInt32("PrintQueueDelay", 2000); } foreach (String FileName in args.Files) { if (FBackgroundWorker.CancellationPending) { e.Cancel = true; FBackgroundWorker.ReportProgress(0, Catalog.GetString("Printing aborted")); return; } // Get a lock on this (empty) piece of code. If it is already locked we will pause here until the lock is released (above) lock (FPauseObject) { } // The lock is released now (or never held) // Open Source OpenPetra: we do not use Templater here // TTemplaterAccess.RunPrintJob(args.PrinterName, Path.Combine(args.FolderPath, FileName)); countDone++; FBackgroundWorker.ReportProgress( (countDone * 100) / countFiles, string.Format(Catalog.GetString("Printing {0} of {1}"), countDone, countFiles)); // This sleep is important for two reasons... // 1. We need to allow some time for the pause button click event to obtain the lock before we print the next document // 2. The RunPrintJob method waits until the process that places the document into the print queue completes BUT ... // Some print applications like Word or PDFCreator need a little more time to close down and close open dialogs. // If we do not allow enough time something like PDFCreator may merge two documents into one folder or Word may leave a dialog showing // for the current document. // Two seconds is enough. Less may be possible. But 2 secs is probably ok unless the printer is VERY fast and can print documents // faster than we put them into the print queue. System.Threading.Thread.Sleep(printDelay); } FBackgroundWorker.ReportProgress(100, Catalog.GetString("Printing complete")); }
/// <summary> /// Method to run in the background while showing a "Please wait" screen /// </summary> /// <param name="sender">The "Please wait" screen form</param> /// <param name="e">Event arguments</param> void findSimilarSearch_DoWork(SplashSceenWaitingForm sender, DoWorkEventArgs e) { // e.Argument always contains whatever was sent to the background worker // in RunWorkerAsync. We can simply cast it to its original type. BackgroundWorkerArgument argObject = e.Argument as BackgroundWorkerArgument; // Perform a time consuming operation and report progress. List <QueryResult> queryList = Analyzer.SimilarTracksSoundfingerprintingList(argObject.QueryFile, repository, argObject.ThresholdTables, argObject.OptimizeSignatureCount, argObject.DoSearchEverything, sender); // and set the result argObject.QueryResultList = queryList; e.Result = argObject; }
/// <summary> /// The main method call to print all files in a specified folder. The method displays a Printer Dialog /// </summary> /// <param name="ACaller">The calling screen. This must implement the IPrintProgress interface</param> /// <param name="AFolderPath">Full path to the folder containing the files</param> public void StartPrintingAsync(IPrintProgress ACaller, string AFolderPath) { FCallerForm = ACaller; string printerName = null; using (PrintDialog pd = new PrintDialog()) { if (pd.ShowDialog() != DialogResult.OK) { RunWorkerCompletedEventArgs completedArgs = new RunWorkerCompletedEventArgs(null, null, true); ACaller.AsyncPrintingCompleted(completedArgs); return; } // Remember this for use lower down printerName = String.Format("\"{0}\"", pd.PrinterSettings.PrinterName); } // Get all the files in the specified folder string[] allFiles = Directory.GetFiles(AFolderPath); // Create a sorted list of the files (they will be named in sequence) SortedList <string, string> sortedFiles = new SortedList <string, string>(); foreach (string fullPath in allFiles) { string fileName = Path.GetFileName(fullPath); sortedFiles.Add(fileName.Substring(0, 4), fileName); } // Now create a simple list from the sorted list List <string> fileList = new List <string>(); foreach (KeyValuePair <string, string> kvp in sortedFiles) { fileList.Add(kvp.Value); } // And call our async method BackgroundWorkerArgument args = new BackgroundWorkerArgument(printerName, AFolderPath, fileList.ToArray()); FBackgroundWorker.RunWorkerAsync(args); }
protected override void OnRPMChanged(int _newRPM) { if (_newRPM < REALTIME_RPM_THRESHOLD) { this.simulatedExhaustNote.Stop(); if (this.backgroundWorker1.IsBusy) { this.backgroundWorker1.CancelAsync(); } this.radioButton_RealTime.Checked = true; } else { this.radioButton_Simulation.Checked = true; } if (this.radioButton_Simulation.Checked) { if (base.Engine != null) { BackgroundWorkerArgument _backgroundWorkerArgument = new BackgroundWorkerArgument( base.Engine, _newRPM); if (!this.backgroundWorker1.IsBusy) { this.backgroundWorker1.RunWorkerAsync(_backgroundWorkerArgument); } else { this.pendingBackgroundWorkerArgument = _backgroundWorkerArgument; this.backgroundWorker1.CancelAsync(); } } else { this.simulatedExhaustNote.Stop(); } } }
private void DoSoundfingerprintingsSearch(BackgroundWorkerArgument bgWorkerArg) { // Start "please wait" screen splashScreen = new SplashSceenWaitingForm(); splashScreen.DoWork += new SplashSceenWaitingForm.DoWorkEventHandler(findSimilarSearch_DoWork); splashScreen.Argument = bgWorkerArg; // check return value DialogResult result = splashScreen.ShowDialog(); if (result == DialogResult.Cancel) { // the user clicked cancel } else if (result == DialogResult.Abort) { // an unhandled exception occured in user function // you may get the exception information: MessageBox.Show(splashScreen.Result.Error.Message); } else if (result == DialogResult.OK) { // the background worker finished normally // the result of the background worker is stored in splashScreen.Result BackgroundWorkerArgument argObject = splashScreen.Result.Result as BackgroundWorkerArgument; if (argObject.QueryResultList != null) { // Get query list from the argument object queryResultList = new BindingList <QueryResult>(argObject.QueryResultList); // update grid bs.DataSource = queryResultList; dataGridView1.DataSource = queryResultList; this.dataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; this.dataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; } } }
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (!e.Cancelled) { if (this.radioButton_Simulation.Checked) { Wave _wave = (Wave)e.Result; this.simulatedExhaustNote.Stop(); this.simulatedExhaustNote.Wave = _wave; this.simulatedExhaustNote.Volume = this.trackBar_Volume.Value; this.simulatedExhaustNote.Play(true); } } else //če je bil cancellan, imamo v morda pendingu { if (this.pendingBackgroundWorkerArgument != null) { this.backgroundWorker1.RunWorkerAsync(this.pendingBackgroundWorkerArgument); this.pendingBackgroundWorkerArgument = null; } } }
private void FindByFilePathSoundfingerprinting(string queryPath) { if (queryPath != "") { FileInfo fi = new FileInfo(queryPath); if (fi.Exists) { // create background worker arugment BackgroundWorkerArgument bgWorkerArg = new BackgroundWorkerArgument { QueryFile = fi, ThresholdTables = (int)ThresholdTablesCombo.SelectedValue, OptimizeSignatureCount = LessAccurateCheckBox.Checked, DoSearchEverything = SearchAllFilesCheckbox.Checked }; // and do the search DoSoundfingerprintingsSearch(bgWorkerArg); } else { MessageBox.Show("File does not exist!"); } } }
private void radioButton_Simulation_CheckedChanged(object sender, EventArgs e) { RadioButton _radioButton = (RadioButton)sender; if (_radioButton.Checked) { if (base.Engine != null) { BackgroundWorkerArgument _backgroundWorkerArgument = new BackgroundWorkerArgument( base.Engine, base.RPM); if (!this.backgroundWorker1.IsBusy) { this.backgroundWorker1.RunWorkerAsync(_backgroundWorkerArgument); } else { this.pendingBackgroundWorkerArgument = _backgroundWorkerArgument; this.backgroundWorker1.CancelAsync(); } } } }
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker _backgroundWorker = (BackgroundWorker)sender; BackgroundWorkerArgument _backgroundWorkerArgument = (BackgroundWorkerArgument)e.Argument; // t_rotacije = (60 / RPM) s // t_cikla = t_rotacije * [št rotacij za ciker] s // samplov/cikel = t_cikla * SamplesPerSecond Wave _wave = new Wave(Properties.Resources.Kick); double _rotationTime_s = 60d / _backgroundWorkerArgument.RPM; //_rotationTime_s *= 2; double _cycleTime_s = _rotationTime_s * _backgroundWorkerArgument.Engine.RevolutionsToCompleteCombinedCycle; double _samplesPerCycle = _cycleTime_s * (double)_wave.WaveFormat.SamplesPerSecond; int _strokes = _backgroundWorkerArgument.Engine.RevolutionsToCompleteCombinedCycle * 2; //po 2 stroka za eno rotacijo //dobimo koliko dolg wave lahko uporabimo int _samplesPerStroke = (int)(_samplesPerCycle / (double)_strokes); double _samplesPerDeg = _samplesPerStroke / 180d; #region "Cancelled?" if (_backgroundWorker.CancellationPending) { e.Cancel = true; return; } #endregion "Cancelled?" //dobimo zvok za 1 combustion stroke (trim je pomemben, ker wave ne sme biti daljši ali krajši od stroka!) _wave.WaveTrack.Trim(_samplesPerStroke); if (_wave.WaveTrack.SampleNumber < _samplesPerStroke) { _wave.WaveTrack.AddTo( _wave.WaveTrack.GenerateSilence(_samplesPerStroke - _wave.WaveTrack.SampleNumber)); } #region "Cancelled?" if (_backgroundWorker.CancellationPending) { e.Cancel = true; return; } #endregion "Cancelled?" //zgradimo track za cel engine Track _engineTrack = new Track(_wave.WaveTrack.ChannelNumer, _wave.WaveTrack.BitsPerSample); //v začetku je tišina; gor bomo miksali cilindre _engineTrack.AddTo(_engineTrack.GenerateSilence((int)_samplesPerCycle)); //dobimo naklone List <double> _tilts = new List <double>(); foreach (PositionedCylinder _positionedCylinder in _backgroundWorkerArgument.Engine.PositionedCylinders) { double _double = Mathematics.GetAbsoluteAngle_deg(_positionedCylinder.Tilt_deg); if (!_tilts.Contains(_double)) { _tilts.Add(_double); } } //dobimo tracke po naklonih Dictionary <double, Track> _tracks = new Dictionary <double, Track>(); //naklon, track za naklon foreach (double _tilt in _tilts) { Track _totalTrackPerTilt = new Track(_wave.WaveTrack.ChannelNumer, _wave.WaveTrack.BitsPerSample); //v začetku je tišina; gor bomo miksali cilinder _totalTrackPerTilt.AddTo(_totalTrackPerTilt.GenerateSilence((int)_samplesPerCycle)); #region "Cancelled?" if (_backgroundWorker.CancellationPending) { e.Cancel = true; return; } #endregion "Cancelled?" #region "dobimo tracke od cilindrov" foreach (PositionedCylinder _positionedCylinder in _backgroundWorkerArgument.Engine.PositionedCylinders) { if (_positionedCylinder.Tilt_deg == _tilt) { Track _track = new Track(_wave.WaveFormat.Channels, _wave.WaveFormat.BitsPerSample); foreach (Stroke _stroke in _positionedCylinder.Cycle.Strokes) { if ((_stroke.Equals(Stroke.Combustion)) || (_stroke.Equals(Stroke.CombustionExhaust))) { _track.AddTo(_wave.WaveTrack); } else { _track.AddTo(_wave.WaveTrack.GenerateSilence(_samplesPerStroke)); } #region "Cancelled?" if (_backgroundWorker.CancellationPending) { e.Cancel = true; return; } #endregion "Cancelled?" } //izračunamo na katerem samplu se začne miksanje za ta cilinder int _mixStartSample = (int)(_positionedCylinder.FiringAngle_deg * _samplesPerDeg); //zmiksamo z ostankom Track _return = _totalTrackPerTilt.MixWithReturn(_track, _mixStartSample); //če je kaj ostalo, damo na začetek (za tiste takte, ki se mogoče ne bi končali v ciklu) if ((_return != null) && (_return.SampleNumber > 0)) { _totalTrackPerTilt.MixWith(_return, 0, false); //sprostimo, ker žre dosti rama _return = null; } //sprostimo, ker žre dosti rama _track = null; GC.Collect(); #region "Cancelled?" if (_backgroundWorker.CancellationPending) { e.Cancel = true; return; } #endregion "Cancelled?" } } #endregion "dobimo tracke od cilindrov" _tracks.Add(_tilt, _totalTrackPerTilt); } //če imamo V motor ali boxer, računamo, da gre vsak bank v svoj auspuh if (_tilts.Count == 2) { Track _left = new Track(_wave.WaveFormat.Channels, _wave.WaveFormat.BitsPerSample); for (int a = 0; a < _tracks[_tilts[0]].SampleNumber; a++) { _left.Add(0, _tracks[_tilts[0]][0, a]); _left.Add(1, new Sample(16)); } Track _right = new Track(_wave.WaveFormat.Channels, _wave.WaveFormat.BitsPerSample); for (int a = 0; a < _tracks[_tilts[1]].SampleNumber; a++) { _right.Add(0, new Sample(16)); _right.Add(1, _tracks[_tilts[1]][1, a]); } _engineTrack.MixWith(_left, 0, false); _engineTrack.MixWith(_right, 0, false); } else { foreach (Track _track in _tracks.Values) { _engineTrack.MixWith(_track, 0, false); } } //damo spet v wave _wave.WaveTrack = _engineTrack; //sprostimo, ker žre dosti rama _engineTrack = null; GC.Collect(); e.Result = _wave; }
private void FindByIdSoundfingerprinting(int queryId) { if (queryId != -1) { Track track = databaseService.ReadTrackById(queryId); if (track != null) { if (track.FilePath != null && File.Exists(track.FilePath)) { // create background worker arugment BackgroundWorkerArgument bgWorkerArg = new BackgroundWorkerArgument { QueryFile = new FileInfo(track.FilePath), ThresholdTables = (int) ThresholdTablesCombo.SelectedValue, OptimizeSignatureCount = LessAccurateCheckBox.Checked, DoSearchEverything = SearchAllFilesCheckbox.Checked }; // and do the search DoSoundfingerprintingsSearch(bgWorkerArg); } else { MessageBox.Show("File does not exist!"); } } else { MessageBox.Show("File-id does not exist!"); } } }
private void FindByFilePathSoundfingerprinting(string queryPath) { if (queryPath != "") { FileInfo fi = new FileInfo(queryPath); if (fi.Exists) { // create background worker arugment BackgroundWorkerArgument bgWorkerArg = new BackgroundWorkerArgument { QueryFile = fi, ThresholdTables = (int) ThresholdTablesCombo.SelectedValue, OptimizeSignatureCount = LessAccurateCheckBox.Checked, DoSearchEverything = SearchAllFilesCheckbox.Checked }; // and do the search DoSoundfingerprintingsSearch(bgWorkerArg); } else { MessageBox.Show("File does not exist!"); } } }
private void DoSoundfingerprintingsSearch(BackgroundWorkerArgument bgWorkerArg) { // Start "please wait" screen splashScreen = new SplashSceenWaitingForm(); splashScreen.DoWork += new SplashSceenWaitingForm.DoWorkEventHandler(findSimilarSearch_DoWork); splashScreen.Argument = bgWorkerArg; // check return value DialogResult result = splashScreen.ShowDialog(); if (result == DialogResult.Cancel) { // the user clicked cancel } else if (result == DialogResult.Abort) { // an unhandled exception occured in user function // you may get the exception information: MessageBox.Show(splashScreen.Result.Error.Message); } else if (result == DialogResult.OK) { // the background worker finished normally // the result of the background worker is stored in splashScreen.Result BackgroundWorkerArgument argObject = splashScreen.Result.Result as BackgroundWorkerArgument; if (argObject.QueryResultList != null) { // Get query list from the argument object queryResultList = new BindingList<QueryResult>( argObject.QueryResultList ); // update grid bs.DataSource = queryResultList; dataGridView1.DataSource = queryResultList; this.dataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; this.dataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; } } }