Beispiel #1
0
        private void BackgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            try {
                LoginInformation loginInfo = ( LoginInformation )e.Argument;

                if (_worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }

                if (_vm != null)
                {
                    ErrType err = _vm.Login(loginInfo.AccountName, loginInfo.Password, loginInfo.AccountType);

                    if (_worker.CancellationPending)
                    {
                        e.Cancel = true;
                        return;
                    }
                    e.Result = err;
                }
                CheckUpdateProgram();
            }
            catch (Exception ex) {
                e.Result = new ErrType(ERR.EXEPTION, ErrorText.ServiceError);
            }
        }
Beispiel #2
0
        void bgWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            System.IO.StreamReader sr = new System.IO.StreamReader(this.importFileName);
            int    counter = 0;
            string oldValue, newValue, line;

            while ((line = sr.ReadLine()) != null)
            {
                string langPair = langFrom + "-" + langTo;
                System.Console.WriteLine(langPair);

                oldValue = line.Trim();
                newValue = yt.Translate(oldValue, langPair);
                vocab.Add(new VocabItem(oldValue, newValue, counter));
                System.Console.WriteLine(line);
                System.Console.WriteLine(newValue);
                counter++;
                bgWorker.ReportProgress(counter);
            }

            for (int i = 0; i < vocab.Count; i++)
            {
                System.Console.WriteLine(vocab[i].isValid);
                if (!vocab[i].isValid)
                {
                    badvocab.Add(vocab[i]);
                }
            }
            sr.Close();
        }
Beispiel #3
0
        private void backgroundWorker2_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            if (m_client.Connected)
            {
                try
                {
                    m_sw.WriteLine(m_strSendingText);

                    this.lb_ChatWindow.Invoke(new MethodInvoker(delegate()
                    {
                        lb_ChatWindow.Items.Add("Me:" + rtb_Message.Text);
                        rtb_Message.Text = "";
                    }
                                                                ));
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
            else
            {
                MessageBox.Show("Sending Failed");
            }

            backgroundWorker2.CancelAsync();
        }
Beispiel #4
0
        private void backgroundSentJson_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:8090/person/SavePerson");

            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method      = "POST";

            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                string json = new JavaScriptSerializer().Serialize(new
                {
                    description = newPerson.Description,
                    fPrint      = newPerson.FingerPrint,
                    id          = newPerson.Id,
                    name        = newPerson.Name
                });

                streamWriter.Write(json);
            }

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
            }
        }
Beispiel #5
0
        private static void OnDoBackgroundWork(System.Object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            ResponseData result = new ResponseData();

            try
            {
                RequestData        req      = (RequestData)e.Argument;
                string             code     = req.Text;
                NativeCodeAnalyzer analyzer = NativeCodeAnalyzerFactory.CreateForMiniParse(OsVersion.WindowsVista, req.InitialMacroList);
                analyzer.IncludePathList.Add("c:\\program files (x86)\\windows kits\\8.1\\include\\shared");
                using (var reader = new StringReader(code))
                {
                    NativeCodeAnalyzerResult parseResult = analyzer.Analyze(reader);
                    ErrorProvider            ep          = parseResult.ErrorProvider;
                    if (ep.Warnings.Count == 0 && ep.Errors.Count == 0)
                    {
                        result.ParseOutput = "None ...";
                    }
                    else
                    {
                        result.ParseOutput = ep.CreateDisplayString();
                    }
                }
            }
            catch (Exception ex)
            {
                result.ParseOutput = ex.Message;
            }

            e.Result = result;
        }
Beispiel #6
0
        private void backgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            if (!(sender is BackgroundWorker worker))
            {
                return;
            }
            var n = (int)e.Argument;

            try
            {
                e.Result = _webService.Fibonacci(n);
            }
            catch (System.ServiceModel.CommunicationException exception)
            {
                MessageBox.Show("Connection Error", "Oups", MessageBoxButtons.OK);
                throw new Exception("Connection Error", exception);
            }
            catch (Exception exception)
            {
                MessageBox.Show("An error has ocurred", "Oups", MessageBoxButtons.OK);
                throw new Exception("Connection Error", exception);
            }
            for (int i = 1; i <= n; i++)
            {
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    break;
                }
                System.Threading.Thread.Sleep(250);
                worker.ReportProgress(i * 100 / n);
            }
        }
		void ReadFilesProperties(object sender, DoWorkEventArgs e)
		{
			while(_itemsToRead.Count > 0)
			{
				BaseItem item = _itemsToRead[0];
				_itemsToRead.RemoveAt(0);

				Thread.Sleep(50); //emulate time consuming operation
				if (item is FolderItem)
				{
					DirectoryInfo info = new DirectoryInfo(item.ItemPath);
					item.Date = info.CreationTime;
				}
				else if (item is FileItem)
				{
					FileInfo info = new FileInfo(item.ItemPath);
					item.Size = info.Length;
					item.Date = info.CreationTime;
					if (info.Extension.ToLower() == ".ico")
					{
						Icon icon = new Icon(item.ItemPath);
						item.Icon = icon.ToBitmap();
					}
					else if (info.Extension.ToLower() == ".bmp")
					{
						item.Icon = new Bitmap(item.ItemPath);
					}
				}
				_worker.ReportProgress(0, item);
			}
		}
Beispiel #8
0
        void backroungWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    //On récupère les informations
                    dbc = new DataBaseContext(DataBaseContext.DBConnectionString);

                    //Les logs du niveau home
                    var homelogs = from log in dbc.Logs
                                   where log.Reponse.Question.Scene.Niveau.Nom == "home"
                                   orderby log.Date descending
                                   select log;

                    foreach(var homelog in homelogs)
                    {
                        if (homelog.Reponse.Vrai == false)
                        {

                            logs.Add(new ParentsCornerItem(homelog.Date.ToString(), "Question : " + homelog.Reponse.Question.Intitule, "Answer :" + homelog.Reponse.Intitule, Colors.Red.ToString()));
                        }
                        else
                        {
                            //lstParentsHome.Items.Add(new ParentsCornerItem(homelog.Date.ToString(), homelog.Reponse.Question.Intitule, homelog.Reponse.Intitule));
                            logs.Add(new ParentsCornerItem(homelog.Date.ToString(), "Question : " + homelog.Reponse.Question.Intitule, "Answer : " + homelog.Reponse.Intitule, "#FF0A7C37"));
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Erreur", MessageBoxButton.OK);
            }
        }
Beispiel #9
0
        protected override void BackgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            Process _myProcesses = Process.GetCurrentProcess();

            ReportProgress(this, new ProgressChangedEventArgs(1, String.Format("Starting archiving background process {0}.", _myProcesses.MainWindowTitle)));
            BackgroundProcessArgument _argument = (BackgroundProcessArgument)e.Argument;

            if ((_argument.Phases & Phases.CleanupContent) > 0)
            {
                CleanupContent.DoCleanupContent(_argument.URL, _argument.SQLConnectionString, x => ReportProgress(this, x), y => { MemoryUsage(_myProcesses); this.Log(y, Category.Debug, Priority.None); });
            }
            else
            {
                this.ReportProgress(this, new ProgressChangedEventArgs(0, "Cleanup content skipped because is not selected by the user."));
            }
            if ((_argument.Phases & Phases.SynchronizationContent) > 0)
            {
                SynchronizationContent.DoSynchronizationContent(_argument.URL, _argument.SQLConnectionString, x => ReportProgress(this, x), y => this.Log(y, Category.Debug, Priority.None));
            }
            else
            {
                this.ReportProgress(this, new ProgressChangedEventArgs(0, "Synchronization content skipped because is not selected by the user."));
            }
            if ((_argument.Phases & Phases.ArchivingContent) > 0)
            {
                ArchivingContent.DoArchivingContent(_argument.URL, _argument.SQLConnectionString, _argument.ArchivalDelay, _argument.RowLimit, x => ReportProgress(this, x), y => this.Log(y, Category.Debug, Priority.None));
            }
            else
            {
                this.ReportProgress(this, new ProgressChangedEventArgs(0, "Archiving content skipped because is not selected by the user."));
            }
        }
Beispiel #10
0
        private void loadTv(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            int complete = 0;
            int total    = this.settings.Tags.Count;

            Parallel.ForEach(this.settings.Tags, (tag) => {
                currentIndexes[tag] = 0;
                posts[tag]          = new List <Post>();

                using (WebClient wc = new WebClient()) {
                    wc.Headers.Add("X-Requested-With", "XMLHttpRequest");
                    var jsonResponse = wc.DownloadString("https://www.tumblr.com/svc/tv/search/" + WebUtility.UrlEncode(tag) + "?size=1280&limit=40");

                    dynamic json = JsonConvert.DeserializeObject(jsonResponse);
                    foreach (var image in json.response.images)
                    {
                        posts[tag].Add(new Post()
                        {
                            Url    = image.media[0].url,
                            Avatar = image.avatar,
                            Name   = image.tumblelog
                        });
                    }
                }

                complete++;
                ((BackgroundWorker)sender).ReportProgress((int)(((float)complete / (float)total) * 100));
            });
        }
        private void BackgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            try
            {
                QcImporter.ConnectProject(pwdBox.Password);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            int interationcount = QcImporter.Test2Import.Count;

            //int interation = interationcount / 100;
            for (int i = 1; i <= interationcount; i++)
            {
                try
                {
                    QcImporter.ImportQC(QcImporter.Test2Import[i - 1]);
                    // double value = i * 100.0 / QcImporter.Test2Import.Count;
                    //lbShow.Content = "Imported:" + i;
                    backgroundWorker.ReportProgress(i * 100 / interationcount);
                    //pbBar.Dispatcher.Invoke(new Action<System.Windows.DependencyProperty, object>(pbBar.SetValue), System.Windows.Threading.DispatcherPriority.Background, ProgressBar.ValueProperty, value);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
            }
        }
Beispiel #12
0
        private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            var count = 0;

            foreach (var name in names)
            {
                var splits = name.Split();
                if (splits.Length > 1)
                {
                    var prenume  = splits[0];
                    var nume     = splits[1];
                    var rezultat = FindDosareByName(prenume, nume);
                    if (rezultat != null)
                    {
                        if (rezultat.Error != null)
                        {
                            errors.Add($"Nume cautat: {name} -> Erori: {rezultat.Error}");
                        }
                        else
                        {
                            File.WriteAllText(Path.Combine(textBoxFolder.Text, $"{prenume} {nume}.json"), rezultat.Json);
                            countJson++;
                        }
                    }
                }
                count++;
                worker.ReportProgress(count);
            }
        }
Beispiel #13
0
        private void AsyncPlayFilesWorker(object sender, DoWorkEventArgs e)
        {
            var songs = (Collection<ApiAudioSong>)e.Argument;

            if (songs == null)
                return;
            if (!_parent.IsConnected())
                return;

            _parent.JsonCommand("AudioPlaylist.Clear", null);
            var i = 0;
            var args = new JsonObject();
            foreach (var apiAudioSong in songs)
            {
                if (((BackgroundWorker)sender).CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
                args["songid"] = apiAudioSong.IdSong;
                _parent.JsonCommand("AudioPlaylist.Add", args);
                if (i != 0) continue;
                _parent.JsonCommand("AudioPlaylist.Play", null);
                i++;
            }
        }
Beispiel #14
0
        private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            BackgroundWorker worker = sender as BackgroundWorker;

            BigramService bigramService = new BigramService(_settings);
            var           words         = bigramService.SplitWords(txtInput.Text);

            worker.ReportProgress(5);
            List <Bigram> bigrams = bigramService.GetSequence(words, worker);

            //string output = bigramService.GetOutput(bigrams);


            if (_settings.ShowBigramGraph == true)
            {
                setBigramChart(bigrams);
            }

            if (_settings.ShowLetterFrequency == true)
            {
                setLetterChart(bigramService.GetLetterFrequency());
                //var a = bigramService.GetLetterFrequency();
            }

            stopwatch.Stop();
            TimeSpan ts = stopwatch.Elapsed;

            txtOutput.Text = string.Format("Input length: {0} {3}Words length: {1} {3}Runtime: {4} {3}{2}", txtInput.Text.Length, words.Length, bigramService.GetOutput(bigrams), Environment.NewLine, ts.TotalSeconds);
        }
Beispiel #15
0
 //bool toCancelReceive = false;
 /// <summary>
 /// Асинхронно и рекурсивно добавляет набор файлов и директорий в кассету в указанную коллекцию
 /// и возвращает набор добавленных в базу данных XElement-записей - это для синхронизации
 /// </summary>
 /// <param name="filenamesAndCollectionId">К массиву имен файлов и директорий, последним элементом прикреплен (добавлен) идентификатор коллекции, в которую записываются внешние файлы</param>
 /// <param name="worker"></param>
 /// <param name="e"></param>
 /// <returns></returns>
 private IEnumerable<XElement> AddFilesAndDirectoriesAsync(string[] filenamesAndCollectionId,
     BackgroundWorker worker, DoWorkEventArgs e)
 {
     List<XElement> addedElements = new List<XElement>();
     string[] filenames = filenamesAndCollectionId.Take(filenamesAndCollectionId.Length - 1).ToArray();
     string collectionId = filenamesAndCollectionId[filenamesAndCollectionId.Length - 1];
     // правильно посчитаю число вводимых файлов
     int fnumber = 0;
     foreach (string fn in filenames)
     {
         if (File.Exists(fn)) { if (fn != "Thumbs.db") fnumber++; }
         else fnumber += 1 + CountTotalFiles(new DirectoryInfo(fn));
     }
     // а теперь добавлю файлы и директории с
     int count = 0;
     foreach (string fname in filenames)
     {
         if (worker.CancellationPending) break;
         if (File.Exists(fname))
         {
             if (fname != "Thumbs.db")
                 addedElements.AddRange(this.cass.AddFile(new FileInfo(fname), collectionId));
             count++;
             worker.ReportProgress(100 * count / fnumber);
         }
         else if (Directory.Exists(fname))
         {
             //smallImageFullNames.AddRange(this.cass.AddDirectory(new DirectoryInfo(fname), collectionId));
             addedElements.AddRange(AddDirectoryAsync(new DirectoryInfo(fname), collectionId, ref count, fnumber, worker));
         }
     }
     return addedElements;
 }
Beispiel #16
0
        private void bwResolver_DoWork(object sender, DoWorkEventArgs e) {
            POP3 pop3 = this.pop3;
            if (pop3 == null)
                return;
            while (true) {
                MailItem next = null;
                ListViewItem lviIt = null;
                Sync.Send(delegate(object state) {
                    foreach (ListViewItem lvi in lvm.Items) {
                        if (lvi.ImageIndex == 0) {
                            next = (MailItem)lvi.Tag;
                            lviIt = lvi;
                            break;
                        }
                    }
                }, null);
                if (next == null || lviIt == null)
                    break;
                String rows = pop3.Top(next.i, 1);
                String text = "?";
                try {
                    EML_Reader er = new EML_Reader();
                    er.read(new StringReader(rows));
                    text = er.main.mlSubject;
                }
                catch (Exception) {

                }
                Sync.Send(delegate(object state) {
                    lviIt.ImageIndex = 1;
                    lviIt.Text = text;
                }, null);
            }
        }
        /// <summary>
        /// This is meant to be run on a background thread which starts when 
        /// the user clicks the snake button. 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected override void RunContinuously(object sender, DoWorkEventArgs e)
        {
            Color c = ThreadColor;
            while (mContinueThread)
            {
                int snakeParts = mLightState.Lights.Count;
                foreach (Light turn in mLightState.Lights)
                {
                    // Each light get its turn to be the head of the snake for the given color.
                    int snakeHead = mLightState.Lights.IndexOf(turn);

                    foreach (Light light in mLightState.Lights)
                    {
                        int currentIndex = mLightState.Lights.IndexOf(light);
                        int distanceFromHead = (snakeHead - currentIndex) % snakeParts;
                        if (distanceFromHead < 0)
                            distanceFromHead += snakeParts;

                        int divideValue = distanceFromHead + 1;

                        light.Red = (int)c.R / divideValue ^ 3;
                        light.Green = (int)c.G / divideValue ^ 3;
                        light.Blue = (int)c.B / divideValue ^ 3;

                    }

                    mLightState.Update();
                    System.Threading.Thread.Sleep(100 - mSpeed);
                }
            }
            mLightState.Clear();
        }
 //backgroudwork
 private void getstauts(object sender, System.ComponentModel.DoWorkEventArgs e)
 {
     try
     {
         while (iscangetstatus)
         {
             if (this.testDevice.StylusStatue() && ismoveative == false)
             {
                 if (thiscard)
                 {
                     Settings.Default.num--;
                     this.ismoveative = getevent();
                     if (!isBabyYiNing)
                     {
                         Checkpicture checkpicture = new Checkpicture(tbSavePath.Text, Settings.Default.num + xYrulescs.Name, true, numericUpDown1.Value);
                         checkpicture.ShowDialog();
                     }
                     thiscard = false;
                     Settings.Default.num++;
                 }
                 else
                 {
                     this.ismoveative = getevent();
                     Settings.Default.num++;
                 }
             }
             Thread.Sleep(200);
         }
         e.Cancel = true;
     }
     catch (Exception ex)
     {
         Loghelper.WriteLog("获取箱体按钮状态失败", ex);
     }
 }
Beispiel #19
0
 private void bwImportTransactions_DoWork(object sender, DoWorkEventArgs e)
 {
     Basket basket = e.Argument as Basket;
     ofxFileImporter.UpdateBalance(basket);
     decimal numberOfTransactions = basket.ofxFile.Transactions.Count;
     decimal currentPosition = 0;
     List<Merchant> nationalMerchants = Merchant.NationalMerchants();
     foreach (Transaction Transaction in basket.ofxFile.Transactions)
     {
         if (ofxFileImporter.TransactionDoesNotExist(Transaction, basket.BankAccount.BankAccountID))
         {
             Transaction transaction = Transaction.CheckBankTricks(Transaction, basket.BankAccount);
             string categoryName = "";
             if (transaction.TransactionType == "ATM" && transaction.BankMemo != "STAMP PURCHASE")
                 categoryName = "Miscellaneous: Cash";
             if (categoryName == "")
                 categoryName = ofxFileImporter.FindCategory(transaction, nationalMerchants);
             int orginalTransactionID = ofxFileImporter.InsertIntoOringalTransaction(basket.BankAccount,
                 transaction, categoryName);
             ofxFileImporter.InsertIntoSplitTransction(categoryName, orginalTransactionID, transaction);
         }
         currentPosition++;
         decimal percent = currentPosition / numberOfTransactions;
         decimal percentnew = percent * 100;
         bwImportTransactions.ReportProgress((int)percentnew);
     }
 }
Beispiel #20
0
 private void imageProcessor_DoWork(object sender, DoWorkEventArgs e)
 {
     e.Result = e.Argument;
     FilterInfo filterInfo = (FilterInfo)e.Argument;
     filterInfo.Image = filterInfo.Filter.RunFilter(imageProcessor, filterInfo.Value, filterInfo.Position, filterInfo.Selection, filterInfo.Image);
     e.Result = e.Argument;
 }
Beispiel #21
0
        public static void MakeDatZips(object sender, DoWorkEventArgs e)
        {
            _bgw = sender as BackgroundWorker;
            Program.SyncCont = e.Argument as SynchronizationContext;
            if (Program.SyncCont == null)
            {
                _bgw = null;
                return;
            }

            if (!Directory.Exists(_outputdir))
                return;

            if (_treeRow != null)
                FindDats(_treeRow);
            else
            {
                RvGame tGame = new RvGame();
                tGame.DBRead((int)_gameId, true);
                ExtractGame(tGame, _outputdir);
            }
            _bgw.ReportProgress(0, new bgwText("Creating Zips Complete"));
            _bgw = null;
            Program.SyncCont = null;
        }
        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = (BackgroundWorker)sender;
            TimeSpan duration = (TimeSpan)e.Argument;

            DateTime expiration = DateTime.Now + duration;

            worker.ReportProgress(0);
            e.Result = 0;
            while (DateTime.Now < expiration)
            {
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    break;
                }

                TimeSpan remaining = expiration - DateTime.Now;
                e.Result = duration.TotalSeconds - remaining.TotalSeconds;
                int percent = 100 - (int)(100 * (remaining.TotalMilliseconds / duration.TotalMilliseconds));
                worker.ReportProgress(percent);

                // Sleep to give the UI thread a chance to process
                // updates.
                Thread.Sleep(100);
            }

            if (!e.Cancel)
            {
                e.Result = duration.TotalSeconds;
                worker.ReportProgress(100);
            }
        }
Beispiel #23
0
        static void BwDoWork(object sender, DoWorkEventArgs e)
        {
            Console.WriteLine("BwDoWork INI");

            using (var awe = new AdventureWorksEntities())
            {
                var c = new Contato()
                {
                    Nome = "Adão",
                    Sobrenome = "da Silva",
                    PasswordHash = "abc",
                    PasswordSalt = "xyz",
                    rowguid = Guid.NewGuid(),
                    ModifiedDate = DateTime.Now
                };

                awe.Contatos.AddObject(c);

                awe.SaveChanges();

                e.Result = c.ContactID;
            }

            Console.WriteLine("BwDoWork FIM");
        }
Beispiel #24
0
        //worker thread
        //-------------
        private void backgroundWorkerConnect_DoWork(object sender, DoWorkEventArgs e)
        {
            DeviceSettings sessionInfo = (DeviceSettings)e.Argument;
            BackgroundWorker worker = (BackgroundWorker)sender;

            try
            {
                _connecting = true;
                _connected = _session.OpenSession(sessionInfo.Host, sessionInfo.Username, sessionInfo.Password);

                //check remember settings
                if (_connected)
                {
                    if (checkBoxSave.Checked)
                        SettingsUtils.saveSettings(new ToolSettings
                        {
                            Device = _selectedModem,
                            Username = sessionInfo.Username,
                            Password = sessionInfo.Password,
                            Host = sessionInfo.Host,
                        });
                    else
                        SettingsUtils.deleteSettings();

                    //refresh
                    ThreadUtils.setButtonTextFromThread(buttonConnect, "Refreshing, please wait...");
                    _session.RefreshData();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unexpected error occurred. Debug info: " + ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void bkwPrint_DoWork(object sender, DoWorkEventArgs e)
        {
            List<object> Arguments = e.Argument as List<object>;

            DateTime StartDate = ((DateTime)Arguments[0]).ToDayStart();
            DateTime EndDate = ((DateTime)Arguments[1]).ToDayEnd();
            List<string> CommonPeriods = Arguments[2] as List<string>;
            List<string> OtherPeriods = Arguments[3] as List<string>;

            Dictionary<string, List<DataSet>> result = new Dictionary<string, List<DataSet>>();

            DataSet DataSet = new DataSet("DataSection");

            result.Add("請假代課統計表", new List<DataSet>());

            result["請假代課統計表"].Add(DataSet);

            DataSet.Tables.Add(StartDate.ToShortDateString().ToDataTable("開始日期", "開始日期"));
            DataSet.Tables.Add(EndDate.ToShortDateString().ToDataTable("結束日期", "結束日期"));
            DataSet.Tables.Add(K12.Data.School.DefaultSchoolYear.ToDataTable("學年度", "學年度"));
            DataSet.Tables.Add(K12.Data.School.DefaultSemester.ToDataTable("學期", "學期"));
            DataSet.Tables.Add(StartDate.Month.ToDataTable("月份", "月份"));

            List<CalendarRecord> Records = Calendar.Instance.FindReplaceRecords(null, null, null,null,StartDate, EndDate);

            SatRecords vSatRecords = new SatRecords(CommonPeriods, OtherPeriods);

            foreach (CalendarRecord Record in Records)
                vSatRecords.Add(Record);

            DataSet.Tables.Add(vSatRecords.ToDataTable());

            e.Result = result;
        }
Beispiel #26
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            while (socketManager.CountClients < maxClients)
            {
                if (worker.CancellationPending)
                {
                    socketManager.Stop();
                    e.Cancel = true;
                    break;
                }

                if (socketManager.HasIncoming)
                {
                    SocketHandler player = socketManager.ConnectPlayer();
                    string playerName = player.WaitForName();
                    Debug.WriteLine(playerName);
                }

                string state = string.Format("Waiting for {0} players..",
                                             maxClients -
                                             socketManager.CountClients);
                worker.ReportProgress(socketManager.CountClients * 100 / maxClients,
                                      state);
                Thread.Sleep(10);
            }
        }
Beispiel #27
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();

            //// There are various options, set as needed
            htmlDoc.OptionFixNestedTags = true;

            htmlDoc.LoadHtml(DownloadPage("http://www.pogdesign.co.uk/cat/showselect.php"));
            HtmlNodeCollection series = htmlDoc.DocumentNode.SelectNodes("//div[@class='butthold'][" + (int)e.Argument + "]/div");

            ElementCount = series.Count;

            if (series != null)
            {
                for (int i = 1; i < ElementCount; i++)
                {
                    Console.WriteLine(series[i].SelectSingleNode("label").InnerText.Trim());
                    backgroundWorker1.ReportProgress(i, correctTitle(series[i].SelectSingleNode("label").InnerText.Trim()));
                }
            }
            else
            {
                Console.WriteLine("NULL NODE");
            }
        }
Beispiel #28
0
        public void Mux(object sender, DoWorkEventArgs e)
        {
            var inputM2TsFlags = _keepM2TsAudio ? null : "--no-audio";
            var inputMkvFlags = _keepM2TsAudio ? "--no-audio" : null;

            var args = new ArgumentList();

            // Chapter file
            args.AddIfAllNonEmpty("--chapters", _inputChaptersPath);

            // Output file
            args.AddAll("-o", _outputMkvPath);

            // Input M2TS file
            args.AddNonEmpty("--no-video", inputM2TsFlags, _inputM2TsPath);

            // If an input chapter file is specified, exclude chapters from the input MKV file
            if (!string.IsNullOrEmpty(_inputChaptersPath))
                args.Add("--no-chapters");

            // Input MKV file
            args.AddNonEmpty(inputMkvFlags, _inputMkvPath);

            Execute(args, sender, e);
        }
Beispiel #29
0
 private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
 {
     try
     {
     this.backgroundWorker1.ReportProgress(0, string.Format("{0}に接続中・・・", this.uri));
     this.client = new WebClient();
     while (this.client.IsBusy)
     {
         Thread.Sleep(100);
         if (this.backgroundWorker1.CancellationPending)
         {
             return;
         }
     }
     Stream stream = this.client.OpenRead(this.uri);
     this.backgroundWorker1.ReportProgress(0, string.Format("{0}に接続完了", this.uri));
     this.backgroundWorker1.ReportProgress(0, string.Format("データを読み込み中", this.uri));
     StreamReader reader = new StreamReader(stream);
     string str = reader.ReadToEnd();
     this.xmltext = str;
     reader.Close();
     this.backgroundWorker1.ReportProgress(0, string.Format("完了", this.uri));
     }
     catch (Exception exception)
     {
     throw new Exception(exception.Message);
     }
 }
        protected void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {

            Debug.Assert(e.Argument is CalculateGroupsAsyncArgs);

            CalculateGroupsAsyncArgs tmpArgs = (CalculateGroupsAsyncArgs)e.Argument;
            AnalyzerBase[] analyzers = tmpArgs.Analyzers.ToArray();
            IGraph graph = tmpArgs.Graph;
            LinkedList<AnalyzeResultBase> results = new LinkedList<AnalyzeResultBase>();
            foreach (AnalyzerBase analyzer in analyzers)
            {
                
                AnalyzeResultBase result;
                if (!analyzer.tryAnalyze(graph, m_oBackgroundWorker, out result)) // The user cancelled.
                {
                    e.Cancel = true;
                    m_oBackgroundWorker.ReportProgress(0, "Cancelled.");
                    return;
                }
                
                results.AddLast(result);
            }
            Debug.Assert(results != null);
            e.Result = results;
            m_oBackgroundWorker.ReportProgress(100, new ProgressState(100, "Writing Back..", true));

        }
Beispiel #31
0
        private void FetchBaseAsync(object argument, BackgroundWorker worker,
                                    System.ComponentModel.DoWorkEventArgs e)
        {
            IDictionary <string, List <Draw> > fetchList =
                (IDictionary <string, List <Draw> >)argument;

            using (ServerSQL dataSQL = new ServerSQL(DatabaseFrom.Database, true))       // чтение
            {
                using (ServerSQL fetchSQL = new ServerSQL(DatabaseFrom.Fetchbase, true)) // чтение
                {
                    if (dataSQL.Connected && fetchSQL.Connected)
                    {
                        int i = 0;
                        foreach (KeyValuePair <string, List <Draw> > item in fetchList)
                        {
                            if (worker.CancellationPending)
                            {
                                e.Cancel = true; break;
                            }
                            string ptname = item.Key;
                            // получение данных
                            IDictionary <string, string> realvals =
                                Data.GetRealValues(ptname, fetchSQL, dataSQL);
                            worker.ReportProgress(i,
                                                  new Tuple <List <Draw>,
                                                             IDictionary <string, string>, string>(
                                                      item.Value, realvals, ptname));
                            i++;
                        }
                    }
                }
            }
        }
        //Connect to COSMIC, preform login and get the Articles for each mutatin that has cosmic details.
        private void _articlesBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            BeginInvoke((MethodInvoker)delegate
            {
                _articleTabControl.TabPages.Clear();
            });
            _articlesBackgroundWorker.ReportProgress(0);
            bool logedIn = _cosmicWebService.loginToCosmic(Properties.Settings.Default.CosmicEmail, Properties.Settings.Default.CosmicPassword, 5);

            if (_cosmicWebService.isLogedIn())
            {
                _articlesBackgroundWorker.ReportProgress(1);
                foreach (Mutation m in _mutationList)
                {
                    if (!m.CosmicName.Equals("-----"))
                    {
                        foreach(int i in m.getCosmicNums())
                        {
                            string tsvStringFromCosmic = _cosmicWebService.getTsvFromCosmic(i);
                            string tabName = m.GeneName + "  " + m.PMutationName + "  COSM"+i;
                            ArticleTabPage p = new ArticleTabPage(tabName, TSVHandler.getArticleListFromTsv(tsvStringFromCosmic));
                            BeginInvoke((MethodInvoker)delegate
                            {
                                _articleTabControl.TabPages.Add(p);
                            });
                        }
                    }
                }
            }
            else
            {
                _articlesBackgroundWorker.ReportProgress(2);
            }
        }
        void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            string fn = (string)e.Argument;
            while (true)
            {
                Process proc = new Process();
                proc.StartInfo.FileName = System.IO.Directory.GetCurrentDirectory() + "\\ffmpeg.exe";
                proc.StartInfo.Arguments = "-i " + fn + " -y " + fn.Substring(0, fn.Length - (fn.Length - fn.LastIndexOf("."))) + "_Audio.mp3";
                proc.StartInfo.RedirectStandardError = true;
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.CreateNoWindow = true;
                proc.Start();
                StreamReader reader = proc.StandardError;

                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    if (worker.CancellationPending == true)
                    {
                        e.Cancel = true;
                        break;
                    }
                    if (line.Contains("No such file or directory"))
                    {
                        error = true;
                        break;
                    }
                    worker.ReportProgress(0, line);
                }
                proc.Close();
                break;
            }
        }
        private void bgwCode_DoWork(object sender, DoWorkEventArgs e)
        {
            System.ComponentModel.BackgroundWorker worker = sender as System.ComponentModel.BackgroundWorker;

            int value = (int)e.Argument;
            e.Result = Treatment((int)e.Argument, (int)e.Argument, worker, e);
        }
        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            // Get the input values.
            FindPrimesInput input = (FindPrimesInput)e.Argument;

            // Start the search for primes and wait.
            int[] primes = MultithreadingWorker.Worker.FindPrimes(input.From, input.To, backgroundWorker);

            if (backgroundWorker.CancellationPending)
            {
                e.Cancel = true;
                return;
            }

            // Paste the list of primes together into one long string.
            StringBuilder sb = new StringBuilder();
            foreach (int prime in primes)
            {
                sb.Append(prime.ToString());
                sb.Append("  ");
            }

            // Return the result.
            e.Result = sb.ToString();
        }
        private void PBarWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            int currentSize = 0;

            // Generate new Sections
            List<Section> sections = Controller.generateSections();

            // Run all sections
            foreach (Section s in sections)
            {
                while (s.canRun())
                {
                    currentSize += s.run();
                    worker.ReportProgress(currentSize);
                    System.Threading.Thread.Sleep(Controller.TIMERTICKSPEED);

                    // Support Work Cancellation
                    if (worker.CancellationPending)
                    {
                        e.Cancel = true;
                        break;
                    }
                }
            }

            // Make sure the bar is full in the end
            worker.ReportProgress(Controller.SIZE);
        }
Beispiel #37
0
		private void copyGroupBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
		{
			Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
			BackgroundWorker backgroundWorker = (BackgroundWorker)sender;

			PushMeshGroupDataToAsynchLists(TraceInfoOpperation.DO_COPY);

			MeshGroup meshGroupToCopy = asynchMeshGroups[SelectedMeshGroupIndex];
			MeshGroup copyMeshGroup = new MeshGroup();
			double meshCount = meshGroupToCopy.Meshes.Count;
			for (int i = 0; i < meshCount; i++)
			{
				Mesh mesh = asynchMeshGroups[SelectedMeshGroupIndex].Meshes[i];
				copyMeshGroup.Meshes.Add(Mesh.Copy(mesh, (double progress0To1, string processingState, out bool continueProcessing) =>
				{
					BackgroundWorker_ProgressChanged(progress0To1, processingState, out continueProcessing);
				}));
			}

			PlatingHelper.FindPositionForGroupAndAddToPlate(copyMeshGroup, SelectedMeshGroupTransform, asynchPlatingDatas, asynchMeshGroups, asynchMeshGroupTransforms);
			PlatingHelper.CreateITraceableForMeshGroup(asynchPlatingDatas, asynchMeshGroups, asynchMeshGroups.Count - 1, null);

			bool continueProcessing2;
			BackgroundWorker_ProgressChanged(.95, "", out continueProcessing2);
		}
 void Bw_DoWork(object sender, DoWorkEventArgs e)
 {
     if (this.backgroundMethod != null)
     {
         this.backgroundMethod();
     }
 }
 /// <summary>
 /// Called when background work begins</summary>
 /// <param name="sender">Sender</param>
 /// <param name="e">Event args</param>
 void BgwDoWork(object sender, DoWorkEventArgs e)
 {
     var bgw = sender as BackgroundWorker;
     var result = new List<TargetInfo>();
     result.AddRange(FindTargets());
     e.Result = result;                                  
 }
Beispiel #40
0
        public void DownloadFeedback(object sender, DoWorkEventArgs e)
        {
            SyncInfo info = (SyncInfo)e.Argument;

            List<string> files = SyncHelper.GetRemoteDirectoryListing(info.RemoteDirectory);
            List<string> localFiles = SyncHelper.GetLocalDirectoryListing(info.LocalDirectory, true);

            // TODO: Set text to increment files downloaded.

            // Iterate through the list of files, download each one if needed, and increment progress.
            for (int i = 0; i < files.Count; i++)
            {
                if (SyncHelper.NeedsFeedbackDownload(files[i], localFiles))
                    SyncHelper.DownloadFile(files[i], info.LocalDirectory, info.RemoteDirectory);

                float progress = (float)(i + 1) / files.Count * 100;
                _worker.ReportProgress((int)progress);
            }

            // TODO: Set text to mention cleanup.

            // Iterate through all local files in the directory, and delete them if they are not present in the remote directory.
            foreach (string s in SyncHelper.GetLocalDirectoryListing(info.LocalDirectory, true))
            {
                if (!files.Contains(s))
                    SyncHelper.DeleteLocalFile(s, info.LocalDirectory);
            }
        }
        private void bw_DoWorkAddSchueler(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            HttpWebRequest req = WebRequest.Create(new Uri(MainWindow.URL + "/api/schueler/")) as HttpWebRequest;
            req.Method = "PUT";

            req.ContentType = "application/json";
            req.Accept = "application/json";
            Schueler toadd = (Schueler)e.Argument;

            JavaScriptSerializer json_serializer = new JavaScriptSerializer();
            String content = json_serializer.Serialize(toadd);

            req.ContentLength = content.Length;
            byte[] data = Encoding.ASCII.GetBytes(content);
            using (Stream stream = req.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

            Console.WriteLine("###################");
            Console.WriteLine(content);
            Console.WriteLine("###################");
            using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse)
            {
                StreamReader reader = new StreamReader(resp.GetResponseStream());
                e.Result = reader.ReadToEnd();
            }
        }
 protected override System.Data.DataSet MakeDataSource(DoWorkEventArgs e)
 {
     if (base.m_Period.DateEndIsNull || base.m_Period.DateBeginIsNull)
     {
         Messages.ShowMessage("Заполните период");
         return null;
     }
     Area area = new Area();
     if (this.groupAdressesView.GetSelectedAddresses().get_Count() != 0)
     {
         area.SaveChanges();
         area.SaveAddresses(this.groupAdressesView.GetSelectedAddresses());
         area.SaveChanges();
     }
     ObjectList<Organization> selectedOrganizations = this.selectOrgs1.SelectedOrganizations;
     ObjectList<ServiceTypeOld> serviceTypes = this.selectServiceTypes1.ServiceTypes;
     System.DateTime fromPeriod = base.m_Period.DateBeginIsNull ? Constants.NullDate : base.m_Period.DateBegin;
     System.DateTime toPeriod = base.m_Period.DateEndIsNull ? Constants.NullDate : base.m_Period.DateEnd;
     if ((fromPeriod == Constants.MinDate) || (toPeriod == Constants.MinDate))
     {
         Messages.ShowMessage("Не заданы даты!");
         return null;
     }
     System.Data.DataSet set = Mappers.SimpleReportMapper.GetJnReportByChargeVacations(area.Id, selectedOrganizations, serviceTypes, fromPeriod, toPeriod);
     set.Tables.get_Item(0).set_TableName("tuning");
     set.Tables.get_Item(1).set_TableName("crit");
     set.Tables.get_Item(2).set_TableName("data");
     area.DeleteWithRelations();
     return set;
 }
Beispiel #43
0
 // Background do
 private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
 {
     // download and save
     QuizManage.GetFromDb((int)numericUpDown1.Value,
         (checkBox1.Checked ? (int)numericUpDown2.Value : -1));
     QuizManage.Save();
 }
 /// <summary>
 /// Evento que surge cuando el Proceso en segundo plano empieza a guardar el banner
 /// </summary>
 /// <param name="sender">Objeto que  envía el evento</param>
 /// <param name="e">Argumentos del evento</param>
 private void backgroundWorker_BotonAceptar_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
 {
     this.iFuncionVentana(this.iBanner);
     if ((this.iFuente != null) && (this.iFuente.GetType() == typeof(FuenteTextoFijo)))
     {
         ControladorFuente.Eliminar(this.iFuente);
     }
 }
Beispiel #45
0
        private void backgroundWorkerChooser_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            var value        = (SelectProductParamItems)e.Argument;
            var dbReader     = new DBReader();
            var productItems = dbReader.ProductGet(value);

            e.Result = productItems;
        }
Beispiel #46
0
        /* 设置报告进度更新
         * backgroundWorker1.WorkerReportsProgress = true;
         * **/

        //线程主体方法
        private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            for (int i = 0; i < 60; i++)
            {
                this.backgroundWorker1.ReportProgress(50, i);
                Thread.Sleep(100);
            }
        }
        private void SendSVHClinicEmail(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            this.m_BackgroundWorker.ReportProgress(1, "Sending SVH Clinic Email: " + DateTime.Now.ToLongTimeString());
            int rowCount = Business.Billing.Model.SVHClinicMailMessage.SendMessage();

            this.m_BackgroundWorker.ReportProgress(1, "SVH Clinic Email Sent with " + rowCount.ToString() + " rows");
            Business.Gateway.BillingGateway.UpdateBillingEODProcess(this.m_PostDate, "SendSVHClinicEmail");
        }
        private void processPackage_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            System.ComponentModel.BackgroundWorker worker = (System.ComponentModel.BackgroundWorker)sender;

            DtsContainer container = (DtsContainer)e.Argument;

            ProcessObject(container, worker, string.Empty);
        }
Beispiel #49
0
 private void ProgressBarBackground_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
 {
     for (int i = 1; i <= 100; i++)
     {
         Thread.Sleep(50);
         ProgressBarBackground.ReportProgress(i);
     }
 }
        // Called when the background worker starts
        private void bw_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            // reset the progress
            bw.ReportProgress(0);

            // Start the syncEngine
            _syncEngine.Run();
        }
Beispiel #51
0
        private void bPayRuleBuildingWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            SetUpXmlApiSettings();
            var jobStatusTracker = Program.Container.Resolve <JobStatusTracker>();
            var job = new GetPayRuleBuildingDataJob(_commandExecutor, _outputFileDictionary, jobStatusTracker, _logger);

            ExecuteJob(job);
        }
 private void bgw_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
 {
     try
     {
         DHuy.CheckAndUpdateFile(FileName, true);
     }
     catch (Exception ex) { }
 }
Beispiel #53
0
 void bw_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
 {
     for (int i = 0; i <= 100; i++)
     {
         this.bw.ReportProgress(i);
         System.Threading.Thread.Sleep(100);
     }
 }
Beispiel #54
0
        private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            var result = Parallel.ForEach(MainClassWithLists.Jewelries.Select(p => p.IdProduct),
                                          ParserConsole_2_.Parser.GetMoreInformation);

            work = false;
            backgroundWorker1.CancelAsync();
        }
Beispiel #55
0
        private void FitsFinderWrkr_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            int numparams = Convert.ToInt32(REG.GetReg("CCDLAB", "FindFilesNumKeyValPairs"));

            string[]  fullfilesinit = (string[])e.Argument;
            ArrayList filelist      = new ArrayList();

            string[] KeyParams    = new string[(numparams)];
            string[] KeyValParams = new string[(numparams)];
            int      match        = 0;

            for (int i = 0; i < numparams; i++)            //get the key/keyvalue pairs
            {
                KeyParams[i]    = (string)REG.GetReg("CCDLAB", String.Concat("FindFilesKey", i));
                KeyValParams[i] = (string)REG.GetReg("CCDLAB", String.Concat("FindFilesKeyVal", i));
            }
            //done filling the param pairs...now need to do the work

            for (int ii = 0; ii < fullfilesinit.Length; ii++)
            {
                if (this.WAITBAR.DialogResult == DialogResult.Cancel)
                {
                    this.DialogResult = DialogResult.Cancel;
                    this.Tag          = DialogResult.Cancel;
                    return;
                }
                FitsFinderWrkr.ReportProgress(ii + 1, filelist.Count);

                FITSImage f1 = new FITSImage(fullfilesinit[ii], null, true, false, false, false);

                match = 0;
                for (int j = 0; j < f1.Header.Length; j++)
                {
                    string key = f1.Header[j].Name;
                    for (int k = 0; k < numparams; k++)
                    {
                        if (KeyParams[k] == key && KeyValParams[k] == f1.Header[j].Value)
                        {
                            match++;
                        }
                    }
                }
                if (match == numparams)
                {
                    filelist.Add(fullfilesinit[ii]);
                }
            }

            string[] matchedfiles = new string[(filelist.Count)];
            for (int h = 0; h < filelist.Count; h++)
            {
                matchedfiles[h] = (string)filelist[h];
            }

            e.Result = matchedfiles;

            this.DialogResult = DialogResult.OK;
        }
Beispiel #56
0
        private void AirAPICheck_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            APIOK = true;


            if (!My.Computer.Network.IsAvailable)
            {
                combnum = -2;
                APIOK   = false;
                goto endtask;
            }

            try
            {
                // 디버깅 항목!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                if (!My.Settings.CustomAPI == null /* TODO Change to default(_) if this is not a reference type */)
                {
                    airData = webget(My.Settings.CustomAPI) + "#CUSTOMAPI#";
                    goto passforDEBUGING;
                }
                // 디버깅 항목!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!


                // 실질적 에어데이터는 여기서 수집함!!! (변화여부를 파악해야 하므로)
                if (!(My.Settings.StationName == null /* TODO Change to default(_) if this is not a reference type */))
                {
                    station = My.Settings.StationName;
                }
                else if (!(My.Settings.LocationPoint_X == null /* TODO Change to default(_) if this is not a reference type */ | My.Settings.LocationPoint_Y == null /* TODO Change to default(_) if this is not a reference type */))
                {
                    if (station == null)
                    {
                        station = getData(getNearStation(My.Settings.LocationPoint_X, My.Settings.LocationPoint_Y), "stationName");
                        My.Settings.StationName = station;
                        My.Settings.Save();
                        My.Settings.Reload();
                    }
                }


                airData = getairinfo(station);

                // MsgBox(airData)

passforDEBUGING:
                ;
                APIupdTime = DateTime.Now.Day.ToString() + "일 " + DateTime.Now.ToString("HH:mm:ss");
                NowChk     = getData(airData, "dataTime");
            }
            catch (Exception ex)
            {
                APIOK   = false;
                combnum = -1;
            }

endtask:
            ;
        }
        void Thread_DoWork(Object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            IPAddress   ipLocalhost = IPAddress.Any;
            TcpListener tcpListener = new TcpListener(ipLocalhost, tcpPort);

            try
            {
                tcpListener.Start(100);
                while (!tcpThread.CancellationPending)
                {
                    while (!tcpListener.Pending() && !tcpThread.CancellationPending)
                    {
                        System.Windows.Forms.Application.DoEvents();
                        Thread.Sleep(10);
                    }

                    //check for cancel pending
                    if (tcpThread.CancellationPending)
                    {
                        break;
                    }

                    //Socket soc = tcpListener.AcceptSocket();

                    //open stream and receive data
                    TcpClient tcpClient = tcpListener.AcceptTcpClient();
                    //Stream netStream = new NetworkStream(soc);
                    NetworkStream netStream       = tcpClient.GetStream();
                    StreamReader  netStreamReader = new StreamReader(netStream);
                    StreamWriter  netStreamWriter = new StreamWriter(netStream);
                    netStreamWriter.AutoFlush = true;
                    string stringData;

                    //report thread progress
                    stringData = netStreamReader.ReadToEnd();
                    tcpThread.ReportProgress(0, stringData);

                    //close stream
                    netStreamReader.Close();
                    netStream.Close();
                    //soc.Close();
                    tcpClient.Close();
                }
            }

            catch (Exception ex)
            {
                throw;
                //handle the exception outside the thread
                //MessageBox.Show("MessageReceiver",ex.Message);
            }
            finally
            {
                tcpThread.ReportProgress(100, e);
                //stop the listener
                tcpListener.Stop();
            }
        }
Beispiel #58
0
 private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
 {
     while (true)
     {
         Thread.Sleep(500);
         data = CardReaderTest.Reader.GetData();
         backgroundWorker1.ReportProgress(0);
     }
 }
Beispiel #59
0
 private void worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
 {
     while (!IsCanceled && seconds != 0)
     {
         SetMessage();
         Thread.Sleep(1000);
         seconds--;
     }
 }
Beispiel #60
0
        private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            Dictionary <string, string> startupStrings = new Dictionary <string, string>();

            startupStrings.Add("NewVersion", CheckNewVersionAvailable());
            startupStrings.Add("SupportExpired", CheckSupportExpiry());

            e.Result = startupStrings;
        }