private void setupResultsBar(int max) { resultsBar.Value = 0; resultsBar.Minimum = 0; resultsBar.Maximum = max; resultsBar.Step = 1; resultsBar.Refresh(); }
/// ///////////////////////////////////////////////////////////////// public void SetValue(int nValue) { m_progressBar.BeginInvoke((MethodInvoker) delegate { try { m_progressBar.Value = m_gestionnaireSegments.GetValeurReelle(nValue); m_progressBar.Refresh(); } catch { } }); }
/// ///////////////////////////////////////////////////////////////// public void SetValue(int nValue) { m_progressBar.BeginInvoke((MethodInvoker) delegate { try { m_progressBar.Value = m_gestionnaireSegments.GetValeurReelle(nValue); Text = m_progressBar.Value.ToString() + "% " + "Traitement en cours"; Refresh(); m_progressBar.Refresh(); } catch { } }); }
public void SetProgressBar(ProgressBar progressBar) { progressBar.Value = 0; int count = 0; foreach(ToDoDetails CurrentToDoDetails in ToDoDetails) { if (CurrentToDoDetails.Done == true) count++; } double score = 100 * count / ToDoDetails.Count; int z; if (score>0) progressBar.Value = (int)score; progressBar.Refresh(); }
internal void writeProgess(ProgressBar progressBar) { progressBar.Refresh(); using (Graphics gr = progressBar.CreateGraphics()) { String s = progressBar.Value.ToString() + "/" + progressBar.Maximum.ToString(); gr.DrawString(s, SystemFonts.DefaultFont, Brushes.Black, new PointF(progressBar.Width / 2 - (gr.MeasureString(s, SystemFonts.DefaultFont).Width / 2.0F), progressBar.Height / 2 - (gr.MeasureString(s, SystemFonts.DefaultFont).Height / 2.0F))); } //progressBar.Refresh(); //progressBar.CreateGraphics().DrawString(progressBar.Value.ToString() + "/" + progressBar.Maximum.ToString(), new Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(progressBar.Width / 2 - 10, progressBar.Height / 2 - 7)); }
private void UpdateProgess(ProgressBar progBar, int percentComplete, Label progDetails, string message) { if (progDetails != null) { progDetails.Text = message; progDetails.Refresh(); } if (progBar != null) { progBar.Value = percentComplete; progBar.Refresh(); } }
/// <summary> /// downloadFile /// </summary> /// <param name="filename">Ten file</param> /// <param name="pro">chon controls ProgressBar</param> /// <returns></returns> public bool downloadFile(string filename, System.Windows.Forms.ProgressBar pro) { downloadedData = new byte[0]; try { //Optional Application.DoEvents(); //Create FTP request //Note: format is ftp://server.com/file.ext FtpWebRequest request = FtpWebRequest.Create("ftp://" + server + "/" + filename) as FtpWebRequest; //Optional Application.DoEvents(); //Get the file size first (for progress bar) request.Method = WebRequestMethods.Ftp.GetFileSize; request.Credentials = new NetworkCredential(user, pass); request.UsePassive = true; request.UseBinary = true; request.KeepAlive = true; //don't close the connection int dataLength = (int)request.GetResponse().ContentLength; //Optional Application.DoEvents(); //Now get the actual data request = FtpWebRequest.Create("ftp://" + server + "/" + filename) as FtpWebRequest; request.Method = WebRequestMethods.Ftp.DownloadFile; request.Credentials = new NetworkCredential(user, pass); request.UsePassive = true; request.UseBinary = true; request.KeepAlive = false; //close the connection when done //Set up progress bar pro.Value = 0; pro.Maximum = dataLength; //lbProgress.Text = "0/" + dataLength.ToString(); //Streams FtpWebResponse response = request.GetResponse() as FtpWebResponse; Stream reader = response.GetResponseStream(); //Download to memory //Note: adjust the streams here to download directly to the hard drive MemoryStream memStream = new MemoryStream(); byte[] buffer = new byte[1024]; //downloads in chuncks while (true) { Application.DoEvents(); //prevent application from crashing //Try to read the data int bytesRead = reader.Read(buffer, 0, buffer.Length); if (bytesRead == 0) { //Nothing was read, finished downloading pro.Value = pro.Maximum; //lbProgress.Text = dataLength.ToString() + "/" + dataLength.ToString(); Application.DoEvents(); break; } else { //Write the downloaded data memStream.Write(buffer, 0, bytesRead); ////Update the progress bar if (pro.Value + bytesRead <= pro.Maximum) { pro.Value += bytesRead; //lbProgress.Text = progressBar1.Value.ToString() + "/" + dataLength.ToString(); pro.Refresh(); Application.DoEvents(); } } } //Convert the downloaded stream to a byte array downloadedData = memStream.ToArray(); //Clean up reader.Close(); memStream.Close(); response.Close(); return(true); } catch (Exception) { MessageBox.Show("There was an error connecting to the FTP Server."); return(false); } //txtData.Text = downloadedData.Length.ToString(); //this.Text = "Download Data through FTP"; user = string.Empty; pass = string.Empty; }
private void exportByList(Hashtable listOfTiles, out int countExported, out int countTotal) { countExported = 0; countTotal = 0; int toExport = listOfTiles.Count; DateTime lastDisplayed = DateTime.Now; DateTime started = DateTime.Now; // save selected tiles. This loop takes time, if BMP conversion is performed. foreach (string tileName in listOfTiles.Keys) { if (m_canceling) { break; } string fileNameJpg = tileName + ".jpg"; string srcPath = Project.GetTerraserverPath(fileNameJpg); int percentComplete = (int)(countTotal * 100.0d / toExport); if (File.Exists(srcPath)) { try { string dstPath = PdaHelper.exportSingleFile(tileName, srcPath, true); if ((DateTime.Now - lastDisplayed).TotalMilliseconds > 500) { string timeLeftStr = ""; if (percentComplete > 1.0d) { TimeSpan elapsed = DateTime.Now - started; TimeSpan projected = new TimeSpan((long)(((double)elapsed.Ticks) / ((double)percentComplete) * 100.0d)); TimeSpan left = projected - elapsed; timeLeftStr = " (" + left.Minutes + " min. " + left.Seconds + " sec. left)"; } this.estimateLabel.Text = "" + countTotal + " of " + toExport + " - " + percentComplete + "%" + timeLeftStr + "\r\n" + dstPath; this.estimateLabel.Refresh(); progressBar1.Value = Math.Min(percentComplete, 100); progressBar1.Refresh(); Application.DoEvents(); lastDisplayed = DateTime.Now; } countExported++; } catch (Exception ee) { #if DEBUG // some files may be broken/missing, not a big deal LibSys.StatusBar.Error("PreloadTiles:export " + ee.Message); #endif } } countTotal++; } this.estimateLabel.Text = "100% complete"; this.estimateLabel.Refresh(); progressBar1.Value = 100; progressBar1.Refresh(); Application.DoEvents(); }
public static void GeneraArchivoTxT(string nomArchi, DataTable dt, char Separador, ref ProgressBar progresBar1, ref Label lblQueHacemos) { string cadena = null; cadena = null; for (int i = 0; i < dt.Rows.Count; i++) { Application.DoEvents(); for (int j = 0; j < dt.Columns.Count; j++) { cadena = cadena + dt.Rows[i][j].ToString().Trim() + Separador; Application.DoEvents(); if ((i % 7) == 0) { progresBar1.Value = i; progresBar1.Refresh(); Application.DoEvents(); } } grabaArchivoTexto(nomArchi, cadena, true); cadena = null; } }
public void GetData() { short x = 0; System.DateTime dDate = new System.DateTime(monthCalendar1.SelectionStart.Year, monthCalendar1.SelectionStart.Month, monthCalendar1.SelectionStart.Day); // cmdGetData.Enabled = false; bIsStillProcessing = true; progressBar1.Visible = true; progressBar1.Refresh(); axMSChart1.ShowLegend = true; axMSChart1.Plot.SeriesCollection[1].LegendText = "Anonymous"; axMSChart1.Plot.SeriesCollection[2].LegendText = "Customer"; progressBar1.Visible = true; progressBar1.Minimum = 0; progressBar1.Maximum = 29; progressBar1.Value = 0; for (x = 1; x < 8; x++) { axMSChart1.Row = x; axMSChart1.RowLabel = dDate.AddDays(x - 1).ToShortDateString(); //+ dDate.Date.ToString(); } ThreadStart s_DayOne = new ThreadStart(this.TDayOne); t_DayOne = new Thread(s_DayOne); t_DayOne.Name = "Thread One"; t_DayOne.Start(); ThreadStart s_DayTwo = new ThreadStart(this.TDayTwo); t_DayTwo = new Thread(s_DayTwo); t_DayTwo.Name = "Thread Two"; t_DayTwo.Start(); ThreadStart s_DayThree = new ThreadStart(this.TDayThree); t_DayThree = new Thread(s_DayThree); t_DayThree.Name = "Thread Three"; t_DayThree.Start(); ThreadStart s_DayFour = new ThreadStart(this.TDayFour); t_DayFour = new Thread(s_DayFour); t_DayFour.Name = "Thread Four"; t_DayFour.Start(); ThreadStart s_DayFive = new ThreadStart(this.TDayFive); t_DayFive = new Thread(s_DayFive); t_DayFive.Name = "Thread Five"; t_DayFive.Start(); ThreadStart s_DaySix = new ThreadStart(this.TDaySix); t_DaySix = new Thread(s_DaySix); t_DaySix.Name = "Thread Six"; t_DaySix.Start(); ThreadStart s_DaySeven = new ThreadStart(this.TDaySeven); t_DaySeven = new Thread(s_DaySeven); t_DaySeven.Name = "Thread Seven"; t_DaySeven.Start(); statusBar1.Text = "Done"; }
void UploadFlash(string filename, string board) { byte[] FLASH = new byte[1]; StreamReader sr = null; try { lbl_status.Text = "Reading Hex File"; this.Refresh(); sr = new StreamReader(filename); FLASH = readIntelHEXv2(sr); sr.Close(); Console.WriteLine("\n\nSize: {0}\n\n", FLASH.Length); } catch (Exception ex) { if (sr != null) { sr.Dispose(); } lbl_status.Text = "Failed read HEX"; MessageBox.Show("Failed to read firmware.hex : " + ex.Message); return; } ArduinoComms port = new ArduinoSTK(); if (board == "1280") { if (FLASH.Length > 126976) { MessageBox.Show("Firmware is to big for a 1280, Please upgrade!!"); return; } //port = new ArduinoSTK(); port.BaudRate = 57600; } else if (board == "2560" || board == "2560-2") { port = new ArduinoSTKv2(); port.BaudRate = 115200; } port.DataBits = 8; port.StopBits = StopBits.One; port.Parity = Parity.None; port.DtrEnable = true; try { port.PortName = MainV2.comportname; port.Open(); flashing = true; if (port.connectAP()) { Console.WriteLine("starting"); lbl_status.Text = "Uploading " + FLASH.Length + " bytes to APM"; progress.Value = 0; this.Refresh(); // this is enough to make ap_var reset //port.upload(new byte[256], 0, 2, 0); port.Progress += new ProgressEventHandler(port_Progress); if (!port.uploadflash(FLASH, 0, FLASH.Length, 0)) { flashing = false; if (port.IsOpen) { port.Close(); } throw new Exception("Upload failed. Lost sync. Try Arduino!!"); } port.Progress -= new ProgressEventHandler(port_Progress); progress.Value = 100; Console.WriteLine("Uploaded"); this.Refresh(); int start = 0; short length = 0x100; byte[] flashverify = new byte[FLASH.Length + 256]; lbl_status.Text = "Verify APM"; progress.Value = 0; this.Refresh(); while (start < FLASH.Length) { progress.Value = (int)((start / (float)FLASH.Length) * 100); progress.Refresh(); port.setaddress(start); Console.WriteLine("Downloading " + length + " at " + start); port.downloadflash(length).CopyTo(flashverify, start); start += length; } progress.Value = 100; for (int s = 0; s < FLASH.Length; s++) { if (FLASH[s] != flashverify[s]) { MessageBox.Show("Upload succeeded, but verify failed: exp " + FLASH[s].ToString("X") + " got " + flashverify[s].ToString("X") + " at " + s); break; } } lbl_status.Text = "Write Done... Waiting (17 sec)"; } else { lbl_status.Text = "Failed upload"; MessageBox.Show("Communication Error - no connection"); } port.Close(); flashing = false; Application.DoEvents(); try { ((SerialPort)port).Open(); } catch { } DateTime startwait = DateTime.Now; while ((DateTime.Now - startwait).TotalSeconds < 17) { try { Console.Write(((SerialPort)port).ReadExisting().Replace("\0", " ")); } catch { } System.Threading.Thread.Sleep(1000); progress.Value = (int)((DateTime.Now - startwait).TotalSeconds / 17 * 100); progress.Refresh(); } try { ((SerialPort)port).Close(); } catch { } progress.Value = 100; lbl_status.Text = "Done"; } catch (Exception ex) { lbl_status.Text = "Failed upload"; MessageBox.Show("Check port settings or Port in use? " + ex.ToString()); port.Close(); } flashing = false; MainV2.givecomport = false; }
public static void recalcMatches(List<Person> playerList, List<Match> matchList, Double startMu, Double startSigma, Double multiplier, UInt16 decay, UInt32 decayValue, DateTime lastDate, ProgressBar progress) { lastDate += new TimeSpan(23, 59, 59); Dictionary<String, Person> playerMap = new Dictionary<string, Person>(); DateTime latestMatch = DateTime.MinValue; int matchTotal = matchList.Count; int counted = 0; if (progress != null) { progress.Value = 0; progress.Refresh(); } foreach (Person person in playerList) { person.Mu = startMu; person.Sigma = startSigma; person.Wins = 0; person.Losses = 0; person.Draws = 0; person.Multiplier = multiplier; person.DecayDays = 0; person.DecayMonths = 0; playerMap.Add(person.Name, person); } foreach (Match match in matchList) { if (progress != null) { counted++; progress.Value = (counted * 100) / matchTotal; progress.PerformStep(); } if (match.Timestamp <= lastDate) { Person p1 = playerMap[match.Player1]; Person p2 = playerMap[match.Player2]; if (decay > 0) { uint i = 0; if (decay < 3) { while (p1.LastMatch.AddDays(i).CompareTo(match.Timestamp) < 0) { i++; } p1.DecayDays += i; i = 0; while (p2.LastMatch.AddDays(i).CompareTo(match.Timestamp) < 0) { i++; } p2.DecayDays += i; } else { i = 0; while (p1.LastMatch.AddMonths((int)i).CompareTo(match.Timestamp) < 0) { i++; } p1.DecayMonths += i; i = 0; while (p2.LastMatch.AddMonths((int)i).CompareTo(match.Timestamp) < 0) { i++; } p2.DecayMonths += i; } switch (decay) { case 1: while (p1.DecayDays > decayValue - 1) { p1.decayScore(startSigma); p1.DecayDays -= decayValue; } while (p2.DecayDays > decayValue - 1) { p2.decayScore(startSigma); p2.DecayDays -= decayValue; } break; case 2: while (p1.DecayDays > (7 * decayValue) - 1) { p1.decayScore(startSigma); p1.DecayDays -= 7 * decayValue; } while (p2.DecayDays > (7 * decayValue) - 1) { p2.decayScore(startSigma); p2.DecayDays -= 7 * decayValue; } break; case 3: while (p1.DecayMonths > decayValue - 1) { p1.decayScore(startSigma); p1.DecayMonths -= decayValue; } while (p2.DecayMonths > decayValue - 1) { p2.decayScore(startSigma); p2.DecayMonths -= decayValue; } break; case 4: while (p1.DecayMonths > (12 * decayValue) - 1) { p1.decayScore(startSigma); p1.DecayMonths -= 12 * decayValue; } while (p2.DecayMonths > (12 * decayValue) - 1) { p2.decayScore(startSigma); p2.DecayMonths -= 12 * decayValue; } break; } } match.P1Score = p1.Score; match.P2Score = p2.Score; Player p1s = new Player(1); Player p2s = new Player(2); Rating p1r = new Rating(p1.Mu, p1.Sigma); Rating p2r = new Rating(p2.Mu, p2.Sigma); Team t1 = new Team(p1s, p1r); Team t2 = new Team(p2s, p2r); IDictionary<Player, Rating> newRatings = null; if (match.Winner == 0) newRatings = TrueSkillCalculator.CalculateNewRatings(GameInfo.DefaultGameInfo, Teams.Concat(t1, t2), 1, 1); else if (match.Winner == 1) newRatings = TrueSkillCalculator.CalculateNewRatings(GameInfo.DefaultGameInfo, Teams.Concat(t1, t2), 1, 2); else if (match.Winner == 2) newRatings = TrueSkillCalculator.CalculateNewRatings(GameInfo.DefaultGameInfo, Teams.Concat(t1, t2), 2, 1); p1.Mu = newRatings[p1s].Mean; p1.Sigma = newRatings[p1s].StandardDeviation; p2.Mu = newRatings[p2s].Mean; p2.Sigma = newRatings[p2s].StandardDeviation; match.P1Score2 = p1.Score; match.P2Score2 = p2.Score; p1.LastMatch = match.Timestamp; p2.LastMatch = match.Timestamp; if (latestMatch < match.Timestamp) latestMatch = match.Timestamp; if (match.Winner == 0) { p1.Draws++; p2.Draws++; } else if (match.Winner == 1) { p1.Wins++; p2.Losses++; } else if (match.Winner == 2) { p1.Losses++; p2.Wins++; } } else break; } foreach (Person p in playerList) { if (decay > 0) { uint i = 0; while (p.LastMatch.AddDays(i).CompareTo(latestMatch) < 0) { i++; } p.DecayDays += i; i = 0; while (p.LastMatch.AddMonths((int)i).CompareTo(latestMatch) < 0) { i++; } p.DecayMonths += i; switch (decay) { case 1: while (p.DecayDays > 0) { p.decayScore(startSigma); p.DecayDays--; } break; case 2: while (p.DecayDays > 6) { p.decayScore(startSigma); p.DecayDays -= 7; } break; case 3: while (p.DecayMonths > 0) { p.decayScore(startSigma); p.DecayMonths--; } break; case 4: while (p.DecayMonths > 11) { p.decayScore(startSigma); p.DecayMonths -= 12; } break; } } } }
public void GetData() { short x = 0; System.DateTime dDate = new System.DateTime(monthCalendar1.SelectionStart.Year, monthCalendar1.SelectionStart.Month, monthCalendar1.SelectionStart.Day); axMSChart1.ColumnCount = 4; axMSChart1.RowCount = 7; // cmdGetData.Enabled = false; bIsStillProcessing = true; progressBar1.Visible = true; progressBar1.Minimum = 0; progressBar1.Maximum = 35; progressBar1.Value = 0; progressBar1.Refresh(); axMSChart1.ShowLegend = true; axMSChart1.Plot.SeriesCollection[1].LegendText = "Specific"; axMSChart1.Plot.SeriesCollection[2].LegendText = "General"; axMSChart1.Plot.SeriesCollection[3].LegendText = "Stop Code"; axMSChart1.Plot.SeriesCollection[4].LegendText = "No Solution"; for (x = 1; x < 8; x++) { axMSChart1.Row = x; axMSChart1.RowLabel = dDate.AddDays(x - 1).ToShortDateString(); //+ dDate.Date.ToString(); } ThreadStart s_DayOne = new ThreadStart(this.TDayOne); t_DayOne = new Thread(s_DayOne); t_DayOne.Name = "Thread One"; ThreadStart s_DayTwo = new ThreadStart(this.TDayTwo); t_DayTwo = new Thread(s_DayTwo); t_DayTwo.Name = "Thread Two"; ThreadStart s_DayThree = new ThreadStart(this.TDayThree); t_DayThree = new Thread(s_DayThree); t_DayThree.Name = "Thread Three"; ThreadStart s_DayFour = new ThreadStart(this.TDayFour); t_DayFour = new Thread(s_DayFour); t_DayFour.Name = "Thread Four"; ThreadStart s_DayFive = new ThreadStart(this.TDayFive); t_DayFive = new Thread(s_DayFive); t_DayFive.Name = "Thread Five"; ThreadStart s_DaySix = new ThreadStart(this.TDaySix); t_DaySix = new Thread(s_DaySix); t_DaySix.Name = "Thread Six"; ThreadStart s_DaySeven = new ThreadStart(this.TDaySeven); t_DaySeven = new Thread(s_DaySeven); t_DaySeven.Name = "Thread Seven"; t_DayOne.Start(); t_DayTwo.Start(); t_DayThree.Start(); t_DayFour.Start(); t_DayFive.Start(); t_DaySix.Start(); t_DaySeven.Start(); }
//解压缩文件 public void UnZipFile(string file) { string serverDir = Application.StartupPath + "\\"; ZipInputStream s = new ZipInputStream(File.OpenRead(serverDir + file)); ZipEntry theEntry; try { ArrayList alDBLog = new ArrayList(); string version = String.Empty; //循环获取压缩实体 while ((theEntry = s.GetNextEntry()) != null) { string directoryName = Path.GetDirectoryName(theEntry.Name); string fileName = Path.GetFileName(theEntry.Name); if (directoryName != String.Empty && !Directory.Exists(serverDir + directoryName)) { Directory.CreateDirectory(directoryName); } if (fileName != String.Empty && fileName.IndexOf("AutoUpdate") < 0 && fileName.IndexOf("SharpZipLib") < 0 && fileName.IndexOf("UpdateObject") < 0 && fileName.IndexOf("Client.log") < 0 && fileName.IndexOf("sqlnet.log") < 0 && fileName.IndexOf("UpdateLog.txt") < 0 && fileName.IndexOf("Log.") < 0 && fileName.IndexOf("_log") < 0) { Tools.UpdateLog updateLog = new Tools.UpdateLog(); updateLog.FileName = fileName; updateLog.UpdateTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"); updateLog.Result = "TRUE"; if (File.Exists(fileName)) { try { File.SetAttributes(fileName, FileAttributes.Normal); //Laws Lu,2006/08/15 无需删除,只需要更改属性 // File.Delete(fileName); } catch (Exception ex) { updateLog.Result = "FALSE"; } FileInfo fi = new FileInfo(fileName); if (fi.LastWriteTime == theEntry.DateTime || fi.Length == 0) { continue; } } Tools.FileLog.FileLogContentOut(fileName); #region 写入文件 if (directoryName != String.Empty) { directoryName = directoryName + "\\"; } FileStream streamWriter = File.Create(directoryName + fileName); try { int size = 2048; byte[] data = new byte[2048]; while (true) { size = s.Read(data, 0, data.Length); //get version if (fileName.IndexOf("Version.") >= 0) { version = System.Text.Encoding.Default.GetString(data).Replace("\0", ""); } if (size > 0) { //写文件 streamWriter.Write(data, 0, size); } else { break; } } Tools.FileLog.FileLogOut(process_ok); } catch (Exception ex) { Tools.FileLog.FileLogOut(process_failure + "\t" + ex.Message); updateLog.Result = "FALSE"; } finally { streamWriter.Close(); } #endregion alDBLog.Add(updateLog); } //进度条累加 if (pgbDownload.Value < 100) { pgbDownload.Value += 1; pgbDownload.Refresh(); } System.Threading.Thread.Sleep(50); } if (alDBLog.Count > 0) { Tools.UpdateLog[] logs = new Tools.UpdateLog[alDBLog.Count]; for (int i = 0; i < alDBLog.Count; i++) { (alDBLog[i] as Tools.UpdateLog).Version = version; logs[i] = alDBLog[i] as Tools.UpdateLog; } Tools.FileLog.DBLogOut(logs); } } catch (Exception ex) { Tools.FileLog.FileLogOut(process_failure + "\t" + ex.Message); } finally { s.Close(); } }
/************************************************************************************* * module: frmWeekly.cs - GetData * * author: Tim Ragain * date: Jan 22, 2002 * * Purpose: Initializes the threads. Appropriately sets the legend of the calendar control, * initializes the progress bar, disables the cmdGetData button. Initializes each * column on the calendar to the appropriated days. New ThreadStart delegate is created * and each delegate is set to the appropriate day from the end date. All threads are then * started. *************************************************************************************/ public void GetData() { System.DateTime dDate = new System.DateTime(monthCalendar1.SelectionStart.Year, monthCalendar1.SelectionStart.Month, monthCalendar1.SelectionStart.Day); RegistryKey regArchive = Registry.CurrentUser.OpenSubKey("software").OpenSubKey("microsoft", true).CreateSubKey("OCATools").CreateSubKey("OCAReports").CreateSubKey("Archive"); RegistryKey regWatson = Registry.CurrentUser.OpenSubKey("software").OpenSubKey("microsoft", true).CreateSubKey("OCATools").CreateSubKey("OCAReports").CreateSubKey("Watson"); bIsStillProcessing = true; try { if (regArchive.GetValue("Loc0").ToString().Length == 0) { frmLocation fLoc = new frmLocation(); fLoc.ShowDialog(this); } } catch { frmLocation fLoc = new frmLocation(); fLoc.ShowDialog(this); } try { if (regWatson.GetValue("Loc0").ToString().Length == 0) { frmLocation fLoc = new frmLocation(); fLoc.ShowDialog(this); } } catch { frmLocation fLoc = new frmLocation(); fLoc.ShowDialog(this); } // cmdGetData.Enabled = false; progressBar1.Visible = true; progressBar1.Minimum = 0; progressBar1.Maximum = 22; progressBar1.Value = 0; progressBar1.Visible = true; progressBar1.Refresh(); axMSChart1.ShowLegend = true; axMSChart1.Plot.SeriesCollection[1].LegendText = "Database"; axMSChart1.Plot.SeriesCollection[2].LegendText = "Watson"; axMSChart1.Plot.SeriesCollection[3].LegendText = "Archive"; ThreadStart s_DayOne = new ThreadStart(this.TDayOne); t_DayOne = new Thread(s_DayOne); t_DayOne.Name = "Thread One"; ThreadStart s_DayTwo = new ThreadStart(this.TDayTwo); t_DayTwo = new Thread(s_DayTwo); t_DayTwo.Name = "Thread Two"; ThreadStart s_DayThree = new ThreadStart(this.TDayThree); t_DayThree = new Thread(s_DayThree); t_DayThree.Name = "Thread Three"; ThreadStart s_DayFour = new ThreadStart(this.TDayFour); t_DayFour = new Thread(s_DayFour); t_DayFour.Name = "Thread Four"; ThreadStart s_DayFive = new ThreadStart(this.TDayFive); t_DayFive = new Thread(s_DayFive); t_DayFive.Name = "Thread Five"; ThreadStart s_DaySix = new ThreadStart(this.TDaySix); t_DaySix = new Thread(s_DaySix); t_DaySix.Name = "Thread Six"; ThreadStart s_DaySeven = new ThreadStart(this.TDaySeven); t_DaySeven = new Thread(s_DaySeven); t_DaySeven.Name = "Thread Seven"; //WaitForSingleObject(tSeven, -1); t_DayOne.Start(); t_DayTwo.Start(); t_DayThree.Start(); t_DayFour.Start(); t_DayFive.Start(); t_DaySix.Start(); t_DaySeven.Start(); statusBar1.Text = "Done"; }
private void ExportButton_Click(object sender, System.EventArgs e) { lblResult.Text = ""; string databaseName = (string)ExportDatabaseList.SelectedItem.ToString(); bool scriptDatabase = chkDatabase.Checked; bool scriptDrop = this.chkDropCommands.Checked; bool scriptTableSchema = this.chkTableSchemas.Checked; bool scriptTableData = this.chkTableData.Checked; bool scriptStoredProcedures = this.chkStoredProcs.Checked; bool scriptComments = this.chkDescriptiveComments.Checked; SqlServer server = new SqlServer(this.txtServer.Text, this.txtUserName.Text, this.txtPassword.Text); server.Connect(); SqlDatabase database = server.Databases[databaseName]; if (database == null) { server.Disconnect(); // Database doesn't exist - break out and go to error page MessageBox.Show("connection error"); return; } SqlTableCollection tables = database.Tables; SqlStoredProcedureCollection sprocs = database.StoredProcedures; StringBuilder scriptResult = new StringBuilder(); scriptResult.EnsureCapacity(400000); scriptResult.Append(String.Format("/* Generated on {0} */\r\n\r\n", DateTime.Now.ToString())); scriptResult.Append("/* Options selected: "); if (scriptDatabase) { scriptResult.Append("database "); } if (scriptDrop) { scriptResult.Append("drop-commands "); } if (scriptTableSchema) { scriptResult.Append("table-schema "); } if (scriptTableData) { scriptResult.Append("table-data "); } if (scriptStoredProcedures) { scriptResult.Append("stored-procedures "); } if (scriptComments) { scriptResult.Append("comments "); } scriptResult.Append(" */\r\n\r\n"); // Script flow: // DROP and CREATE database // use [database] // GO // DROP sprocs // DROP tables // CREATE tables without constraints // Add table data // Add table constraints // CREATE sprocs // Drop and create database if (scriptDatabase) { scriptResult.Append(database.Script( SqlScriptType.Create | (scriptDrop ? SqlScriptType.Drop : 0) | (scriptComments ? SqlScriptType.Comments : 0))); } // Use database scriptResult.Append(String.Format("\r\nuse [{0}]\r\nGO\r\n\r\n", databaseName)); progressBar1.Value = 20; progressBar1.Refresh(); // Drop stored procedures if (scriptStoredProcedures && scriptDrop) { for (int i = 0; i < sprocs.Count; i++) { if (sprocs[i].StoredProcedureType == SqlObjectType.User) { scriptResult.Append(sprocs[i].Script(SqlScriptType.Drop | (scriptComments ? SqlScriptType.Comments : 0))); } } } progressBar1.Value = 30; progressBar1.Refresh(); // Drop tables (this includes schemas and data) if (scriptTableSchema && scriptDrop) { for (int i = 0; i < tables.Count; i++) { if (tables[i].TableType == SqlObjectType.User) { scriptResult.Append(tables[i].ScriptSchema(SqlScriptType.Drop | (scriptComments ? SqlScriptType.Comments : 0))); } } } progressBar1.Value = 40; progressBar1.Refresh(); // Create table schemas if (scriptTableSchema) { // First create tables with no constraints for (int i = 0; i < tables.Count; i++) { if (tables[i].TableType == SqlObjectType.User) { scriptResult.Append(tables[i].ScriptSchema(SqlScriptType.Create | (scriptComments ? SqlScriptType.Comments : 0))); } } } progressBar1.Value = 50; progressBar1.Refresh(); // Create table data if (scriptTableData) { for (int i = 0; i < tables.Count; i++) { if (tables[i].TableType == SqlObjectType.User) { scriptResult.Append(tables[i].ScriptData(scriptComments ? SqlScriptType.Comments : 0)); } } } progressBar1.Value = 60; progressBar1.Refresh(); if (scriptTableSchema) { // Add defaults, primary key, and checks for (int i = 0; i < tables.Count; i++) { if (tables[i].TableType == SqlObjectType.User) { scriptResult.Append(tables[i].ScriptSchema(SqlScriptType.Defaults | SqlScriptType.PrimaryKey | SqlScriptType.Checks | (scriptComments ? SqlScriptType.Comments : 0))); } } // Add foreign keys for (int i = 0; i < tables.Count; i++) { if (tables[i].TableType == SqlObjectType.User) { scriptResult.Append(tables[i].ScriptSchema(SqlScriptType.ForeignKeys | (scriptComments ? SqlScriptType.Comments : 0))); } } progressBar1.Value = 70; progressBar1.Refresh(); // Add unique keys for (int i = 0; i < tables.Count; i++) { if (tables[i].TableType == SqlObjectType.User) { scriptResult.Append(tables[i].ScriptSchema(SqlScriptType.UniqueKeys | (scriptComments ? SqlScriptType.Comments : 0))); } } // Add indexes for (int i = 0; i < tables.Count; i++) { if (tables[i].TableType == SqlObjectType.User) { scriptResult.Append(tables[i].ScriptSchema(SqlScriptType.Indexes | (scriptComments ? SqlScriptType.Comments : 0))); } } } progressBar1.Value = 80; progressBar1.Refresh(); // Create stored procedures if (scriptStoredProcedures) { string tmpResult = String.Empty; for (int i = 0; i < sprocs.Count; i++) { if (sprocs[i].StoredProcedureType == SqlObjectType.User) { tmpResult = sprocs[i].Script(SqlScriptType.Create | (scriptComments ? SqlScriptType.Comments : 0)); scriptResult.Append(tmpResult); tmpResult = ""; } } } server.Disconnect(); progressBar1.Value = 100; progressBar1.Refresh(); scriptResult.Append("/*-----END SCRIPT------*/"); saveFileDialog1.Filter = "Sql files (*.sql)|*.sql|All files (*.*)|*.*"; saveFileDialog1.RestoreDirectory = true; Stream myStream; string theContent = scriptResult.ToString(); if (saveFileDialog1.ShowDialog() == DialogResult.OK) { if ((myStream = saveFileDialog1.OpenFile()) != null) { StreamWriter wText = new StreamWriter(myStream); wText.Write(theContent); wText.Flush(); myStream.Close(); lblResult.Text = "File Saved!"; } } }
private void SetValue4Prg(ProgressBar Prg, int _Value) { try { if (Prg.InvokeRequired) { Prg.Invoke(new SetPrgValue(SetValue4Prg), new object[] {Prg, _Value}); } else { if (Prg.Value + _Value <= Prg.Maximum) Prg.Value += _Value; Prg.Refresh(); } } catch { } }
private void timerUpdateDisplay_Tick(object sender, System.EventArgs e) { double percentCompleted = (double)(_task.TotalCounter) / _task.TotalIterations; double runTime = (double)(_task.TotalTime + DateTime.Now.Ticks) / TimeSpan.TicksPerSecond; string strEstRunTime = "Calculating..."; if (percentCompleted > 0.03) { double estRunTime = runTime / percentCompleted; double estSec = estRunTime % 60; estRunTime = Math.Floor(estRunTime / 60); double estMin = estRunTime % 60; estRunTime = Math.Floor(estRunTime / 60); double estHour = estRunTime; strEstRunTime = String.Format("{0:00}:{1:00}:{2:00}", estHour, estMin, estSec); } double sec = runTime % 60; runTime = Math.Floor(runTime / 60); double min = runTime % 60; runTime = Math.Floor(runTime / 60); double hour = runTime; string strRunTime = String.Format("{0:00}:{1:00}:{2:00.0}", hour, min, sec); //textBoxTime.Text = "Time: " + strRunTime; //textBoxTime.Text = String.Format("Timing: {0:0.0} Seconds", (double)(_task.TotalTime + DateTime.Now.Ticks) / TimeSpan.TicksPerSecond); //textBoxTime.Refresh(); if (_task.TotalCounter < _task.TotalIterations) { // ProgressBar_Total progressBar.Value = _task.TotalCounter; progressBar.Refresh(); // Label_Analyzing textBoxAnalyzing.Text = String.Format("Processing...{0,3:D}/{1,3:D} ({2:#0.00%})", _task.TotalCounter, _task.TotalIterations, percentCompleted); textBoxAnalyzing.Refresh(); // Label_Found textBoxFound.Text = String.Format("Found: {0,3:D}/{1,3:D} ({2:#0.00%})", _task.TotalFound, _task.TotalCounter, ((double)(_task.TotalFound) / _task.TotalCounter)); textBoxFound.Refresh(); // Label_Time textBoxTime.Text = "Time: " + strRunTime + " (Est: " + strEstRunTime + ")"; //textBoxTime.Text = String.Format("Timing: {0:0.0} Seconds", (double)(_task.TotalTime + DateTime.Now.Ticks) / TimeSpan.TicksPerSecond); textBoxTime.Refresh(); } else if (_task.Results[_taskInput.OuterIterations - 1].Total == _taskInput.InnerIterations) { // Stop update timer timerUpdateDisplay.Enabled = false; timerSaveProgress.Enabled = false; // ProgressBar_Total progressBar.Value = _task.TotalCounter; // Label_Analyzing textBoxAnalyzing.Text = "Complete"; // textBoxAnalyzing.Text = _task.Results[_taskInput.OuterIterations - 1].Total.ToString(); // Label_Found textBoxFound.Text = String.Format("Found: {0,3:D}/{1,3:D} ({2:#0.00%}) ({3:#0.0000%})", _task.TotalFound, _task.TotalCounter, ((double)(_task.TotalFound) / _task.TotalCounter), Stdev(_task.Results)); // Label_Time textBoxTime.Text = "Time: " + strRunTime; // Output textBoxOutput.AppendText(textBoxFound.Text + "\r\n"); // build results string string strFillAlgorithm = ""; switch (_mapInput.FillAlgorithm) // 0 = Fixed Count, 1 = Random Count, 2 = Fractal { case 0: strFillAlgorithm = "Fixed Count"; break; case 1: strFillAlgorithm = "Random Count"; break; case 2: strFillAlgorithm = "Fractal H " + _mapInput.H.ToString(); break; } string strDirectionJump = ""; switch (_pathInput.SearchType) // 1 = 4 way, 2 = 8 way { case 1: strDirectionJump += "N4"; break; case 2: strDirectionJump += "N8"; break; } strDirectionJump += "J" + _pathInput.Jump; String report = String.Format(" {0} {1}, {2},{3}x{4},{5},{6},{7}x{8},{9},{10},{11}", DateTime.Now.ToString("d"), DateTime.Now.ToString("T", DateTimeFormatInfo.InvariantInfo), strRunTime, _taskInput.InnerIterations, _taskInput.OuterIterations, strFillAlgorithm, strDirectionJump, _mapInput.Width, _mapInput.Height, _mapInput.FillRate, ((double)(_task.TotalFound) / _task.TotalCounter), Stdev(_task.Results)); foreach (Result result in _task.Results) { report += String.Format(",{0}", (double)(result.Found) / result.Total); } if (!File.Exists("results.csv")) { using (StreamWriter streamWriterResults = File.AppendText("results.csv")) // save results to file { streamWriterResults.WriteLine("DateTime,RunTime,Iterations,FillAlgorithm,Path,MatrixSize,Fill,Found,Stdev"); streamWriterResults.Close(); } } using (StreamWriter streamWriterResults = File.AppendText("results.csv")) // save results to file { streamWriterResults.WriteLine(report); streamWriterResults.Close(); } // reset button text //buttonStart.Text = "Start"; // delete progress file if (File.Exists("progress.txt")) { File.Delete("progress.txt"); } } }
private void Initiate_Torrent_Ranking_Analizes(int tabPage2GoBack, int x, int y, int w, Control parentControl, string preSearch = "") { int nOfWebPagesToCollect = 20; //number of pages to collect from indexer site (below) System.Windows.Forms.Cursor.Current = Cursors.WaitCursor; if (!Parameters.torrentPageAlreadyExtrated) //within same session no need to repopulate listview { string codHtmlRanking = ""; string rankingWeekFileName = Path.Combine(Parameters.myProgPath + "\\Ranking", "Week" + Parameters.weekOfTheYear(DateTime.Today).ToString("00") + ".txt"); string defaultFileName = Path.Combine(Parameters.myProgPath + "\\Ranking", "Ranking" + ".txt"); if (File.Exists(rankingWeekFileName)) //within same week. is gonna use week file. { codHtmlRanking = File.ReadAllText(rankingWeekFileName); } else if (File.Exists(defaultFileName)) { DialogResult dr; dr = MessageBox.Show(@"The Ranking Data is Old. You Can Get New Data or Use the Old one. Do you Want Get New Data From Web? Is going to take Some Time.", "Ranking Data File is Old", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); if (DialogResult.No == dr) { codHtmlRanking = File.ReadAllText(defaultFileName); } else if (DialogResult.Cancel == dr) { return; } } else { DialogResult dr; dr = MessageBox.Show(@"The Torrent Ranking Data is Gotten from the Web and Takes Some Time (about 2 minutes). Want to Continue?", "New Ranking Data is Required", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (DialogResult.No == dr) { return; } } this.progressBar_Ranking = new System.Windows.Forms.ProgressBar(); // // progressBar_Ranking // this.progressBar_Ranking.BackColor = System.Drawing.Color.DarkGray; this.progressBar_Ranking.ForeColor = System.Drawing.Color.Lime; this.progressBar_Ranking.Location = new System.Drawing.Point(x + 4, y - 11); //button_Ranking.Top = buttonOK.Top; //buttonCancel.Left = buttonOK.Right + 5; //buttonCancel.Width = buttonOK.Width; //buttonCancel.Height = buttonOK.Height; this.progressBar_Ranking.Step = 1; this.progressBar_Ranking.Name = "progressBar_Ranking"; this.progressBar_Ranking.Size = new System.Drawing.Size(w - 10, 7); this.progressBar_Ranking.Style = System.Windows.Forms.ProgressBarStyle.Continuous; this.progressBar_Ranking.TabIndex = 22; parentControl.Controls.Add(this.progressBar_Ranking); this.progressBar_Ranking.Maximum = nOfWebPagesToCollect + 5; this.progressBar_Ranking.BringToFront(); this.progressBar_Ranking.Refresh(); Thread.Sleep(200); if (codHtmlRanking == "") //new data has been required { codHtmlRanking += CodHtmlTvTorrentsPageCodeExtractor(0); //maybe turn this in a backgroundworker if (codHtmlRanking == "#off-line#") { MessageBox.Show("Sorry, WebSite or Internet is off-line. Going to Use old Data if available. Try Again Late"); } else { for (int i = 1; i <= nOfWebPagesToCollect; i++) { codHtmlRanking += CodHtmlTvTorrentsPageCodeExtractor(i); //maybe turn this in a backgroundworker progressBar_Ranking.Value = i; progressBar_Ranking.Refresh(); } SaveCodhtmlRanking(codHtmlRanking); } } Torrent_Ranking_Extractor(codHtmlRanking); } Thread.Sleep(250); label_TP7_Ranking.Text = "Torrent Ranking. Top " + listView_TorrentRanking.Items.Count.ToString() + " Shows."; tabControl1.SelectedIndex = 6; listView_TorrentRanking.Refresh(); listView_TorrentRanking.Select(); if (preSearch != "") { //try to find listbox show name in rankinglistview. this.listView_TorrentRanking.EnsureVisible(0); preSearch = Parameters.ClearStr(preSearch).Replace("'", "").Replace(".", " ").Replace("&", "and").Trim(); textBox_TP7_FindInRanking.Text = preSearch; FindInListViewRanking(Parameters.ClearStr(preSearch)); } System.Windows.Forms.Cursor.Current = Cursors.Default; Parameters.torrentRankingGoBack = tabPage2GoBack; }
public string BuscaRetorno(tcIdentificacaoPrestador Prestador, KryptonLabel lblStatus, ProgressBar ProgresStatus) { bool parar = false; Globais glob = new Globais(); string sMensagemErro = ""; int iCountBuscaRet = 0; ProgresStatus.Step = 1; ProgresStatus.Minimum = 0; ProgresStatus.Maximum = 20; ProgresStatus.MarqueeAnimationSpeed = 20; ProgresStatus.Value = 0; try { for (; ; ) { ProgresStatus.PerformStep(); ProgresStatus.Refresh(); lblStatus.Text = "Sistema tentando buscar retorno!!" + Environment.NewLine + "Tentativas: " + iCountBuscaRet.ToString() + " de 21"; lblStatus.Refresh(); string sRetConsulta = BuscaRetornoWebService(Prestador); XmlDocument xmlRet = new XmlDocument(); xmlRet.LoadXml(sRetConsulta); XmlNodeList xNodeList = xmlRet.GetElementsByTagName("ns4:MensagemRetorno"); if (xNodeList.Count > 0) { sMensagemErro = "{3}Lote: " + NumeroLote + "{3}{3}Código: {0}{3}{3}Mensagem: {1}{3}{3}Correção: {2}{3}{3}Protocolo: " + Protocolo; foreach (XmlNode node in xNodeList) { sCodigoRetorno = node["ns4:Codigo"].InnerText; if (sCodigoRetorno.Equals("E4") && iCountBuscaRet <= 20) { iCountBuscaRet++; } else { sMensagemErro = string.Format(sMensagemErro, node["ns4:Codigo"].InnerText, "Esse RPS ainda não se encontra em nossa base de dados.", node["ns4:Correcao"].InnerText, Environment.NewLine); parar = true; } } } else if (xmlRet.GetElementsByTagName("ns3:CompNfse").Count > 0) { this.sCodigoRetorno = ""; sMensagemErro = ""; Globais objGlobais = new Globais(); bool bAlteraDupl = Convert.ToBoolean(objGlobais.LeRegConfig("GravaNumNFseDupl")); for (int i = 0; i < xmlRet.GetElementsByTagName("ns3:CompNfse").Count; i++) { #region Salva Arquivo por arquivo string sPasta = Convert.ToDateTime(xmlRet.GetElementsByTagName("ns4:InfNfse")[i]["ns4:DataEmissao"].InnerText).ToString("MM/yy").Replace("/", ""); //Numero da nota no sefaz + numero da sequencia no sistema string sNomeArquivo = sPasta + (xmlRet.GetElementsByTagName("ns4:InfNfse")[i]["ns4:Numero"].InnerText.PadLeft(6, '0')) + (xmlRet.GetElementsByTagName("ns4:IdentificacaoRps")[i]["ns4:Numero"].InnerText.PadLeft(6, '0')); XmlDocument xmlSaveNfes = new XmlDocument(); xmlSaveNfes.LoadXml(xmlRet.GetElementsByTagName("ns4:Nfse")[i].InnerXml); DirectoryInfo dPastaData = new DirectoryInfo(belStaticPastas.ENVIADOS + "\\Servicos\\" + sPasta); if (!dPastaData.Exists) { dPastaData.Create(); } xmlSaveNfes.Save(belStaticPastas.ENVIADOS + "\\Servicos\\" + sPasta + "\\" + sNomeArquivo + "-nfes.xml"); #endregion objNfseRetorno = new TcInfNfse(); objNfseRetorno.Numero = xmlRet.GetElementsByTagName("ns4:InfNfse")[i]["ns4:Numero"].InnerText; objNfseRetorno.CodigoVerificacao = xmlRet.GetElementsByTagName("ns4:InfNfse")[i]["ns4:CodigoVerificacao"].InnerText; tcIdentificacaoRps objIdentRps = BuscatcIdentificacaoRps(xmlRet.GetElementsByTagName("ns4:IdentificacaoRps")[i]["ns4:Numero"].InnerText.PadLeft(6, '0')); belGerarXML objBelGeraXml = new belGerarXML(); if (belStatic.sNomeEmpresa == "LORENZON") { AlteraDuplicataNumNFse(objIdentRps, xmlRet.GetElementsByTagName("ns4:InfNfse")[i]["ns4:Numero"].InnerText); } if (xmlRet.GetElementsByTagName("ns4:SubstituicaoNfse")[i] != null) { objNfseRetorno.NfseSubstituida = xmlRet.GetElementsByTagName("ns4:SubstituicaoNfse")[i]["ns4:NfseSubstituidora"].InnerText; } objNfseRetorno.IdentificacaoRps = objIdentRps; objListaNfseRetorno.Add(objNfseRetorno); } parar = true; } if (parar) break; } return sMensagemErro; } catch (Exception ex) { throw ex; } }
public static bool migrateTerraserverFiles(Form form, Label progressLabel, ProgressBar progressBar) { bool success = false; try { Cursor.Current = Cursors.WaitCursor; string folderName = GetTerraserverMapsBasePath(); DirectoryInfo di = new DirectoryInfo(folderName); // Hashtable folders = new Hashtable(); FileInfo[] allfiles = di.GetFiles("*.jpg"); double toMigrate = (double)allfiles.Length; progressBar.Minimum = 0; progressBar.Maximum = 100; int progressBarValue = 0; int lastProgressBarValue = progressBar.Value; int count = 0; DateTime started = DateTime.Now; string timeLeftStr = ""; progressLabel.Text = "working..."; foreach(FileInfo fi in allfiles) { string hash = makeTsHash(fi.Name); // if(folders.Contains(hash)) // { // int count = (int)folders[hash]; // count++; // folders[hash] = count; // } // else // { // folders.Add(hash, 1); // } string newFolderName = Path.Combine(folderName, hash); if(!Directory.Exists(newFolderName)) { Directory.CreateDirectory(newFolderName); } string oldPath = Path.Combine(folderName, fi.Name); string newPath = Path.Combine(newFolderName, fi.Name); if(File.Exists(newPath)) { // no need to move, just delete the old location File.Delete(oldPath); } else { File.Move(oldPath, newPath); } // Thread.Sleep(10); count++; double percentComplete = ((double)count) * 100.0d / toMigrate; progressBarValue = (int)Math.Floor(percentComplete); if(count % 50 == 0) { progressLabel.Text = fi.Name + timeLeftStr; progressLabel.Refresh(); Cursor.Current = Cursors.WaitCursor; } if(progressBarValue != lastProgressBarValue) { progressBar.Value = progressBarValue; progressBar.Refresh(); lastProgressBarValue = progressBarValue; TimeSpan elapsed = DateTime.Now - started; TimeSpan projected = new TimeSpan((long)(((double)elapsed.Ticks) / ((double)percentComplete) * 100.0d)); TimeSpan left = projected - elapsed; timeLeftStr = " (" + left.Minutes + " min. " + left.Seconds + " sec. left)"; progressLabel.Text = fi.Name + timeLeftStr; progressLabel.Refresh(); } } progressLabel.Text = "Done"; success = true; // System.Console.WriteLine("Hashtable count: " + folders.Count); // foreach(string key in folders.Keys) // { // System.Console.WriteLine("" + key + " : " + folders[key]); // } } catch (Exception exc) { Project.MessageBox(form, "Error: " + exc.Message); progressLabel.Text = "Error: " + exc.Message; } finally { Cursor.Current = Cursors.Default; } return success; }
public void GetData() { short x = 0; System.DateTime dDate = new System.DateTime(monthCalendar1.SelectionStart.Year, monthCalendar1.SelectionStart.Month, monthCalendar1.SelectionStart.Day); bIsStillProcessing = true; // cmdGetData.Enabled = false; progressBar1.Visible = true; progressBar1.Refresh(); axMSChart1.ShowLegend = true; if (chkDatabaseCount.Checked == true) { axMSChart1.ColumnCount = 3; axMSChart1.Plot.SeriesCollection[1].LegendText = "Auto Uploads"; axMSChart1.Plot.SeriesCollection[2].LegendText = "Manual Uploads"; axMSChart1.Plot.SeriesCollection[3].LegendText = "Null Uploads"; } else { axMSChart1.ColumnCount = 2; axMSChart1.Plot.SeriesCollection[1].LegendText = "Auto Uploads"; axMSChart1.Plot.SeriesCollection[2].LegendText = "Manual Uploads"; } progressBar1.Visible = true; progressBar1.Minimum = 0; progressBar1.Maximum = 29; progressBar1.Value = 0; for (x = 1; x < 8; x++) { axMSChart1.Row = x; axMSChart1.RowLabel = dDate.AddDays(x - 1).ToShortDateString(); //+ dDate.Date.ToString(); } ThreadStart s_DayOne = new ThreadStart(this.TDayOne); t_DayOne = new Thread(s_DayOne); t_DayOne.Name = "Thread Day One"; t_DayOne.Start(); ThreadStart s_DayTwo = new ThreadStart(this.TDayTwo); t_DayTwo = new Thread(s_DayTwo); t_DayTwo.Name = "Thread Two"; t_DayTwo.Start(); ThreadStart s_DayThree = new ThreadStart(this.TDayThree); t_DayThree = new Thread(s_DayThree); t_DayThree.Name = "Thread Three"; t_DayThree.Start(); ThreadStart s_DayFour = new ThreadStart(this.TDayFour); t_DayFour = new Thread(s_DayFour); t_DayFour.Name = "Thread Four"; t_DayFour.Start(); ThreadStart s_DayFive = new ThreadStart(this.TDayFive); t_DayFive = new Thread(s_DayFive); t_DayFive.Name = "Thread Five"; t_DayFive.Start(); ThreadStart s_DaySix = new ThreadStart(this.TDaySix); t_DaySix = new Thread(s_DaySix); t_DaySix.Name = "Thread Six"; t_DaySix.Start(); ThreadStart s_DaySeven = new ThreadStart(this.TDaySeven); t_DaySeven = new Thread(s_DaySeven); t_DaySeven.Name = "Thread Seven"; t_DaySeven.Start(); }
/// <summary> /// Saves a wz file to the disk, AKA repacking. /// </summary> /// <param name="path">Path to the output wz file</param> /// <param name="progressBar">Progressbar, optional. (Set to null if not in use)</param> public void SaveToDisk(string path, ProgressBar progressBar) { WzIv = WzTool.GetIvByMapleVersion(mapleVersion); CreateVersionHash(); wzDir.SetHash(versionHash); if (progressBar != null) { progressBar.PerformStep(); progressBar.Refresh(); } //30% string tempFile = Path.GetFileNameWithoutExtension(path) + ".TEMP"; File.Create(tempFile).Close(); wzDir.GenerateDataFile(tempFile); WzTool.StringCache.Clear(); if (progressBar != null) { progressBar.PerformStep(); progressBar.Refresh(); } //40% uint totalLen = wzDir.GetImgOffsets(wzDir.GetOffsets(Header.FStart + 2)); WzBinaryWriter wzWriter = new WzBinaryWriter(File.Create(path), WzIv); wzWriter.Hash = (uint)versionHash; Header.FSize = totalLen - Header.FStart; for (int i = 0; i < 4; i++) wzWriter.Write((byte)Header.Ident[i]); if (progressBar != null) { progressBar.PerformStep(); progressBar.Refresh(); } //50% wzWriter.Write((long)Header.FSize); wzWriter.Write(Header.FStart); wzWriter.WriteNullTerminatedString(Header.Copyright); if (progressBar != null) { progressBar.PerformStep(); progressBar.Refresh(); } //60% long extraHeaderLength = Header.FStart - wzWriter.BaseStream.Position; if (extraHeaderLength > 0) { wzWriter.Write(new byte[(int)extraHeaderLength]); } if (progressBar != null) { progressBar.PerformStep(); progressBar.Refresh(); } //70% wzWriter.Write(version); wzWriter.Header = Header; wzDir.SaveDirectory(wzWriter); wzWriter.StringCache.Clear(); FileStream fs = File.OpenRead(tempFile); wzDir.SaveImages(wzWriter, fs); fs.Close(); if (progressBar != null) { progressBar.PerformStep(); progressBar.Refresh(); } //80% File.Delete(tempFile); wzWriter.StringCache.Clear(); wzWriter.Close(); if (progressBar != null) { progressBar.PerformStep(); progressBar.Refresh(); } //90% GC.Collect(); GC.WaitForPendingFinalizers(); }
void GetAllSignes() { Form frm = new Form(); ProgressBar pb = new ProgressBar(); frm.Controls.Add(pb); frm.Width = 200; frm.Height = 50; frm.TopMost = true; frm.Show(); frm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; pb.Visible = true; pb.Dock = DockStyle.Fill; pb.Maximum = listBox1b.Items.Count ; pb.Value = 0; int n = 0; foreach (var item in listBox1b.Items) { pb.Value = n; frm.Invalidate(); Application.DoEvents(); pb.Refresh(); Application.DoEvents(); NNH.GetBaseSign((string)item); n++; } frm.Close(); }
private void ProgressBar_Closing(object sender, CancelEventArgs e) { progressBar1.Value = progressBar1.Maximum; progressBar1.Refresh(); Thread.Sleep(200); }
void GetNeuroData() { Form frm = new Form(); ProgressBar pb = new ProgressBar(); frm.Controls.Add(pb); frm.Width = 300; frm.Height = 50; frm.TopMost = true; frm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; pb.Visible = true; pb.Maximum = NNH.Signes.Count; pb.Value = 0; pb.Height = 50; pb.Dock = DockStyle.Fill; pb.Invalidate(); Application.DoEvents(); frm.Show(); int n = 0; for (int i = 0; i < NNH.Signes.Count ; i++) { if (i%5==0) { pb.Value = n; pb.Refresh(); frm.Invalidate(); Application.DoEvents(); } if (NNH.Signes[i].Spectr == null) { NNH.Signes[i].Spectr = (GetDoubAr(SpecA.GetRawSpectrData(NNH.Signes[i].filepath, BassGetSpectrum.Spectrum.FFTSize.FFT1024, 30, 10000))); } var item = NNH.Signes[i]; NNH.GetNeuroData(ref item); NNH.Signes[i].NeuroDays = item.NeuroDays; NNH.Signes[i].NeuroHours = item.NeuroHours; n++; } frm.Close(); }
private void startAnalyzing() { groupAnalyze.Visible = true; Hashtable imgHash = new Hashtable(); Hashtable mcdHash = new Hashtable(); groupInfo.Text = "Map: " + map.Name; lblDimensions.Text = map.MapSize.Rows + "," + map.MapSize.Cols + "," + map.MapSize.Height; lblPckFiles.Text = ""; bool one = true; int totalImages = 0; int totalMcd = 0; if (map is XCMapFile) { foreach (string s in ((XCMapFile)map).Dependencies) { if (one) { one = false; } else { lblPckFiles.Text += ","; } totalImages += GameInfo.ImageInfo[s].GetPckFile().Count; totalMcd += GameInfo.ImageInfo[s].GetMcdFile().Count; lblPckFiles.Text += s; } } pBar.Maximum = map.MapSize.Rows * map.MapSize.Cols * map.MapSize.Height; pBar.Value = 0; for (int h = 0; h < map.MapSize.Height; h++) { for (int r = 0; r < map.MapSize.Rows; r++) { for (int c = 0; c < map.MapSize.Cols; c++) { XCMapTile tile = (XCMapTile)map[r, c, h]; if (!tile.Blank) { if (tile.Ground != null) { count(imgHash, mcdHash, tile.Ground); if (tile.Ground is XCTile) { count(imgHash, mcdHash, ((XCTile)tile.Ground).Dead); } slotsUsed++; } if (tile.West != null) { count(imgHash, mcdHash, tile.West); if (tile.West is XCTile) { count(imgHash, mcdHash, ((XCTile)tile.West).Dead); } slotsUsed++; } if (tile.North != null) { count(imgHash, mcdHash, tile.North); if (tile.North is XCTile) { count(imgHash, mcdHash, ((XCTile)tile.North).Dead); } slotsUsed++; } if (tile.Content != null) { count(imgHash, mcdHash, tile.Content); if (tile.Content is XCTile) { count(imgHash, mcdHash, ((XCTile)tile.Content).Dead); } slotsUsed++; } pBar.Value = (r + 1) * (c + 1) * (h + 1); pBar.Refresh(); } } } } var pct = Math.Round(100 * ((mcdHash.Keys.Count * 1.0) / totalMcd), 2); lblMcd.Text = mcdHash.Keys.Count + "/" + totalMcd + " - " + pct + "%"; pct = Math.Round(100 * ((imgHash.Keys.Count * 1.0) / totalImages), 2); lblPckImages.Text = imgHash.Keys.Count + "/" + totalImages + " - " + pct + "%"; pct = Math.Round(100 * ((slotsUsed * 1.0) / (pBar.Maximum * 4)), 2); lblFilled.Text = slotsUsed + "/" + (pBar.Maximum * 4) + " - " + pct + "%"; groupAnalyze.Visible = false; }
public string BuscaRetorno(tcIdentificacaoPrestador Prestador, KryptonLabel lblStatus, ProgressBar ProgresStatus) { bool parar = false; string sMensagemErro = ""; int iCountBuscaRet = 1; ProgresStatus.Step = 1; ProgresStatus.Minimum = 0; ProgresStatus.Maximum = 20; ProgresStatus.MarqueeAnimationSpeed = 20; ProgresStatus.Value = 0; try { for (; ; ) { ProgresStatus.PerformStep(); ProgresStatus.Refresh(); lblStatus.Text = "O Sistema está tentando buscar Retorno..." + Environment.NewLine + "Tentativa " + iCountBuscaRet.ToString() + " de 21"; lblStatus.Refresh(); string sRetConsulta = BuscaRetornoWebService(Prestador); XmlDocument xmlRet = new XmlDocument(); xmlRet.LoadXml(sRetConsulta); XmlNodeList xNodeList = xmlRet.GetElementsByTagName((Acesso.tipoWsNfse == Acesso.TP_WS_NFSE.GINFES ? "ns4:" : "") + "MensagemRetorno"); if (xNodeList.Count > 0) { sMensagemErro = "{3}Lote: " + NumeroLote + "{3}{3}Código: {0}{3}{3}Mensagem: {1}{3}{3}Correção: {2}{3}{3}Protocolo: " + Protocolo; foreach (XmlNode node in xNodeList) { sCodigoRetorno = node[(Acesso.tipoWsNfse == Acesso.TP_WS_NFSE.GINFES ? "ns4:" : "") + "Codigo"].InnerText; if (sCodigoRetorno.Equals("E4") && iCountBuscaRet <= 20) { iCountBuscaRet++; } else { sMensagemErro = string.Format(sMensagemErro, node[(Acesso.tipoWsNfse == Acesso.TP_WS_NFSE.GINFES ? "ns4:" : "") + "Codigo"].InnerText, "Esse RPS ainda não se encontra em nossa base de dados.", node[(Acesso.tipoWsNfse == Acesso.TP_WS_NFSE.GINFES ? "ns4:" : "") + "Correcao"].InnerText, Environment.NewLine); parar = true; } } } else if (xmlRet.GetElementsByTagName((Acesso.tipoWsNfse == Acesso.TP_WS_NFSE.GINFES ? "ns3:" : "") + "CompNfse").Count > 0) { this.sCodigoRetorno = ""; sMensagemErro = ""; bool bAlteraDupl = Convert.ToBoolean(Acesso.GRAVA_NUM_NF_DUPL); for (int i = 0; i < xmlRet.GetElementsByTagName((Acesso.tipoWsNfse == Acesso.TP_WS_NFSE.GINFES ? "ns3:" : "") + "CompNfse").Count; i++) { #region Salva Arquivo por arquivo string sPasta = Convert.ToDateTime(xmlRet.GetElementsByTagName((Acesso.tipoWsNfse == Acesso.TP_WS_NFSE.GINFES ? "ns4:" : "") + "InfNfse")[i][(Acesso.tipoWsNfse == Acesso.TP_WS_NFSE.GINFES ? "ns4:" : "") + "DataEmissao"].InnerText).ToString("MM/yy").Replace("/", ""); //Numero da nota no sefaz + numero da sequencia no sistema string sNomeArquivo = sPasta + (xmlRet.GetElementsByTagName((Acesso.tipoWsNfse == Acesso.TP_WS_NFSE.GINFES ? "ns4:" : "") + "InfNfse")[i][(Acesso.tipoWsNfse == Acesso.TP_WS_NFSE.GINFES ? "ns4:" : "") + "Numero"].InnerText.PadLeft(6, '0')) + (xmlRet.GetElementsByTagName((Acesso.tipoWsNfse == Acesso.TP_WS_NFSE.GINFES ? "ns4:" : "") + "IdentificacaoRps")[i][(Acesso.tipoWsNfse == Acesso.TP_WS_NFSE.GINFES ? "ns4:" : "") + "Numero"].InnerText.PadLeft(6, '0')); XmlDocument xmlSaveNfes = new XmlDocument(); xmlSaveNfes.LoadXml(xmlRet.GetElementsByTagName((Acesso.tipoWsNfse == Acesso.TP_WS_NFSE.GINFES ? "ns4:" : "") + "Nfse")[i].InnerXml); DirectoryInfo dPastaData = new DirectoryInfo(Pastas.ENVIADOS + "\\Servicos\\" + sPasta); if (!dPastaData.Exists) { dPastaData.Create(); } xmlSaveNfes.Save(Pastas.ENVIADOS + "\\Servicos\\" + sPasta + "\\" + sNomeArquivo + "-nfes.xml"); #endregion objNfseRetorno = new TcInfNfse(); objNfseRetorno.Numero = xmlRet.GetElementsByTagName((Acesso.tipoWsNfse == Acesso.TP_WS_NFSE.GINFES ? "ns4:" : "") + "InfNfse")[i][(Acesso.tipoWsNfse == Acesso.TP_WS_NFSE.GINFES ? "ns4:" : "") + "Numero"].InnerText; objNfseRetorno.CodigoVerificacao = xmlRet.GetElementsByTagName((Acesso.tipoWsNfse == Acesso.TP_WS_NFSE.GINFES ? "ns4:" : "") + "InfNfse")[i][(Acesso.tipoWsNfse == Acesso.TP_WS_NFSE.GINFES ? "ns4:" : "") + "CodigoVerificacao"].InnerText; tcIdentificacaoRps objIdentRps = BuscatcIdentificacaoRps(xmlRet.GetElementsByTagName((Acesso.tipoWsNfse == Acesso.TP_WS_NFSE.GINFES ? "ns4:" : "") + "IdentificacaoRps")[i][(Acesso.tipoWsNfse == Acesso.TP_WS_NFSE.GINFES ? "ns4:" : "") + "Numero"].InnerText.PadLeft(6, '0')); string sNotaFis = xmlRet.GetElementsByTagName((Acesso.tipoWsNfse == Acesso.TP_WS_NFSE.GINFES ? "ns4:" : "") + "InfNfse")[i][(Acesso.tipoWsNfse == Acesso.TP_WS_NFSE.GINFES ? "ns4:" : "") + "Numero"].InnerText; if (Acesso.NM_EMPRESA.Equals("LORENZON")) { AlteraDuplicataNumNFse(objIdentRps, sNotaFis); } if (Acesso.NM_EMPRESA.Equals("FORMINGP")) { daoDuplicata objdaodup = new daoDuplicata(); objdaodup.BuscaVencto(objIdentRps.Nfseq, sNotaFis, objIdentRps.Numero); } if (xmlRet.GetElementsByTagName((Acesso.tipoWsNfse == Acesso.TP_WS_NFSE.GINFES ? "ns4:" : "") + "SubstituicaoNfse")[i] != null) { objNfseRetorno.NfseSubstituida = xmlRet.GetElementsByTagName((Acesso.tipoWsNfse == Acesso.TP_WS_NFSE.GINFES ? "ns4:" : "") + "SubstituicaoNfse")[i][(Acesso.tipoWsNfse == Acesso.TP_WS_NFSE.GINFES ? "ns4:" : "") + "NfseSubstituidora"].InnerText; } objNfseRetorno.IdentificacaoRps = objIdentRps; objListaNfseRetorno.Add(objNfseRetorno); } parar = true; } if (parar) break; } return sMensagemErro; } catch (Exception ex) { throw ex; } }