public static void Begin(int minimum, int maximum) { if (callback != null) { callback.Begin(minimum, maximum); } }
private void DoSomeWork(object status) { errorList = new StringBuilder(); errorMail = false; errorList.AppendLine("Email not sent to:"); callback = status as IProgressCallback; try { callback.Begin(0, nbrTxtInc); SendContributieIncassoAankondiging(); SendInschrijfIncassoAankondiging(); callback.WaitOK(); } catch (System.Threading.ThreadAbortException) { // We want to exit gracefully here (if we're lucky) } catch (System.Threading.ThreadInterruptedException) { // And here, if we can } catch (Exception ex) { GuiRoutines.ExceptionMessageBox(this, ex); } finally { if (callback != null) { callback.End(); } } }
private void BuildAnalyses(object status) { try { IProgressCallback callback = status as IProgressCallback; callback.SetRange(0, CheckedIndices.Count - 1); callback.Begin(); int expectedCount = uCtrlNumberPerCase.Value.Activated ? uCtrlNumberPerCase.Value.Value : -1; PackableBrick packable = cbBoxes.SelectedType as PackableBrick; // build list of analyses for (int i = 0; i < CheckedIndices.Count; ++i) { try { if (callback.IsAborting) { break; } callback.StepTo(i); callback.SetText(string.Format(Resources.ID_EVALUATINGCASE, i + 1, CheckedIndices.Count)); if ((chklbCases.Items[CheckedIndices[i]] as ItemBaseCB).Item is BoxProperties caseProperties) { // build constraint set ConstraintSetBoxCase constraintSet = new ConstraintSetBoxCase(caseProperties); constraintSet.SetAllowedOrientations(uCtrlCaseOrient.AllowedOrientations); if (uCtrlNumberPerCase.Value.Activated) { constraintSet.SetMaxNumber(uCtrlNumberPerCase.Value.Value); } // build solver + get analyses SolverBoxCase solver = new SolverBoxCase(packable, caseProperties); var listAnalyses = solver.BuildAnalyses(constraintSet, false); foreach (var analysis in listAnalyses) { if ((-1 == expectedCount) || (expectedCount == analysis.Solution.ItemCount)) { Analyses.Add(analysis); } } } } catch (Exception) {} } callback.SetText(Resources.ID_SORTINGSOLUTIONS); // sort analysis Analyses.Sort(new AnalysisComparer()); callback.End(); } catch (Exception) {} }
private void outPageExcel(object objs) { ArrayList list = (ArrayList)objs; IProgressCallback callback = list[0] as IProgressCallback; string strFileName = list[1] as string; try { callback.Begin(0, 100); callback.SetText("正在生成{'资源'}的导出文件……"); this.DoOutFile(strFileName); } catch (Exception exception) { PrintException.Print(exception); } finally { callback.End(); } }
public void Downloader(object status) { try { IProgressCallback callback = status as IProgressCallback; callback.Begin(0, requiredDependancies.Count); WebClient web = new WebClient(); for (int i = 0; i < requiredDependancies.Count; i++) { if (!File.Exists("Mods/" + requiredDependancies[i])) { MelonLogger.Log("Downloading " + requiredDependancies[i]); web.DownloadFileTaskAsync("https://raw.githubusercontent.com/KosmicShovel/BTD6-Mods/master/BTD6.py/DLL/" + requiredDependancies[i], "Mods/" + requiredDependancies[i]).GetAwaiter().GetResult(); MelonLogger.Log("Downloaded " + requiredDependancies[i] + "!"); Console.WriteLine(""); } callback.StepTo(i); } callback.End(); MelonLogger.Log("THE WIZARD WILL NOW RESTART SO YOU CAN USE THE SCRIPT MODS!"); } catch (System.FormatException) {} }
private static void OnDoWork(object sender, DoWorkEventArgs e) { AsyncExportingProgressParams exportingParams = (AsyncExportingProgressParams)e.Argument; ExportMultipleDialogModel model = exportingParams.Model; ExportMultipleDialogModel.ExportFormat exportFormat = exportingParams.ExportFormat; string exportPath = exportingParams.ExportPath; IProgressCallback progressCallback = exportingParams.ProgressCallback; try { progressCallback.Begin(model.ConversationCount); model.ExportConversations(exportFormat, exportPath, progressCallback); progressCallback.End(); } catch (OperationCanceledException) { e.Cancel = true; } }
public bool GenerateSortedSolutionList(IProgressCallback callback, out List <ImpositionSolution> solutions) { // get applicable pattern list List <ImpositionPattern> patternList = GetPatternList(); // need to compute orthogonal positions ? bool processOrthogonalImposition = AllowOrthogonalImposition; /*_allowOrthogonalImposition && (_cardboardFormat.Width != _cardboardFormat.Height);*/ // compute number of expected solutions if (null != callback) { callback.Begin(0, patternList.Count * (processOrthogonalImposition ? 4 : 2)); } // instantiate solution list solutions = new List <ImpositionSolution>(); // process pattern list foreach (ImpositionPattern pattern in patternList) { // generate pattern try { pattern.GeneratePattern(InitialEntities, SpaceBetween, ImpositionOffset, false); } catch (Exception ex) { _log.Error(ex.Message); continue; } // default orientation ImpositionSolution solution = GenerateSolution(pattern); if (null != solution && solution.IsValid) { solution.UnitLengthCut = _unitLengthCut; solution.UnitLengthFold = _unitLengthFold; solution.UnitArea = _unitArea; solutions.Add(solution); } // increment progress dialog? if (null != callback) { callback.Increment(solutions.Count); } // orthogonal direction if (processOrthogonalImposition) { // generate pattern try { pattern.GeneratePattern(InitialEntities, SpaceBetween, ImpositionOffset, true); } catch (Exception ex) { _log.Error(ex.Message); continue; } solution = GenerateSolution(pattern); if (null != solution && solution.IsValid) { solution.UnitLengthCut = _unitLengthCut; solution.UnitLengthFold = _unitLengthFold; solution.UnitArea = _unitArea; solutions.Add(solution); } } // increment progress dialog? if (null != callback) { callback.Increment(solutions.Count); } } // generate thumbnails foreach (ImpositionSolution sol in solutions) { sol.GenerateThumbnail(); // increment progress dialog? if (null != callback) { callback.Increment(solutions.Count); } } // sort solution list solutions.Sort(new SolutionComparerFormat()); if (null != callback) { callback.End(); } return(solutions.Count > 0); }
// The heart of GEDmill is here. public void Create() { fLogger.WriteInfo("Website::Create()"); // 1 means the process was aborted, for signalling back to calling thread. 2 means file nError. ThreadError threaderror = new ThreadError(1, "No error"); try { // The value to indicate in the progress bar to show how much of the website creation is complete. int progress = 0; int[] gfstats = fTree.GetRecordStats(); // The maximum value of the progress bar, i.e. when website creation is fully complete. int progressMax = 1 // Site-wide multimedia files + 1 // W3C Sticker + 1 // Background image + 1 // Style sheet + gfstats[(int)GDMRecordType.rtIndividual] + 1 // Individuals Index + gfstats[(int)GDMRecordType.rtSource] + 1 // Front page + 1 // CD ROM (Doesn't matter here that CD ROM autorun might not be included.) + 1; // Scripts (Doesn't matter here that scripts might not be included.) // The paintbox with which to draw the mini tree var paintbox = new Paintbox(GMConfig.Instance); paintbox.SetBackgroundImage(GMConfig.Instance.BackgroundImage); // Object to keep count of number of files created etc. var stats = new Stats(); // Here goes.... // Start the progress indicator. fProgressWindow.Begin(0, progressMax); if (fProgressWindow.IsAborting) { return; } // Copy the images to use in place of non-pic multimedia files. fProgressWindow.SetText("Copying multimedia"); CopyIcons(); if (fProgressWindow.IsAborting) { return; } fProgressWindow.StepTo(++progress); // Copy the W3C sticker file. fProgressWindow.SetText("Copying W3C sticker"); string sW3CFilename = ""; if (GMConfig.Instance.IncludeValiditySticker) { sW3CFilename = CopyW3CSticker(); } if (fProgressWindow.IsAborting) { return; } fProgressWindow.StepTo(++progress); // Create the index creator for use by the individuals records creator. var indiIndexCreator = new CreatorIndexIndividuals(fTree, fProgressWindow, sW3CFilename); // Copy the image for the background of the webpages. fProgressWindow.SetText("Copying background image"); string backgroundImageFilename = CopyBackgroundImage(); if (fProgressWindow.IsAborting) { return; } fProgressWindow.StepTo(++progress); // Create the style sheet fProgressWindow.SetText("Creating style sheet"); string cssFilename = string.Concat(GMConfig.Instance.OutputFolder, "\\", GMConfig.Instance.StylesheetFilename, ".css"); if (GMConfig.Instance.StylesheetFilename.Length > 0 && (!GMConfig.Instance.PreserveStylesheet || !File.Exists(cssFilename))) { var csc = new CreatorStylesheet(fTree, fProgressWindow, sW3CFilename, cssFilename, backgroundImageFilename); csc.Create(); } if (fProgressWindow.IsAborting) { return; } fProgressWindow.StepTo(++progress); // Create the pages for the individual records. fProgressWindow.SetText("Creating individual pages"); var indiList = fTree.GetRecords <GDMIndividualRecord>(); foreach (GDMIndividualRecord ir in indiList) { var ipc = new CreatorRecordIndividual(fTree, fProgressWindow, sW3CFilename, ir, indiIndexCreator, paintbox); if (ipc.Create(stats)) { stats.Individuals++; } if (fProgressWindow.IsAborting) { return; } fProgressWindow.StepTo(++progress); } // Create the index for the individual records pages. fProgressWindow.SetText("Creating individuals index"); indiIndexCreator.Create(); if (fProgressWindow.IsAborting) { return; } fProgressWindow.StepTo(++progress); // Clear list of copied files, so that source images get copied afresh // and so get resized differently to any indi images based on the same file. Creator.ClearCopiedFilesList(); // Create the pages for the source records. fProgressWindow.SetText("Creating source pages"); var sourList = fTree.GetRecords <GDMSourceRecord>(); foreach (GDMSourceRecord sr in sourList) { var spc = new CreatorRecordSource(fTree, fProgressWindow, sW3CFilename, sr); if (spc.Create(stats)) { stats.Sources++; } if (fProgressWindow.IsAborting) { return; } fProgressWindow.StepTo(++progress); } if (fProgressWindow.IsAborting) { return; } // Create the front page fProgressWindow.SetText("Creating front page"); string front_page_filename = string.Concat(GMConfig.Instance.OutputFolder, "\\", GMConfig.Instance.FrontPageFilename, ".", GMConfig.Instance.HtmlExtension); if (GMConfig.Instance.FrontPageFilename.Length > 0 && (!GMConfig.Instance.PreserveFrontPage || !File.Exists(front_page_filename))) { CreatorFrontPage fpc = new CreatorFrontPage(fTree, fProgressWindow, sW3CFilename, stats); fpc.Create(); } fProgressWindow.StepTo(++progress); if (fProgressWindow.IsAborting) { return; } // Copy the CD ROM autorun file fProgressWindow.SetText("Creating CD-ROM files"); if (GMConfig.Instance.CreateCDROMFiles) { CreateCDROMFiles(); } if (fProgressWindow.IsAborting) { return; } fProgressWindow.StepTo(++progress); // Copy the Javascript fProgressWindow.SetText("Creating Javascript file"); // Currently (10Dec08) the only thing that uses javascript is the multiple images feature. if (GMConfig.Instance.AllowMultipleImages) { CreateJavascriptFiles(); } if (fProgressWindow.IsAborting) { return; } fProgressWindow.StepTo(++progress); // Done fLogger.WriteInfo("Website::CreateFinished"); fProgressWindow.SetText("Done"); threaderror.Error = 0; threaderror.Message = ""; } catch (ArgumentException e) { fLogger.WriteError("Caught Argument Exception : ", e); threaderror.Error = 2; // 2 => abnormal abort. threaderror.Message = ""; } catch (IOException e) { fLogger.WriteError("Caught IO Exception : ", e); threaderror.Error = 2; // 2 => abnormal abort. threaderror.Message = ""; } catch (NullReferenceException e) { fLogger.WriteError("Caught NullReference Exception : ", e); threaderror.Error = 2; // 2 => abnormal abort. threaderror.Message = ""; } catch (HTMLException e) { threaderror.Error = 2; // 2 => abnormal abort. threaderror.Message = e.Message; } catch (Exception e) { fLogger.WriteError("Caught Exception : ", e); threaderror.Error = 2; // 2 => abnormal abort. threaderror.Message = ""; } finally { fLogger.WriteInfo("Thread ending..."); if (fProgressWindow != null) { fProgressWindow.End(threaderror); } } }
private void DoSomeWork(object status) { errorList = new StringBuilder(); errorMail = false; string sSource = "MultiMail"; string sLog = "Application"; errorList.AppendLine("Email not sent to:"); IProgressCallback callback = status as IProgressCallback; try { callback.Begin(0, clbLeden.CheckedItems.Count + clbExtraEmail.CheckedItems.Count); SmtpClientExt client = new SmtpClientExt(param.STMPserver, param.STMPport, param.EmailUserId, param.EmailPassword, EmailLogFile, chkLogEmail.Checked, ckbDoNotSendEmail.Checked, callback.SetText); MailMessage message = new MailMessage(); message.Subject = txtSubject.Text; message.From = new MailAddress(param.EmailReturnAdress); message.ReplyToList.Add(param.EmailReturnAdress); message.IsBodyHtml = ckbHtml.Checked; string messid = string.Format("<{0}@{1}>", Guid.NewGuid().ToString(), "wwww.ttvn.nl"); message.Headers.Add("Message-Id", messid); string strBody = string.Empty; if (ckbHtml.Checked) { strBody = string.Format(@"<html><head><meta http-equiv=Content-Type content=""text/html; charset=us-ascii""></head>{0}</html>", htmlTextbox1.Text); } else { strBody = htmlTextbox1.PlainText; } if (txtBijlage1.Text != string.Empty) { //emailer.Attachments.Add(new SmtpAttachment(txtBijlage1.Text)); message.Attachments.Add(new Attachment(txtBijlage1.Text)); } if (txtBijlage2.Text != string.Empty) { //emailer.Attachments.Add(new SmtpAttachment(txtBijlage2.Text)); message.Attachments.Add(new Attachment(txtBijlage2.Text)); } if (txtBijlage3.Text != string.Empty) { //emailer.Attachments.Add(new SmtpAttachment(txtBijlage3.Text)); message.Attachments.Add(new Attachment(txtBijlage3.Text)); } for (int i = 0; i < clbLeden.Items.Count; i++) { if (!clbLeden.GetItemChecked(i)) { continue; } message.To.Clear(); message.To.Add(clbLeden.Items[i].ToString()); message.Body = MailRoutines.ReplaceKeyWords(strBody, ledenSchaduwlijst[i], param); //emailer.To.Clear(); //emailer.To.Add(clbLeden.Items[i].ToString()); //emailer.Body = MailRoutines.ReplaceKeyWords(strBody, ledenSchaduwlijst[i], param); try { //emailer.SendMessage(); client.Send(message); } catch (Exception ex) { try { if (!EventLog.SourceExists("MultiMail")) { EventLog.CreateEventSource(sSource, sLog); } EventLog.WriteEntry(sSource, ex.Message + @"/n" + message.Body, EventLogEntryType.Warning, 001); } catch (Exception ex2) { GuiRoutines.ExceptionMessageBox(this, ex); Console.WriteLine(ex2.ToString()); } errorMail = true; errorList.AppendLine(clbLeden.Items[i].ToString()); } callback.Increment(1); callback.SetText(clbLeden.Items[i].ToString()); System.Threading.Thread.Sleep(50); if (callback.IsAborting) { return; } } for (int i = 0; i < clbExtraEmail.Items.Count; i++) { if (!clbExtraEmail.GetItemChecked(i)) { continue; } message.To.Clear(); message.To.Add(clbExtraEmail.Items[i].ToString()); message.Body = MailRoutines.ReplaceKeyWords(strBody, new tblLid(), param); try { client.Send(message); } catch (Exception ex) { try { if (!EventLog.SourceExists("MultiMail")) { EventLog.CreateEventSource(sSource, sLog); } EventLog.WriteEntry(sSource, ex.Message, EventLogEntryType.Warning, 001); } catch { } errorMail = true; errorList.AppendLine(clbExtraEmail.Items[i].ToString()); } callback.Increment(1); callback.SetText(clbExtraEmail.Items[i].ToString()); System.Threading.Thread.Sleep(50); if (callback.IsAborting) { return; } } callback.WaitOK(); } catch (System.Threading.ThreadAbortException ex) { // We want to exit gracefully here (if we're lucky) try { if (!EventLog.SourceExists("MultiMail")) { EventLog.CreateEventSource(sSource, sLog); } EventLog.WriteEntry(sSource, ex.Message, EventLogEntryType.Warning, 001); } catch { } } catch (System.Threading.ThreadInterruptedException ex) { // And here, if we can try { if (!EventLog.SourceExists("MultiMail")) { EventLog.CreateEventSource(sSource, sLog); } EventLog.WriteEntry(sSource, ex.Message, EventLogEntryType.Warning, 001); } catch { } } catch (Exception ex) { try { if (!EventLog.SourceExists("MultiMail")) { EventLog.CreateEventSource(sSource, sLog); } EventLog.WriteEntry(sSource, ex.Message, EventLogEntryType.Warning, 001); } catch { } GuiRoutines.ExceptionMessageBox(this, ex); } finally { if (callback != null) { callback.End(); } } }
/// <summary> /// The do export database. /// </summary> /// <param name="exportPath"> /// The export path. /// </param> /// <param name="format"> /// The format. /// </param> /// <param name="batchSize"> /// The batch size. /// </param> /// <param name="callback"> /// The callback. /// </param> private void DoExportDatabase(string exportPath, DataFormat format, int batchSize, IProgressCallback callback) { var routes = this.ResultEnvironment.FareDatabase.GetRoutes(true, false, false, false, callback); var journeyBatch = new List<Journey>(); var routesBatch = new List<TravelRoute>(); var jCount = routes.Sum(r => r.Journeys.Count); int stackCount = 0; callback.Begin(0, jCount); callback.Title = string.Format("Processing {0} journeys...", jCount); int routesCount = routes.Count; int lastRoutesIdx = routesCount - 1; for (int i = 0; i < routesCount; i++) { if (callback.IsAborting) { return; } TravelRoute route = routes[i]; callback.Text = string.Format("{0} - {1}", route.Departure, route.Destination); var journeys = route.Journeys; int journeysCount = journeys.Count; int lastJourneyIdx = journeysCount - 1; if (journeysCount > 0) { for (int j = 0; j < journeysCount; j++) { var journey = journeys[j]; journeyBatch.Add(journey); if (journeyBatch.Count >= batchSize || j == lastJourneyIdx) { // Batch is full or this is the last item var expRoute = new TravelRoute(route); // Gather journeys into 1 exported route expRoute.AddJourney(journeyBatch, false); this.ResultEnvironment.FareDatabase.LoadData(journeyBatch, true, AppContext.ProgressCallback); routesBatch.Add(expRoute); stackCount += journeyBatch.Count; journeyBatch.Clear(); } if (stackCount >= batchSize || i == lastRoutesIdx) { if (routesBatch.Count > 0) { this.ResultEnvironment.ArchiveManager.ExportData(routesBatch, exportPath, format, AppContext.ProgressCallback); routesBatch.Clear(); } callback.Increment(stackCount); stackCount = 0; } } } callback.Increment(1); } }
/// <summary> /// Load all the components form the component definition file, nominally components.xml. /// </summary> /// <param name="status">An <see cref="IProgressCallback"/> used for updating the progress dialog.</param> /// <remarks> /// This is run in a worker thread and therefore has no direct access to the UI/user. /// </remarks> private void LoadComponents(object status) { IProgressCallback callback = status as IProgressCallback; // blank the component data components = new ConcurrentDictionary <string, Component>(); XmlDocument xmldoc = new XmlDocument(); bool waitForFile = false; double waitTime = 0; // seconds do { try { using (FileStream componentFileStream = new FileStream(saveFilePath, FileMode.Open, FileAccess.Read)) { xmldoc.Load(componentFileStream); XmlNode xmlnode = xmldoc.DocumentElement; int nodesLoaded = 0; while (xmlnode != null) { // Report.Information("node name = '" + xmlnode.Name + "'"); if (xmlnode.Name == "ROOT") { callback.Begin(0, xmlnode.ChildNodes.Count); xmlnode = xmlnode.FirstChild; } else if (xmlnode.Name == "Component") { ++nodesLoaded; callback.SetText(string.Format("Loading component: {0}", nodesLoaded)); callback.StepTo(nodesLoaded); Component newComponent = new Component(xmlnode); components[newComponent.Name] = newComponent; xmlnode = xmlnode.NextSibling; } else { xmlnode = xmlnode.NextSibling; } // check for user Cancel if (callback.IsAborting) { return; } } } waitForFile = false; callback.Success = true; } catch (System.IO.IOException) { // IOException. Is the file locked? Try waiting. if (waitTime < Global.TotalFileWaitTime) { waitForFile = true; System.Threading.Thread.Sleep(Global.FileWaitRetryTime); waitTime += 0.1; } else { // Give up, maybe something else is wrong? throw; } } catch (System.Threading.ThreadAbortException) { // We want to exit gracefully here (if we're lucky) Report.Error("AllComponents: LoadComponents() - Thread Abort Exception."); } catch (System.Threading.ThreadInterruptedException) { // And here, if we can Report.Error("AllComponents: LoadComponents() - Thread Interrupted Exception."); } catch (Exception e) { Report.Error("Failed to load file: \r\n" + e.Message); } finally { if (callback != null) { callback.End(); } } }while (waitForFile); }
/// <summary> /// 加载缓存 zhangdahang 2013-11-15 /// 算法思路: /// 1、从服务器获得需要更新的表(表名,版本)列表 /// 2、对比本地对应表的版本,决定是否需要更新 /// 3、对需要更新的表,获取其表中的所有记录(ID,版本)列表 /// 4、对比本地其表中的记录和版本,统计需要更新的记录集 /// 5、对需要更新的记录集中的记录进行更新,如有需要,分批更新。 /// </summary> /// <param name="status"></param> public static void LoadCache_Update(object status) { //修复Bug307 #region 准备 float step = 1; String Msg = "系统正在更新..."; IProgressCallback callBack = status as IProgressCallback; if (Yqun.Common.ContextCache.ApplicationContext.Current.ISLocalService) { if (callBack != null) { callBack.End(); } return; } DataTable ServerDataCache = null; DataTable LocalDataCache = null; //栓查版本列,如没有版本列,添加“Stcs_1”列,目前以时间作为记录版本 CompareField(); #endregion callBack.SetText(Msg); callBack.Begin(0, 100); Thread.Sleep(500); //获取服务器表集, try { ServerDataCache = GetServerDataCache(); LocalDataCache = GetLocalDataCache(); } catch (Exception ex) { Msg = string.Format("更新缓存失败,原因:“{0}”,请及时联系管理员!", ex.Message); logger.Error(Msg); if (callBack != null) { callBack.End(); } return; } step = ProgressGo(callBack, step); DataTable updateTable = GetUpdateDateTable(ServerDataCache, LocalDataCache); if (updateTable.Rows.Count == 0) { if (callBack != null) { callBack.End(); } return; } logger.Error("共有" + updateTable.Rows.Count + "表需要更新"); DataSet UpdateDB = new DataSet(); foreach (DataRow cacheRow in updateTable.Rows) { string tableName = cacheRow["tableName"].ToString(); callBack.SetText("分析表:" + tableName + "需要更新的记录"); DataTable ServerTable = GetServerDataTalbe("select ID,Scts_1 from " + tableName); if (LocalDataCache.Select("tableName ='" + tableName + "'").Length == 0) { DataRow newCacheRow = LocalDataCache.NewRow(); newCacheRow.ItemArray = cacheRow.ItemArray; LocalDataCache.Rows.Add(newCacheRow); callBack.SetText("添加新表:" + tableName); UpdateTableData(LocalDataCache.TableName, LocalDataCache); } DataTable LocalTable = GetLocalDataTable("select ID,Scts_1 from " + tableName); DataTable updateRecordTable = GetUpdateDateTable(ServerTable, LocalTable); lock (ProcessInfoList) { if (!ProcessInfoList.ContainsKey(tableName.ToLower().Trim())) { ProcessInfo pi = new ProcessInfo(); pi.CompletedRowsCount = 0; pi.TableRowsCount = updateRecordTable.Rows.Count; ProcessInfoList.Add(tableName.ToLower().Trim(), pi); } } UpdateDB.Tables.Add(updateRecordTable); } //更新 foreach (DataTable table in UpdateDB.Tables) { string tableName = table.TableName; #region 可以更新 if (table.Rows.Count == 0) { DataTable cacheTalbe = GetServerDataTalbe("select * from sys_biz_Cache where tableName='" + tableName + "'"); UpdateTableData("sys_biz_Cache", cacheTalbe); continue; } #endregion callBack.SetText("开始更新,表:" + tableName); string IDStr = ""; int index = 0; Int32 pageSize = GetPageSize(tableName); for (; index < table.Rows.Count; index++) { IDStr += "'" + table.Rows[index]["ID"].ToString() + "',"; if ((index != 0 && index % pageSize == 0) || index == table.Rows.Count - 1) { try { IDStr = IDStr.Substring(IDStr.Length - 1) == "," ? IDStr.Remove(IDStr.Length - 1) : IDStr; string sqlStr = "select * from " + tableName + " where ID in (" + IDStr + ")"; IDStr = ""; object[] parameterArr = new object[] { tableName, sqlStr, callBack, table, ServerDataCache }; //启动一个线程 ,更新本地数据据 System.Threading.Thread process = GetOneThread(); process.Start(parameterArr); } catch (Exception e) { logger.Error(e.ToString()); } } } } bool HasRunningThread = true; while (HasRunningThread) { HasRunningThread = false; lock (RunningThreads) { foreach (Thread t in RunningThreads) { if (t.ThreadState == ThreadState.Running) { HasRunningThread = true; break; } } } Thread.Sleep(50); } logger.Error("更新完成"); callBack.SetText("更新成功!"); callBack.StepTo(100); Thread.Sleep(1000); if (callBack != null) { callBack.End(); } }
/// <summary> /// 加载缓存 寇志凯 2013-10-18 /// </summary> public static void LoadCache(object status) { //修复Bug307 Thread.Sleep(500); int step = 1; String Msg = "系统正在更新..."; IProgressCallback callBack = status as IProgressCallback; if (Yqun.Common.ContextCache.ApplicationContext.Current.ISLocalService) { if (callBack != null) { callBack.End(); } return; } callBack.SetText(Msg); callBack.Begin(0, 100); DataTable DataCache = null; object o = ""; List <CacheHelper> ht = new List <CacheHelper>(); try { DataCache = GetDataCache(); step = ProgressGo(callBack, step); } catch (Exception ex) { Msg = string.Format("更新缓存失败,原因:“{0}”,请及时联系管理员!", ex.Message); logger.Error(Msg); if (callBack != null) { callBack.End(); } return; } CompareField(); step = ProgressGo(callBack, step); Boolean needLoadAgain = true; foreach (DataRow Row in DataCache.Rows) { String TableName = Row["TableName"].ToString(); CacheHelper ch = new CacheHelper(); ch.TableName = TableName; ch.AlreadyIDList = new List <string>(); ch.HasData = true; try { o = CallLocalService("Yqun.BO.LoginBO.dll", "GetMaxSCTS1", new object[] { TableName }); if (o == null || o.ToString() == "") { ch.MaxTime = new DateTime(1900, 1, 1); } else { ch.MaxTime = System.Convert.ToDateTime(o); } } catch (Exception ex) { ch.MaxTime = new DateTime(1900, 1, 1); logger.Error("获取本地最大时间出错:" + ex.Message); } ht.Add(ch); } step = ProgressGo(callBack, step); while (needLoadAgain) { try { List <String> sqls = GetCacheSqls(ht); DataSet ds = GetNewData(sqls); needLoadAgain = ds.Tables.Count > 0; Thread.Sleep(50); foreach (var ch in ht) { ch.HasData = false; } foreach (DataTable dt in ds.Tables) { needLoadAgain = UpdateTableData(dt.TableName, dt); if (!needLoadAgain) { break; } CacheHelper ch = GetCacheHelperByTableName(ht, dt.TableName); if (ch != null) { ch.HasData = true; foreach (DataRow row in dt.Rows) { ch.AlreadyIDList.Add(row["ID"].ToString()); logger.Error(row["ID"].ToString() + "被更新"); } } step = ProgressGo(callBack, step); } } catch (Yqun.Bases.Exceptions.ServiceAccessException sae) { logger.Error("服务端内存溢出,请稍后再试:" + sae.Message); needLoadAgain = false; } catch (Exception ex) { Msg = string.Format("更新数据失败,原因:“{0}”,请及时联系管理员!", ex.Message); logger.Error(Msg); needLoadAgain = false; } } callBack.SetText("更新成功!"); callBack.StepTo(100); Thread.Sleep(2000); if (callBack != null) { callBack.End(); } }
/// <summary> /// The import data. /// </summary> /// <param name="path"> /// The path. /// </param> /// <param name="options"> /// The options. /// </param> /// <param name="callback"> /// The callback. /// </param> /// <returns> /// The <see cref="IList"/>. /// </returns> /// <exception cref="ArgumentException"> /// </exception> public IList<TravelRoute> ImportData(string path, DataOptions options, IProgressCallback callback) { if (string.IsNullOrEmpty(path)) { path = ".\\"; } if (!Directory.Exists(path)) { throw new ArgumentException("Target path does not exist: " + path); } var result = new List<TravelRoute>(); callback.Begin(); callback.Text = "Getting file list..."; string[] fileList = Directory.GetFiles(path, "*"); var acceptedFiles = new List<string>(); foreach (var file in fileList) { string fileExt = Path.GetExtension(file); foreach (var ext in this.AcceptedExtensions) { if (string.Equals(fileExt, ext, StringComparison.OrdinalIgnoreCase)) { acceptedFiles.Add(file); break; } } } callback.Title = string.Format(CultureInfo.InvariantCulture, "Importing {0} files...", acceptedFiles.Count); callback.SetRange(0, acceptedFiles.Count); int stackCount = 0, maxStack = this._config.ProcessBatchSize; long stackSizeBytes = 0, maxStackSizeBytes = 1024 * 1024 * 20; // If data size reaches the limit: Start processing file content var processRoutes = new List<TravelRoute>(); var formatter = new ProtoBufTransfer(this.Logger); var processFiles = new List<string>(); for (int i = 0; i < acceptedFiles.Count; i++) { if (callback.IsAborting) { return result; } string file = acceptedFiles[i]; string fileName = Path.GetFileName(file); string ext = Path.GetExtension(fileName); // Get file extension in order to determine the data type this.Logger.InfoFormat("Importing file [{0}]", fileName); callback.Text = fileName; var fileSize = new FileInfo(file).Length; stackSizeBytes += fileSize; // Handle Binary data if (string.Equals(ext, BIN_EXTENSION, StringComparison.OrdinalIgnoreCase)) { var newRoutes = formatter.FromRaw<List<TravelRoute>>(file); if (newRoutes == null) { var singleRoute = formatter.FromRaw<TravelRoute>(file); if (singleRoute != null && singleRoute.Journeys.Count > 0) { processRoutes.Add(singleRoute); stackCount += singleRoute.Journeys.Count; } } else if (newRoutes.Count > 0) { foreach (var r in newRoutes) { if (r.Journeys.Count > 0) { processRoutes.AddRange(newRoutes); stackCount += r.Journeys.Count; } } } } else { // Handle the old data using the Fare Provider var newRoute = this.FareDataProvider.ReadData(File.ReadAllText(file, Encoding.Default)); if (newRoute != null && newRoute.Journeys.Count > 0) { var existRoute = processRoutes.FirstOrDefault(r => r.IsSameRoute(newRoute)); if (existRoute == null) { processRoutes.Add(newRoute); } else { existRoute.AddJourney(newRoute.Journeys, true); // Merge the journeys into the same Route } foreach (var j in newRoute.Journeys) { foreach (var d in j.Data) { if (d.DataDate.IsUndefined()) { d.DataDate = DateTime.Now; } } } stackCount += newRoute.Journeys.Count; stackSizeBytes += 20 * fileSize; // XML file needs much more resource for processing: Add "padding" to the file size boundary } } processFiles.Add(file); if (stackCount >= maxStack || stackSizeBytes >= maxStackSizeBytes || i == acceptedFiles.Count - 1) { this.FareDatabase.AddData(processRoutes, callback); result.AddRange(processRoutes); if (options.ArchiveDataFiles) { callback.Text = string.Format("Archiving {0} data entries...", processFiles.Count); this.ExportData(processRoutes, this._config.ArchivePath, DataFormat.Binary, callback); foreach (var f in processFiles) { File.Delete(f); } } processRoutes.Clear(); stackCount = 0; stackSizeBytes = 0; } callback.Increment(1); } return result; }