/// <summary> /// 缺省窗口过程 /// </summary> /// <param name="m">消息</param> protected override void DefWndProc(ref Message m) { switch (m.Msg) { case WM_INITIAL: { stop.SetMessage("正在初始化浏览器控件..."); this.Update(); this.MainForm.Update(); ClearWebBrowser(this.webBrowser_info, true); if (this.toolStripButton_monitoring.Checked == true) { StartMonitor(this.comboBox_taskName.Text, this.toolStripButton_monitoring.Checked); } stop.SetMessage(""); } return; } base.DefWndProc(ref m); }
// 检索出盘点库内全部批次号名称 int SearchAllBatchNo( LibraryChannel channel, Stop stop, string strInventoryDbName, out string strError) { strError = ""; this.listView_records.Items.Clear(); // EnableControls(false); stop.OnStop += new StopEventHandler(channel.DoStop); stop.Initial("正在列出全部批次号 ..."); stop.BeginLoop(); try { // 构造检索式 StringBuilder text = new StringBuilder(); text.Append("<target list='" + StringUtil.GetXmlStringSimple(strInventoryDbName + ":" + "批次号") + "'>"); // 当前是否为全局用户 bool bGlobalUser = this._libraryCodeList.Count == 0 || this._libraryCodeList.IndexOf("") != -1; // 全局用户只认列表中 "" 一个值。这样可以检索出全部批次号,包括各个分馆的 if (bGlobalUser == true && this._libraryCodeList.Count != 1) { this._libraryCodeList.Clear(); this._libraryCodeList.Add(""); } int i = 0; foreach (string librarycode in this.LibraryCodeList) { if (i > 0) text.Append("<operator value='OR' />"); text.Append("<item><word>" + StringUtil.GetXmlStringSimple(bGlobalUser ? "" : librarycode + "-") + "</word><match>left</match><relation>=</relation><dataType>string</dataType><maxCount>-1</maxCount></item><lang>zh</lang>"); i++; } if (bGlobalUser == true) { if (i > 0) text.Append("<operator value='OR' />"); // 针对空批次号的检索。空只能被全局用户可见 text.Append("<item><word>" + StringUtil.GetXmlStringSimple("") + "</word><match>exact</match><relation>=</relation><dataType>string</dataType><maxCount>-1</maxCount></item><lang>zh</lang>"); i++; } text.Append("</target>"); #if NO // 构造检索式 string strQueryXml = "<target list='" + StringUtil.GetXmlStringSimple(strInventoryDbName + ":" + "批次号") + "'><item><word>" + StringUtil.GetXmlStringSimple("") + "</word><match>left</match><relation>=</relation><dataType>string</dataType><maxCount>-1</maxCount></item><lang>zh</lang>"; strQueryXml += "<operator value='OR' />"; strQueryXml += "<item><word>" + StringUtil.GetXmlStringSimple("") + "</word><match>exact</match><relation>=</relation><dataType>string</dataType><maxCount>-1</maxCount></item><lang>zh</lang></target>"; #endif long lRet = channel.Search( stop, text.ToString(), "batchno", "keycount", // strOutputStyle out strError); if (lRet == 0) { strError = "not found"; return 0; // not found } if (lRet == -1) return -1; long lHitCount = lRet; long lStart = 0; long lCount = lHitCount; DigitalPlatform.CirculationClient.localhost.Record[] searchresults = null; // 装入浏览格式 for (; ; ) { Application.DoEvents(); // 出让界面控制权 if (stop != null && stop.State != 0) { strError = "用户中断"; return -1; } lRet = channel.GetSearchResult( stop, "batchno", // strResultSetName lStart, lCount, "keycount", "zh", out searchresults, out strError); if (lRet == -1) { strError = "GetSearchResult() error: " + strError; return -1; } if (lRet == 0) { // MessageBox.Show(this, "未命中"); return 0; } // 处理浏览结果 foreach (Record record in searchresults) { if (record.Cols == null) { strError = "请更新应用服务器和数据库内核到最新版本,才能使用列出批次号的功能"; return -1; } // 跳过数字为 0 的事项 if (record.Cols.Length > 0 && record.Cols[0] == "0") continue; ListViewItem item = new ListViewItem(); item.Text = string.IsNullOrEmpty(record.Path) == false ? record.Path : "[空]"; ListViewUtil.ChangeItemText(item, 1, record.Cols[0]); this.listView_records.Items.Add(item); } lStart += searchresults.Length; lCount -= searchresults.Length; stop.SetMessage("共命中 " + lHitCount.ToString() + " 条,已装入 " + lStart.ToString() + " 条"); if (lStart >= lHitCount || lCount <= 0) break; } } finally { stop.EndLoop(); stop.OnStop -= new StopEventHandler(channel.DoStop); stop.Initial(""); // EnableControls(true); } return 1; }
// 打印 private void button_print_Click(object sender, EventArgs e) { string strError = ""; if (Control.ModifierKeys == Keys.Control) { this.m_bShowDialog = true; // 强制出现打印对话框 } else { this.m_bShowDialog = false; } RangeList rl = null; // rl==null表示全部打印 if (String.IsNullOrEmpty(this.textBox_printRange.Text) == false) { try { rl = new RangeList(this.textBox_printRange.Text); } catch (Exception ex) { strError = "打印范围字符串格式错误: " + ex.Message; goto ERROR1; } } int nCopies = 1; try { nCopies = Convert.ToInt32(this.textBox_copies.Text); } catch { strError = "份数值格式错误"; goto ERROR1; } EnableControls(false); stop.OnStop += new StopEventHandler(this.DoStop); stop.Initial("正在打印 ..."); stop.BeginLoop(); this.Update(); Program.MainForm.Update(); int nPrinted = 0; try { this.webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted); this.eventPrintComplete.Reset(); // Debug.Assert(false, ""); for (int c = 0; c < nCopies; c++) { // 打印表格各页 for (int i = 0; i < this.Filenames.Count; i++) { Application.DoEvents(); // 出让界面控制权 if (stop != null) { if (stop.State != 0) { strError = "用户中断"; goto ERROR1; } } if (rl == null || rl.IsInRange(i + 1, false) == true) { // MessageBox.Show(this, "once"); nPrinted++; stop.SetMessage("正在打印第 " + (i + 1).ToString() + " 页..."); this.m_nCurrenPageNo = i; this.LoadPageFile(); // 通过completed事件来驱动打印。 while (true) { Application.DoEvents(); // 出让界面控制权 if (eventPrintComplete.WaitOne(100, true) == true) { break; } } } } } this.webBrowser1.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted); } finally { stop.EndLoop(); stop.OnStop -= new StopEventHandler(this.DoStop); stop.Initial("打印完成。共打印 " + nPrinted.ToString() + "页。"); EnableControls(true); } if (nPrinted == 0) { MessageBox.Show(this, "您所指定的打印页码范围 '" + this.textBox_printRange.Text + "' 没有找到匹配的页。"); } return; ERROR1: MessageBox.Show(this, strError); return; }
// 装入一个日志文件中的若干记录 // parameters: // strStyle 如果包含 accessLog,表示这是需要获取只读日志 // strCacheDir 存储本地缓存文件的目录 // lServerFileSize 服务器端日志文件的尺寸。如果为-1,表示函数内会自动获取 // lSize 进度条所采用的最大尺寸。如果必要,可能会被本函数推动 // return: // -2 此类型的日志尚未启用 // -1 error // 0 正常结束 // 1 用户中断 static int ProcessFile( IWin32Window owner, Stop stop, ProgressEstimate estimate, LibraryChannel channel, string strLogFileName, int nLevel, long lServerFileSize, string strRange, string strStyle, string strCacheDir, object param, Delegate_doRecord procDoRecord, ref long lProgressValue, ref long lSize, out string strError) { strError = ""; int nRet = 0; long lRet = 0; stop.SetMessage("正在装入日志文件 " + strLogFileName + " 中的记录。" + "剩余时间 " + ProgressEstimate.Format(estimate.Estimate(lProgressValue)) + " 已经过时间 " + ProgressEstimate.Format(estimate.delta_passed)); bool bAccessLog = StringUtil.IsInList("accessLog", strStyle); string strXml = ""; long lAttachmentTotalLength = 0; byte[] attachment_data = null; long lFileSize = 0; if (lServerFileSize == -1) { lServerFileSize = 0; string strTempStyle = "level-" + nLevel.ToString(); if (bAccessLog) strTempStyle += ",accessLog"; // 获得服务器端日志文件尺寸 lRet = channel.GetOperLog( stop, strLogFileName, -1, // lIndex, -1, // lHint, strTempStyle, "", // strFilter out strXml, out lServerFileSize, 0, // lAttachmentFragmentStart, 0, // nAttachmentFramengLength, out attachment_data, out lAttachmentTotalLength, out strError); // 2015/11/25 if (lRet == -1) return -1; // 2010/12/13 if (lRet == 0) return 0; if (lServerFileSize == -1) { strError = "日志尚未启用"; return -2; } } Stream stream = null; bool bCacheFileExist = false; bool bRemoveCacheFile = false; // 是否要自动删除未全部完成的本地缓存文件 bool bAutoCache = StringUtil.IsInList("autocache", strStyle); if (bAutoCache == true) { nRet = PrepareCacheFile( strCacheDir, bAccessLog ? strLogFileName + ".a" : strLogFileName, lServerFileSize, out bCacheFileExist, out stream, out strError); if (nRet == -1) return -1; if (bCacheFileExist == false && stream != null) bRemoveCacheFile = true; } try { if (bCacheFileExist == true) lFileSize = stream.Length; else lFileSize = lServerFileSize; // stop.SetProgressRange(0, lTotalSize); if (String.IsNullOrEmpty(strRange) == true) strRange = "0-9999999999"; RangeList rl = new RangeList(strRange); for (int i = 0; i < rl.Count; i++) { RangeItem ri = (RangeItem)rl[i]; OperLogInfo[] records = null; long lStartRecords = 0; long lHint = -1; long lHintNext = -1; for (long lIndex = ri.lStart; lIndex < ri.lStart + ri.lLength; lIndex++) { Application.DoEvents(); if (stop != null) { if (stop.State != 0) { strError = "用户中断1"; goto ERROR1; } } if (lIndex == ri.lStart) lHint = -1; else lHint = lHintNext; if (bCacheFileExist == true) { if (lHint == -1) { // return: // -1 error // 0 成功 // 1 到达文件末尾或者超出 nRet = LocationRecord(stream, lIndex, out strError); if (nRet == -1) return -1; } else { // 根据暗示找到 if (lHint == stream.Length) break; if (lHint > stream.Length) { strError = "lHint参数值不正确"; return -1; } if (stream.Position != lHint) stream.Seek(lHint, SeekOrigin.Begin); } nRet = ReadCachedEnventLog( stream, out strXml, out lAttachmentTotalLength, out strError); if (nRet == -1) return -1; lHintNext = stream.Position; } else { if (records == null || lIndex - ri.lStart >= lStartRecords + records.Length) { int nCount = -1; if (ri.lLength >= Int32.MaxValue) nCount = -1; else nCount = (int)ri.lLength; string strTempStyle = "level-" + nLevel.ToString(); if (bAccessLog) strTempStyle += ",accessLog"; // 获得日志 // return: // -1 error // 0 file not found // 1 succeed // 2 超过范围,本次调用无效 lRet = channel.GetOperLogs( stop, strLogFileName, lIndex, lHint, nCount, strTempStyle, "", // strFilter out records, out strError); if (lRet == -1) { DialogResult result = MessageBox.Show(owner, strError + "\r\n\r\n是否继续处理?", "OperLogForm", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); if (result == DialogResult.No) goto ERROR1; else { // TODO: 是否要在listview中装入一条表示出错的行? lHintNext = -1; continue; } } if (lRet == 0) return 0; if (lRet == 2) break; // records数组表示的起点位置 lStartRecords = lIndex - ri.lStart; } OperLogInfo info = records[lIndex - lStartRecords]; strXml = info.Xml; lHintNext = info.HintNext; lAttachmentTotalLength = info.AttachmentLength; // 写入本地缓存的日志文件 if (stream != null) { try { WriteCachedEnventLog( stream, strXml, lAttachmentTotalLength); } catch (Exception ex) { strError = "写入本地缓存文件的时候出错: " + ex.Message; return -1; } } } #if NO // 2011/12/30 // 日志记录可能动态地增加了,超过了原先为ProgressBar设置的范围 if (lFizeTotalSize < (int)lHintNext) { lFizeTotalSize = lHintNext; stop.SetProgressRange(0, lFizeTotalSize); } #endif if (lHintNext >= 0) { // 校正 if (lProgressValue + lHintNext > lSize) { lSize = lProgressValue + lHintNext; stop.SetProgressRange(0, lSize); estimate.SetRange(0, lSize); } stop.SetProgressValue(lProgressValue + lHintNext); } if (lIndex % 100 == 0) { stop.SetMessage("正在装入日志文件 " + strLogFileName + " 中的记录 " + lIndex.ToString() + " 。" + "剩余时间 " + ProgressEstimate.Format(estimate.Estimate(lProgressValue + lHintNext)) + " 已经过时间 " + ProgressEstimate.Format(estimate.delta_passed)); } // if (procDoRecord != null) { nRet = procDoRecord(strLogFileName, strXml, bCacheFileExist, lHint, lIndex, lAttachmentTotalLength, param, out strError); if (nRet == -1) { DialogResult result = MessageBox.Show(owner, strLogFileName + " : " + lIndex.ToString() + "\r\n" + strError + "\r\n\r\n是否继续处理?", "OperLogForm", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); if (result == DialogResult.No) return -1; } if (nRet == 1) return 1; } } } // 创建本地缓存的日志文件的metadata文件 if (bCacheFileExist == false && stream != null) { nRet = CreateCacheMetadataFile( strCacheDir, bAccessLog ? strLogFileName + ".a" : strLogFileName, lServerFileSize, out strError); if (nRet == -1) goto ERROR1; } bRemoveCacheFile = false; // 不删除 } finally { if (stream != null) stream.Close(); if (bRemoveCacheFile == true) { string strError1 = ""; nRet = DeleteCacheFile( strCacheDir, bAccessLog ? strLogFileName + ".a" : strLogFileName, out strError1); if (nRet == -1) MessageBox.Show(owner, strError1); } } lProgressValue += lFileSize; return 0; ERROR1: return -1; }
// 获得批次号表 // parameters: // strPubType 出版物类型。为 图书/连续出版物/(空) 之一 internal static void GetBatchNoTable(GetKeyCountListEventArgs e, IWin32Window owner, string strPubType, // 出版物类型 string strType, Stop stop, LibraryChannel Channel) { string strError = ""; long lRet = 0; if (e.KeyCounts == null) e.KeyCounts = new List<KeyCount>(); string strName = ""; if (strType == "order") strName = "订购"; else if (strType == "item") strName = "册"; else if (strType == "biblio") strName = "编目"; else throw new Exception("未知的strType '" + strType + "' 值"); // EnableControls(false); stop.OnStop += new StopEventHandler(Channel.DoStop); stop.Initial("正在列出全部" + strName + "批次号 ..."); stop.BeginLoop(); try { int nPerMax = 2000; // 一次检索命中的最大条数限制 string strLang = "zh"; string strDbName = "<all>"; if (strPubType == "图书") strDbName = "<all book>"; else if (strPubType == "连续出版物") strDbName = "<all series>"; else strDbName = "<all>"; if (strType == "order") { lRet = Channel.SearchOrder( stop, strDbName, // "<all>", "", // strBatchNo nPerMax, // -1, "批次号", "left", strLang, "batchno", // strResultSetName "desc", "keycount", // strOutputStyle out strError); } else if (strType == "biblio") { string strQueryXml = ""; lRet = Channel.SearchBiblio( stop, strDbName, // "<all>", // 尽管可以用 this.comboBox_inputBiblioDbName.Text, 以便获得和少数书目库相关的批次号实例,但是容易造成误会:因为数据库名列表刷新后,这里却不会刷新? "", // strBatchNo, nPerMax, // -1, // nPerMax "batchno", "left", strLang, "batchno", // strResultSetName "desc", "keycount", // strOutputStyle "", out strQueryXml, out strError); } else if (strType == "item") { lRet = Channel.SearchItem( stop, strDbName, // "<all>", "", // strBatchNo nPerMax, // -1, "批次号", "left", strLang, "batchno", // strResultSetName "desc", "keycount", // strOutputStyle out strError); } else { Debug.Assert(false, ""); } if (lRet == -1) goto ERROR1; if (lRet == 0) { strError = "没有找到任何" + strName + "批次号检索点"; return; } long lHitCount = lRet; long lStart = 0; long lCount = lHitCount; DigitalPlatform.LibraryClient.localhost.Record[] searchresults = null; // 装入浏览格式 for (; ; ) { Application.DoEvents(); // 出让界面控制权 if (stop != null) { if (stop.State != 0) { strError = "用户中断"; goto ERROR1; } } lRet = Channel.GetSearchResult( stop, "batchno", // strResultSetName lStart, lCount, "keycount", strLang, out searchresults, out strError); if (lRet == -1) { strError = "GetSearchResult() error: " + strError; goto ERROR1; } if (lRet == 0) { // MessageBox.Show(this, "未命中"); return; } // 处理浏览结果 for (int i = 0; i < searchresults.Length; i++) { if (searchresults[i].Cols == null) { strError = "请更新应用服务器和数据库内核到最新版本,才能使用列出" + strName + "批次号的功能"; goto ERROR1; } KeyCount keycount = new KeyCount(); keycount.Key = searchresults[i].Path; keycount.Count = Convert.ToInt32(searchresults[i].Cols[0]); e.KeyCounts.Add(keycount); } lStart += searchresults.Length; lCount -= searchresults.Length; stop.SetMessage("共命中 " + lHitCount.ToString() + " 条,已装入 " + lStart.ToString() + " 条"); if (lStart >= lHitCount || lCount <= 0) break; } } finally { stop.EndLoop(); stop.OnStop -= new StopEventHandler(Channel.DoStop); stop.Initial(""); // EnableControls(true); } return; ERROR1: MessageBox.Show(owner, strError); }
// 获得一条MARC/XML记录 // return: // -1 error 包括not found // 0 found // 1 为诊断记录 public int GetOneRecord( string strStyle, int nTest, string strPathParam, string strParameters, // bool bHilightBrowseLine, out string strSavePath, out string strRecord, out string strXmlFragment, out string strOutStyle, out byte[] baTimestamp, out long lVersion, out DigitalPlatform.Z3950.Record record, out Encoding currrentEncoding, out LoginInfo logininfo, out string strError) { strXmlFragment = ""; strRecord = ""; record = null; strError = ""; currrentEncoding = this.CurrentEncoding; baTimestamp = null; strSavePath = ""; strOutStyle = "marc"; logininfo = new LoginInfo(); lVersion = 0; // 防止重入 if (m_bInSearch == true) { strError = "当前窗口正在被一个未结束的长操作使用,无法获得记录。请稍后再试。"; return(-1); } if (strStyle != "marc" && strStyle != "xml") { strError = "DupForm只支持获取MARC格式记录和xml格式记录,不支持 '" + strStyle + "' 格式的记录"; return(-1); } int nRet = 0; int index = -1; string strPath = ""; string strDirection = ""; nRet = Global.ParsePathParam(strPathParam, out index, out strPath, out strDirection, out strError); if (nRet == -1) { return(-1); } if (index == -1) { strError = "暂时不支持没有 index 的用法"; return(-1); } bool bHilightBrowseLine = StringUtil.IsInList("hilight_browse_line", strParameters); if (index >= this.listView_browse.Items.Count) { strError = "越过结果集尾部"; return(-1); } ListViewItem curItem = this.listView_browse.Items[index]; if (bHilightBrowseLine == true) { // 修改listview中事项的选定状态 for (int i = 0; i < this.listView_browse.SelectedItems.Count; i++) { this.listView_browse.SelectedItems[i].Selected = false; } curItem.Selected = true; curItem.EnsureVisible(); } string strPurePath = curItem.Text; string strServerName = this.LibraryServerName; strPath = strPurePath + "@" + this.LibraryServerName; strSavePath = this.CurrentProtocol + ":" + strPath; // 拉上一个dp2检索窗,好办事 dp2SearchForm dp2_searchform = this.GetDp2SearchForm(); if (dp2_searchform == null) { strError = "没有打开的dp2检索窗,无法GetOneRecordSyntax()"; return(-1); } // 获得server url string strServerUrl = dp2_searchform.GetServerUrl(strServerName); if (strServerUrl == null) { strError = "没有找到服务器名 '" + strServerName + "' 对应的URL"; return(-1); } this.Channel = this.Channels.GetChannel(strServerUrl); stop.OnStop += new StopEventHandler(this.DoStop); stop.Initial("正在初始化浏览器组件 ..."); stop.BeginLoop(); this.Update(); this.MainForm.Update(); try { stop.SetMessage("正在装入书目记录 " + strPath + " ..."); string[] formats = null; formats = new string[1]; formats[0] = "xml"; string[] results = null; long lRet = Channel.GetBiblioInfos( stop, strPurePath, "", formats, out results, out baTimestamp, out strError); if (lRet == 0) { strError = "路径为 '" + strPath + "' 的书目记录没有找到 ..."; goto ERROR1; // not found } if (lRet == -1) { goto ERROR1; } // this.BiblioTimestamp = baTimestamp; if (results == null) { strError = "results == null"; goto ERROR1; } if (results.Length != formats.Length) { strError = "result.Length != formats.Length"; goto ERROR1; } string strXml = results[0]; if (strStyle == "marc") { string strMarcSyntax = ""; string strOutMarcSyntax = ""; // 从数据记录中获得MARC格式 nRet = MarcUtil.Xml2Marc(strXml, true, strMarcSyntax, out strOutMarcSyntax, out strRecord, out strError); if (nRet == -1) { strError = "XML转换到MARC记录时出错: " + strError; goto ERROR1; } // 获得书目以外的其它XML片断 nRet = dp2SearchForm.GetXmlFragment(strXml, out strXmlFragment, out strError); if (nRet == -1) { goto ERROR1; } } else { strRecord = strXml; strOutStyle = strStyle; } } finally { stop.EndLoop(); stop.OnStop -= new StopEventHandler(this.DoStop); stop.Initial(""); } return(0); ERROR1: return(-1); }
// 上传文件到到 dp2lbrary 服务器 // parameters: // timestamp 时间戳。如果为 null,函数会自动根据文件信息得到一个时间戳 // bRetryOverwiteExisting 是否自动在时间戳不一致的情况下覆盖已经存在的服务器文件。== true,表示当发现时间戳不一致的时候,自动用返回的时间戳重试覆盖 // return: // -1 出错 // 0 上传文件成功 int UploadFile( Stop stop, LibraryChannel channel, string strClientFilePath, string strServerFilePath, string strStyle, byte[] timestamp, bool bRetryOverwiteExisting, out string strError) { strError = ""; string strResPath = strServerFilePath; #if NO string strMime = API.MimeTypeFrom(ResObjectDlg.ReadFirst256Bytes(strClientFilePath), ""); #endif string strMime = PathUtil.MimeTypeFrom(strClientFilePath); // 检测文件尺寸 FileInfo fi = new FileInfo(strClientFilePath); if (fi.Exists == false) { strError = "文件 '" + strClientFilePath + "' 不存在..."; return -1; } string[] ranges = null; if (fi.Length == 0) { // 空文件 ranges = new string[1]; ranges[0] = ""; } else { string strRange = ""; strRange = "0-" + (fi.Length - 1).ToString(); // 按照100K作为一个chunk // TODO: 实现滑动窗口,根据速率来决定chunk尺寸 ranges = RangeList.ChunkRange(strRange, channel.UploadResChunkSize // 500 * 1024 ); } if (timestamp == null) timestamp = FileUtil.GetFileTimestamp(strClientFilePath); byte[] output_timestamp = null; // REDOWHOLESAVE: string strWarning = ""; bool bCharRedo = false; // 是否正在击键重做的过程中 TimeSpan old_timeout = channel.Timeout; channel.Timeout = TimeSpan.FromSeconds(10); int nCursorLeft = Console.CursorLeft; int nCursorTop = Console.CursorTop; ProgressEstimate _estimate = new ProgressEstimate(); _estimate.SetRange(0, fi.Length); _estimate.StartEstimate(); string strTotalSize = GetSizeString(fi.Length); try { for (int j = 0; j < ranges.Length; j++) { if (stop != null && stop.State != 0) { strError = "用户中断"; goto ERROR1; } RangeList rl = new RangeList(ranges[j]); long uploaded = ((RangeItem)rl[0]).lStart; string strPercent = ""; if (rl.Count >= 1) { double ratio = (double)uploaded / (double)fi.Length; strPercent = String.Format("{0,3:N}", ratio * (double)100) + "%"; } string strUploadedSize = GetSizeString(uploaded); string strWaiting = ""; if (j == ranges.Length - 1) { strWaiting = " please wait ..."; channel.Timeout = new TimeSpan(0, 40, 0); // 40 分钟 } else if (j > 0) strWaiting = "剩余时间 " + ProgressEstimate.Format(_estimate.Estimate(uploaded)) + " 已经过时间 " + ProgressEstimate.Format(_estimate.delta_passed); #if NO if (stop != null) stop.SetMessage( // strMessagePrefix + "正在上载 " + ranges[j] + "/" + Convert.ToString(fi.Length) + " " + strPercent + " " + strClientFilePath + strWarning + strWaiting); #endif ProgressMessage(nCursorLeft, nCursorTop, "uploading " // + ranges[j] + "/" + Convert.ToString(fi.Length) + " " + strPercent + " " + strUploadedSize + "/" + strTotalSize + " " // + strClientFilePath + strWarning + strWaiting); int nRedoCount = 0; REDO: long lRet = channel.SaveResObject( stop, strResPath, strClientFilePath, strClientFilePath, strMime, ranges[j], // j == ranges.Length - 1 ? true : false, // 最尾一次操作,提醒底层注意设置特殊的WebService API超时时间 timestamp, strStyle, out output_timestamp, out strError); timestamp = output_timestamp; strWarning = ""; if (lRet == -1) { // 如果是第一个 chunk,自动用返回的时间戳重试一次覆盖 if (bRetryOverwiteExisting == true && j == 0 && channel.ErrorCode == DigitalPlatform.LibraryClient.localhost.ErrorCode.TimestampMismatch && nRedoCount == 0) { nRedoCount++; goto REDO; } if (channel.ErrorCode == DigitalPlatform.LibraryClient.localhost.ErrorCode.TimestampMismatch && bCharRedo == true) { bCharRedo = false; goto REDO; } Console.WriteLine("出错: " + strError + "\r\n\r\n是否重试? (Y/N)"); ConsoleKeyInfo info = Console.ReadKey(); if (info.KeyChar == 'y' || info.KeyChar == 'Y') { Console.WriteLine(); nCursorLeft = Console.CursorLeft; nCursorTop = Console.CursorTop + 2; bCharRedo = true; goto REDO; } goto ERROR1; } bCharRedo = false; } } finally { channel.Timeout = old_timeout; ProgressMessage(nCursorLeft, nCursorTop, ""); } return 0; ERROR1: return -1; }
// // return: // -1 error // 0 not found // 1 found /// <summary> /// 根据册条码号,装入册记录和书目记录 /// </summary> /// <param name="bEnableControls">是否在处理过程中禁止界面元素</param> /// <param name="strBarcode">册条码号</param> /// <param name="strError">返回出错信息</param> /// <returns> /// -1 出错 /// 0 没有找到 /// 1 找到 /// </returns> public int LoadRecord( bool bEnableControls, string strBarcode, out string strError) { strError = ""; if (bEnableControls == true) { EnableControls(false); stop.OnStop += new StopEventHandler(this.DoStop); stop.Initial("正在初始化浏览器组件 ..."); stop.BeginLoop(); this.Update(); this.MainForm.Update(); } this.entityEditControl1.Clear(); this.m_webExternalHost_biblio.StopPrevious(); this.webBrowser_biblio.Stop(); Global.ClearHtmlPage(this.webBrowser_biblio, this.MainForm.DataDir); this.textBox_message.Text = ""; stop.SetMessage("正在装入册记录 " + strBarcode + " ..."); try { string strItemText = ""; string strBiblioText = ""; string strItemRecPath = ""; string strBiblioRecPath = ""; byte[] item_timestamp = null; long lRet = Channel.GetItemInfo( stop, strBarcode, "xml", out strItemText, out strItemRecPath, out item_timestamp, "html", out strBiblioText, out strBiblioRecPath, out strError); if (lRet == -1) { goto ERROR1; } if (lRet == 0) { return(0); } if (lRet > 1) { strError = "册条码号 " + strBarcode + " 发现被下列多个册记录所使用: \r\n" + strItemRecPath + "\r\n\r\n这是一个严重错误,请求助于系统管理员尽快排除。"; goto ERROR1; } this.BiblioRecPath = strBiblioRecPath; int nRet = this.entityEditControl1.SetData(strItemText, strItemRecPath, item_timestamp, out strError); if (nRet == -1) { goto ERROR1; } Debug.Assert(this.entityEditControl1.Changed == false, ""); this.entityEditControl1.SetReadOnly("librarian"); #if NO Global.SetHtmlString(this.webBrowser_biblio, strBiblioText, this.MainForm.DataDir, "quickchangeentityform_biblio"); #endif this.m_webExternalHost_biblio.SetHtmlString(strBiblioText, "quickchangeentityform_biblio"); this.textBox_message.Text = "册记录路径: " + strItemRecPath + " ;其从属的种(书目)记录路径: " + strBiblioRecPath; } finally { if (bEnableControls == true) { stop.EndLoop(); stop.OnStop -= new StopEventHandler(this.DoStop); stop.Initial(""); EnableControls(true); } } return(1); ERROR1: strError = "装载册条码号为 " + strBarcode + "的记录发生错误: " + strError; // MessageBox.Show(this, strError); return(-1); }
// 创建读者详情 Excel 文件。这是便于被外部调用的版本,只需要提供读者 XML 记录即可 // return: // -1 出错 // 0 用户中断 // 1 成功 public static int CreateReaderDetailExcelFile(List<string> xmls, Delegate_GetBiblioSummary procGetBiblioSummary, Stop stop, bool bAdvanceXml, bool bLaunchExcel, out string strError) { strError = ""; //int nRet = 0; ExportPatronExcelDialog dlg = new ExportPatronExcelDialog(); MainForm.SetControlFont(dlg, Program.MainForm.Font, false); dlg.UiState = Program.MainForm.AppInfo.GetString( "ReaderSearchForm", "ExportPatronExcelDialog_uiState", ""); Program.MainForm.AppInfo.LinkFormState(dlg, "ReaderSearchForm_ExportPatronExcelDialog_uiState_state"); dlg.ShowDialog(Program.MainForm); Program.MainForm.AppInfo.SetString( "ReaderSearchForm", "ExportPatronExcelDialog_uiState", dlg.UiState); if (dlg.DialogResult == System.Windows.Forms.DialogResult.Cancel) { strError = "放弃操作"; return 0; } string strTimeRange = ""; try { strTimeRange = GetTimeRange(dlg.ChargingHistoryDateRange); } catch (Exception ex) { strError = "日期范围字符串 '" + dlg.ChargingHistoryDateRange + "' 格式不合法: " + ex.Message; return -1; } #if NO // 询问文件名 SaveFileDialog dlg = new SaveFileDialog(); dlg.Title = "请指定要输出的 Excel 文件名"; dlg.CreatePrompt = false; dlg.OverwritePrompt = true; // dlg.FileName = this.ExportExcelFilename; // dlg.InitialDirectory = Environment.CurrentDirectory; dlg.Filter = "Excel 文件 (*.xlsx)|*.xlsx|All files (*.*)|*.*"; dlg.RestoreDirectory = true; if (dlg.ShowDialog() != DialogResult.OK) return 0; #endif XLWorkbook doc = null; try { doc = new XLWorkbook(XLEventTracking.Disabled); File.Delete(dlg.FileName); } catch (Exception ex) { strError = "ReaderSearchForm new XLWorkbook() {0BD1CB34-DF8A-4DDB-B884-8A9CF830D7C7} exception: " + ExceptionUtil.GetAutoText(ex); return -1; } IXLWorksheet sheet = null; sheet = doc.Worksheets.Add("表格"); try { if (stop != null) stop.SetProgressRange(0, xmls.Count); // 每个列的最大字符数 List<int> column_max_chars = new List<int>(); // TODO: 表的标题,创建时间 int nRowIndex = 3; // 空出前两行 //int nColIndex = 1; int nReaderIndex = 0; foreach (string strXml in xmls) { Application.DoEvents(); // 出让界面控制权 if (stop != null && stop.State != 0) return 0; if (string.IsNullOrEmpty(strXml) == true) continue; XmlDocument dom = new XmlDocument(); try { dom.LoadXml(strXml); } catch (Exception ex) { strError = "装载读者记录 XML 到 DOM 时发生错误: " + ex.Message; return -1; } string strBarcode = DomUtil.GetElementText(dom.DocumentElement, "barcode"); // if (dlg.ExportReaderInfo) { OutputReaderInfo(sheet, dom, nReaderIndex, ref nRowIndex, ref column_max_chars); } // 输出在借册表格 if (dlg.ExportBorrowInfo) { OutputBorrows(sheet, dom, procGetBiblioSummary, bAdvanceXml, ref nRowIndex, ref column_max_chars); } // 输出违约金表格 if (dlg.ExportOverdueInfo) { OutputOverdues(sheet, dom, procGetBiblioSummary, ref nRowIndex, ref column_max_chars); } if (dlg.ExportChargingHistory) { LibraryChannel channel = Program.MainForm.GetChannel(); try { ChargingHistoryLoader history_loader = new ChargingHistoryLoader(); history_loader.Channel = channel; history_loader.Stop = stop; history_loader.PatronBarcode = strBarcode; history_loader.TimeRange = strTimeRange; history_loader.Actions = "return,lost"; history_loader.Order = "descending"; CacheableBiblioLoader summary_loader = new CacheableBiblioLoader(); summary_loader.Channel = channel; summary_loader.Stop = stop; summary_loader.Format = "summary"; summary_loader.GetBiblioInfoStyle = GetBiblioInfoStyle.None; // summary_loader.RecPaths = biblio_recpaths; // 输出借阅历史表格 // 可能会抛出异常,例如权限不够 OutputBorrowHistory(sheet, dom, history_loader, // this.MainForm.GetBiblioSummary, summary_loader, ref nRowIndex, ref column_max_chars); } catch (Exception ex) { strError = "输出借阅历史时出现异常: " + ex.Message; return -1; } finally { Program.MainForm.ReturnChannel(channel); } } nRowIndex++; // 读者之间的空行 nReaderIndex++; if (stop != null) stop.SetProgressValue(nReaderIndex); } { if (stop != null) stop.SetMessage("正在调整列宽度 ..."); Application.DoEvents(); // 字符数太多的列不要做 width auto adjust foreach (IXLColumn column in sheet.Columns()) { int MAX_CHARS = 50; // 60 int nIndex = column.FirstCell().Address.ColumnNumber - 1; if (nIndex >= column_max_chars.Count) break; int nChars = column_max_chars[nIndex]; if (nIndex == 1) { column.Width = 10; continue; } if (nIndex == 3) MAX_CHARS = 50; else MAX_CHARS = 24; if (nChars < MAX_CHARS) column.AdjustToContents(); else column.Width = Math.Min(MAX_CHARS, nChars); } } } finally { if (doc != null) { doc.SaveAs(dlg.FileName); doc.Dispose(); } if (bLaunchExcel) { try { System.Diagnostics.Process.Start(dlg.FileName); } catch { } } } return 1; }
// 工作线程每一轮循环的实质性工作 public override void Worker() { int nOldCount = 0; List <ChargingTask> tasks = new List <ChargingTask>(); List <ChargingTask> remove_tasks = new List <ChargingTask>(); if (this.m_lock.TryEnterReadLock(m_nLockTimeout) == false) { throw new LockException("锁定尝试中超时"); } try { nOldCount = this._tasks.Count; foreach (ChargingTask task in this._tasks) { if (task.State == "") { tasks.Add(task); } #if NO if (task.State == "finish" && task.Action == "load_reader_info" && task.ReaderBarcode != this.CurrentReaderBarcode) { remove_tasks.Add(task); } #endif } } finally { this.m_lock.ExitReadLock(); } if (tasks.Count > 0) { stop.OnStop += new StopEventHandler(this.DoStop); stop.Initial("进行一轮任务处理..."); stop.BeginLoop(); try { foreach (ChargingTask task in tasks) { if (this.Stopped == true) { this.Container.SetColorList(); // 促使“任务已经暂停”显示出来 return; } if (stop != null && stop.State != 0) { this.Stopped = true; this.Container.SetColorList(); // 促使“任务已经暂停”显示出来 return; } // bool bStop = false; // 执行任务 if (task.Action == "load_reader_info") { LoadReaderInfo(task); } else if (task.Action == "borrow" || task.Action == "renew" || task.Action == "verify_renew") { Borrow(task); } else if (task.Action == "return" || task.Action == "verify_return" || task.Action == "lost" || task.Action == "verify_lost" || task.Action == "inventory" || task.Action == "read" || task.Action == "boxing") { Return(task); } stop.SetMessage(""); } } finally { stop.EndLoop(); stop.OnStop -= new StopEventHandler(this.DoStop); stop.Initial(""); } } //bool bChanged = false; if (remove_tasks.Count > 0) { if (this.m_lock.TryEnterWriteLock(m_nLockTimeout) == false) { throw new LockException("锁定尝试中超时"); } try { //if (this._tasks.Count != nOldCount) // bChanged = true; foreach (ChargingTask task in remove_tasks) { RemoveTask(task, false); } } finally { this.m_lock.ExitWriteLock(); } } /* * if (bChanged == true) * this.Activate(); * */ }
// 根据读者证条码号,装入读者记录 // parameters: // edit 读者编辑控件。可以==null // webbHtml 用于显示HTML的WebBrowser控件。可以==null // webbXml 用于显示XML的WebBrowser控件。可以==null // return: // 0 cancelled internal int LoadRecord(ref string strBarcode, ReaderEditControl edit, WebExternalHost external_html, // WebBrowser webbHtml, WebBrowser webbXml) { string strError = ""; int nRet = 0; if (edit != null && edit.Changed == true) { // 警告尚未保存 DialogResult result = MessageBox.Show(this, "当前有信息被修改后尚未保存。若此时装载新内容,现有未保存信息将丢失。\r\n\r\n确实要根据证条码号重新装载内容? ", "ActivateForm", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (result != DialogResult.Yes) { return(0); // cancelled } } stop.OnStop += new StopEventHandler(this.DoStop); stop.Initial("正在初始化浏览器组件 ..."); stop.BeginLoop(); this.Update(); this.MainForm.Update(); EnableControls(false); if (edit != null) { edit.Clear(); } #if NO if (webbHtml != null) { Global.ClearHtmlPage(webbHtml, this.MainForm.DataDir); } #endif if (external_html != null) { external_html.ClearHtmlPage(); } if (webbXml != null) { Global.ClearHtmlPage(webbXml, this.MainForm.DataDir); } try { byte[] baTimestamp = null; string strRecPath = ""; int nRedoCount = 0; REDO: stop.SetMessage("正在装入读者记录 " + strBarcode + " ..."); string[] results = null; long lRet = Channel.GetReaderInfo( stop, strBarcode, "xml,html", out results, out strRecPath, out baTimestamp, out strError); if (lRet == -1) { goto ERROR1; } if (lRet == 0) { goto ERROR1; } if (lRet > 1) { // 如果重试后依然发生重复 if (nRedoCount > 0) { strError = "条码 " + strBarcode + " 命中记录 " + lRet.ToString() + " 条,放弃装入读者记录。\r\n\r\n注意这是一个严重错误,请系统管理员尽快排除。"; goto ERROR1; // 当出错处理 } SelectPatronDialog dlg = new SelectPatronDialog(); dlg.Overflow = StringUtil.SplitList(strRecPath).Count < lRet; nRet = dlg.Initial( this.MainForm, //this.Channel, //this.stop, StringUtil.SplitList(strRecPath), "请选择一个读者记录", out strError); if (nRet == -1) { goto ERROR1; } // TODO: 保存窗口内的尺寸状态 this.MainForm.AppInfo.LinkFormState(dlg, "ActivateForm_SelectPatronDialog_state"); dlg.ShowDialog(this); this.MainForm.AppInfo.UnlinkFormState(dlg); if (dlg.DialogResult == System.Windows.Forms.DialogResult.Cancel) { strError = "放弃选择"; return(0); } // strBarcode = dlg.SelectedBarcode; strBarcode = "@path:" + dlg.SelectedRecPath; // 2015/11/16 nRedoCount++; goto REDO; } // this.ReaderBarcode = strBarcode; if (results == null || results.Length < 2) { strError = "返回的results不正常。"; goto ERROR1; } string strXml = ""; strXml = results[0]; string strHtml = results[1]; if (edit != null) { nRet = edit.SetData( strXml, strRecPath, baTimestamp, out strError); if (nRet == -1) { goto ERROR1; } } if (webbXml != null) { /* * SetXmlToWebbrowser(webbXml, * strXml); * */ Global.SetXmlToWebbrowser(webbXml, this.MainForm.DataDir, "xml", strXml); } // this.m_strSetAction = "change"; #if NO if (webbHtml != null) { Global.SetHtmlString(webbHtml, strHtml, this.MainForm.DataDir, "activateform_html"); } #endif if (external_html != null) { external_html.SetHtmlString(strHtml, "activateform_html"); } } finally { EnableControls(true); stop.EndLoop(); stop.OnStop -= new StopEventHandler(this.DoStop); stop.Initial(""); } return(1); ERROR1: MessageBox.Show(this, strError); return(-1); }
// 初始化各种参数 bool InitialProperties(bool bFullInitial, bool bRestoreLastOpenedWindow) { int nRet = 0; // 先禁止界面 if (bFullInitial == true) { EnableControls(false); this.MdiClient.Enabled = false; } try { string strError = ""; if (bFullInitial == true) { // this.Logout(); #if NO { FirstRunDialog first_dialog = new FirstRunDialog(); MainForm.SetControlFont(first_dialog, this.DefaultFont); first_dialog.MainForm = this; first_dialog.StartPosition = FormStartPosition.CenterScreen; if (first_dialog.ShowDialog(this) == System.Windows.Forms.DialogResult.Cancel) { Application.Exit(); return; } } #endif bool bFirstDialog = false; // 如果必要,首先出现配置画面,便于配置 dp2library 的 URL string strLibraryServerUrl = this.AppInfo.GetString( "config", "circulation_server_url", ""); if (String.IsNullOrEmpty(strLibraryServerUrl) == true) { // http://stackoverflow.com/questions/860459/determine-os-using-environment-osversion // 判断当前操作系统版本 if (Environment.OSVersion.Version.Major == 5) { #if NO if (Environment.OSVersion.Version.Minor == 1) { // XP } else if (Environment.OSVersion.Version.Minor == 2) { // Server 2003. XP 64-bit will also fall in here. } #endif MessageBox.Show(this, "dp2Circulation 不支持 Windows XP / Windows Server 2003 操作系统版本。请在 Windows Vista 及以上版本安装运行"); Application.Exit(); return false; } else if (Environment.OSVersion.Version.Major >= 6) { // Vista on up } FirstRunDialog first_dialog = new FirstRunDialog(); MainForm.SetControlFont(first_dialog, this.DefaultFont); first_dialog.MainForm = this; first_dialog.StartPosition = FormStartPosition.CenterScreen; if (first_dialog.ShowDialog(this) == System.Windows.Forms.DialogResult.Cancel) { Application.Exit(); return false; } bFirstDialog = true; // 首次写入 运行模式 信息 this.AppInfo.SetString("main_form", "last_mode", first_dialog.Mode); if (first_dialog.Mode == "test") { this.AppInfo.SetString("sn", "sn", "test"); this.AppInfo.Save(); } else if (first_dialog.Mode == "community") { this.AppInfo.SetString("sn", "sn", "community"); this.AppInfo.Save(); } } else { // 以前已经安装的情况 if (Environment.OSVersion.Version.Major == 5) { MessageBox.Show(this, "尊敬的用户,dp2Circulation 在 2015 年 12 月 31 日以后将不再支持 Windows XP / Windows Server 2003 操作系统版本。请尽快升级您的 Windows 操作系统到 Vista 及以上版本。祝工作顺利。\r\n\r\n数字平台敬上"); } } #if NO // 检查序列号。这里的暂时不要求各种产品功能 // DateTime start_day = new DateTime(2014, 10, 15); // 2014/10/15 以后强制启用序列号功能 // if (DateTime.Now >= start_day || IsExistsSerialNumberStatusFile() == true) { // 在用户目录中写入一个隐藏文件,表示序列号功能已经启用 // WriteSerialNumberStatusFile(); nRet = this.VerifySerialCode("", true, out strError); if (nRet == -1) { MessageBox.Show(this, "dp2Circulation 需要先设置序列号才能使用"); Application.Exit(); return false; } } #endif #if SN { _verified = false; nRet = this.VerifySerialCode("", false, out strError); if (nRet == 0) _verified = true; } #else this.MenuItem_resetSerialCode.Visible = false; #endif bool bLogin = this.AppInfo.GetBoolean( "default_account", "occur_per_start", true); if (bLogin == true && bFirstDialog == false) // 首次运行的对话框出现后,登录对话框就不必出现了 { SetDefaultAccount( null, "登录", // "指定缺省帐户", "首次登录", // "请指定后面操作中即将用到的缺省帐户信息。", LoginFailCondition.None, this, false); } else { // 2015/5/15 string strServerUrl = AppInfo.GetString("config", "circulation_server_url", "http://localhost:8001/dp2library"); if (string.Compare(strServerUrl, CirculationLoginDlg.dp2LibraryXEServerUrl, true) == 0) AutoStartDp2libraryXE(); } } nRet = PrepareSearch(); if (nRet == 1) { try { // 2013/6/18 nRet = TouchServer(false); if (nRet == -1) goto END1; // 只有在前一步没有错出的情况下才探测版本号 if (nRet == 0) { // 检查dp2Library版本号 // return: // -1 error // 0 dp2Library的版本号过低。警告信息在strError中 // 1 dp2Library版本号符合要求 nRet = CheckVersion(false, out strError); if (nRet == -1) { MessageBox.Show(this, strError); goto END1; } if (nRet == 0) MessageBox.Show(this, strError); } // 获得书目数据库From信息 nRet = GetDbFromInfos(false); if (nRet == -1) goto END1; // 获得全部数据库的定义 nRet = GetAllDatabaseInfo(false); if (nRet == -1) goto END1; // 获得书目库属性列表 nRet = InitialBiblioDbProperties(false); if (nRet == -1) goto END1; // 获得读者库名列表 /* nRet = GetReaderDbNames(); if (nRet == -1) goto END1; * */ nRet = InitialReaderDbProperties(false); if (nRet == -1) goto END1; nRet = InitialArrivedDbProperties(false); if (nRet == -1) goto END1; // 获得实用库属性列表 nRet = GetUtilDbProperties(false); if (nRet == -1) goto END1; // 2008/11/29 nRet = InitialNormalDbProperties(false); if (nRet == -1) goto END1; // 获得图书馆一般信息 nRet = GetLibraryInfo(false); if (nRet == -1) goto END1; // 获得索取号配置信息 // 2009/2/24 nRet = GetCallNumberInfo(false); if (nRet == -1) goto END1; // 获得前端交费接口配置信息 // 2009/7/20 nRet = GetClientFineInterfaceInfo(false); if (nRet == -1) goto END1; // 获得服务器映射到本地的配置文件 nRet = GetServerMappedFile(false); if (nRet == -1) goto END1; /* // 检查服务器端library.xml中<libraryserver url="???">配置是否正常 // return: // -1 error // 0 正常 // 1 不正常 nRet = CheckServerUrl(out strError); if (nRet != 0) MessageBox.Show(this, strError); * */ // 核对本地和服务器时钟 // return: // -1 error // 0 没有问题 // 1 本地时钟和服务器时钟偏差过大,超过10分钟 strError中有报错信息 nRet = CheckServerClock(false, out strError); if (nRet != 0) MessageBox.Show(this, strError); } finally { EndSearch(); } } // 安装条码字体 InstallBarcodeFont(); END1: Stop = new DigitalPlatform.Stop(); Stop.Register(stopManager, true); // 和容器关联 Stop.SetMessage("正在删除以前遗留的临时文件..."); /* Type: System.UnauthorizedAccessException Message: Access to the path 'D:\System Volume Information\' is denied. Stack: at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileSystemEnumerableIterator`1.CommonInit() at System.IO.FileSystemEnumerableIterator`1..ctor(String path, String originalUserPath, String searchPattern, SearchOption searchOption, SearchResultHandler`1 resultHandler) at System.IO.DirectoryInfo.InternalGetFiles(String searchPattern, SearchOption searchOption) at System.IO.DirectoryInfo.GetFiles() at dp2Circulation.MainForm.DeleteAllTempFiles(String strDataDir) at dp2Circulation.MainForm.DeleteAllTempFiles(String strDataDir) at dp2Circulation.MainForm.InitialProperties(Boolean bFullInitial, Boolean bRestoreLastOpenedWindow) dp2Circulation 版本: dp2Circulation, Version=2.4.5715.19592, Culture=neutral, PublicKeyToken=null 操作系统:Microsoft Windows NT 5.1.2600 Service Pack 3 * * */ try { DeleteAllTempFiles(this.DataDir); } catch (System.UnauthorizedAccessException ex) { MessageBox.Show(this, "在试图删除数据目录 '"+this.DataDir+"' 内临时文件时出错: " + ex.Message + "\r\n\r\n既然您把软件安装到这个目录或者试图从这里运行软件,就该给当前 Windows 用户赋予针对这个目录的列目录和删除文件的权限"); Application.Exit(); return false; } try { DeleteAllTempFiles(this.UserTempDir); } catch (System.UnauthorizedAccessException ex) { MessageBox.Show(this, "在试图删除用户临时目录 '" + this.UserTempDir + "' 内临时文件时出错: " + ex.Message + "\r\n\r\n应给当前 Windows 用户赋予针对这个目录的列目录和删除文件的权限"); Application.Exit(); return false; } Stop.SetMessage("正在复制报表配置文件..."); // 拷贝目录 nRet = PathUtil.CopyDirectory(Path.Combine(this.DataDir, "report_def"), Path.Combine(this.UserDir, "report_def"), false, out strError); if (nRet == -1) MessageBox.Show(this, strError); Stop.SetMessage(""); if (Stop != null) // 脱离关联 { Stop.Unregister(); // 和容器关联 Stop = null; } // 2013/12/4 if (InitialClientScript(out strError) == -1) MessageBox.Show(this, strError); // 初始化历史对象,包括C#脚本 if (this.OperHistory == null) { this.OperHistory = new OperHistory(); nRet = this.OperHistory.Initial(this, this.webBrowser_history, out strError); if (nRet == -1) MessageBox.Show(this, strError); // this.timer_operHistory.Start(); } // if (Program.IsDevelopMode() == true) { // 初始化 MessageHub this.MessageHub = new MessageHub(); this.MessageHub.Initial(this, this.webBrowser_messageHub); } } finally { // 然后许可界面 if (bFullInitial == true) { this.MdiClient.Enabled = true; EnableControls(true); } if (this.m_backgroundForm != null) { // TODO: 最好有个淡出的功能 this.stopManager.OnDisplayMessage += new DisplayMessageEventHandler(stopManager_OnDisplayMessage); this.MdiClient.SizeChanged -= new EventHandler(MdiClient_SizeChanged); this.m_backgroundForm.Close(); this.m_backgroundForm = null; } } if (bRestoreLastOpenedWindow == true) RestoreLastOpenedMdiWindow(); if (bFullInitial == true) { #if NO // 恢复上次遗留的窗口 string strOpenedMdiWindow = this.AppInfo.GetString( "main_form", "last_opened_mdi_window", ""); RestoreLastOpenedMdiWindow(strOpenedMdiWindow); #endif // 初始化指纹高速缓存 FirstInitialFingerprintCache(); } return true; }
// 填充一个新的amerced行 // stop已经被外层BeginLoop()了 // TODO: Summary获得时出错,最好作为警告而不是错误。 int FillAmercedLine( Stop stop, string strXml, string strRecPath, out string strError) { strError = ""; XmlDocument dom = new XmlDocument(); try { dom.LoadXml(strXml); } catch (Exception ex) { strError = "XML装载到DOM时发生错误: " + ex.Message; return -1; } string strItemBarcode = DomUtil.GetElementText(dom.DocumentElement, "itemBarcode"); string strItemRecPath = DomUtil.GetElementText(dom.DocumentElement, "itemRecPath"); string strSummary = ""; string strPrice = DomUtil.GetElementText(dom.DocumentElement, "price"); string strComment = DomUtil.GetElementText(dom.DocumentElement, "comment"); string strReason = DomUtil.GetElementText(dom.DocumentElement, "reason"); string strBorrowDate = DomUtil.GetElementText(dom.DocumentElement, "borrowDate"); strBorrowDate = DateTimeUtil.LocalTime(strBorrowDate, "u"); string strBorrowPeriod = DomUtil.GetElementText(dom.DocumentElement, "borrowPeriod"); string strReturnDate = DomUtil.GetElementText(dom.DocumentElement, "returnDate"); strReturnDate = DateTimeUtil.LocalTime(strReturnDate, "u"); string strID = DomUtil.GetElementText(dom.DocumentElement, "id"); string strReturnOperator = DomUtil.GetElementText(dom.DocumentElement, "returnOperator"); string strState = DomUtil.GetElementText(dom.DocumentElement, "state"); // 2007/6/18 string strAmerceOperator = DomUtil.GetElementText(dom.DocumentElement, "operator"); string strAmerceTime = DomUtil.GetElementText(dom.DocumentElement, "operTime"); strAmerceTime = DateTimeUtil.LocalTime(strAmerceTime, "u"); string strSettlementOperator = DomUtil.GetElementText(dom.DocumentElement, "settlementOperator"); string strSettlementTime = DomUtil.GetElementText(dom.DocumentElement, "settlementOperTime"); strSettlementTime = DateTimeUtil.LocalTime(strSettlementTime, "u"); #if NO if (String.IsNullOrEmpty(strItemBarcode) == false) { // stop.OnStop += new StopEventHandler(this.DoStop); stop.SetMessage("正在获取摘要 " + strItemBarcode + " ..."); // stop.BeginLoop(); try { string strBiblioRecPath = ""; long lRet = Channel.GetBiblioSummary( stop, strItemBarcode, strItemRecPath, null, out strBiblioRecPath, out strSummary, out strError); if (lRet == -1) { strSummary = strError; // return -1; } } finally { // stop.EndLoop(); // stop.OnStop -= new StopEventHandler(this.DoStop); // stop.Initial(""); } } #endif ListViewItem item = new ListViewItem(strItemBarcode, 0); /* item.SubItems.Add(strSummary); item.SubItems.Add(strPrice); item.SubItems.Add(strComment); item.SubItems.Add(strReason); item.SubItems.Add(strBorrowDate); item.SubItems.Add(strBorrowPeriod); item.SubItems.Add(strReturnDate); item.SubItems.Add(strID); item.SubItems.Add(strReturnOperator); item.SubItems.Add(strState); item.SubItems.Add(strAmerceOperator); item.SubItems.Add(strAmerceTime); item.SubItems.Add(strSettlementOperator); item.SubItems.Add(strSettlementTime); item.SubItems.Add(strRecPath); * */ ListViewUtil.ChangeItemText(item, COLUMN_AMERCED_BIBLIOSUMMARY, strSummary); ListViewUtil.ChangeItemText(item, COLUMN_AMERCED_PRICE, strPrice); ListViewUtil.ChangeItemText(item, COLUMN_AMERCED_COMMENT, strComment); ListViewUtil.ChangeItemText(item, COLUMN_AMERCED_REASON, strReason); ListViewUtil.ChangeItemText(item, COLUMN_AMERCED_BORROWDATE, strBorrowDate); ListViewUtil.ChangeItemText(item, COLUMN_AMERCED_BORROWPERIOD, strBorrowPeriod); ListViewUtil.ChangeItemText(item, COLUMN_AMERCED_RETURNDATE, strReturnDate); ListViewUtil.ChangeItemText(item, COLUMN_AMERCED_ID, strID); ListViewUtil.ChangeItemText(item, COLUMN_AMERCED_RETURNOPERATOR, strReturnOperator); ListViewUtil.ChangeItemText(item, COLUMN_AMERCED_STATE, strState); ListViewUtil.ChangeItemText(item, COLUMN_AMERCED_AMERCEOPERATOR, strAmerceOperator); ListViewUtil.ChangeItemText(item, COLUMN_AMERCED_AMERCETIME, strAmerceTime); ListViewUtil.ChangeItemText(item, COLUMN_AMERCED_SETTLEMENTOPERATOR, strSettlementOperator); ListViewUtil.ChangeItemText(item, COLUMN_AMERCED_SETTLEMENTTIME, strSettlementTime); ListViewUtil.ChangeItemText(item, COLUMN_AMERCED_RECPATH, strRecPath); // 2012/10/8 AmercedItemInfo info = new AmercedItemInfo(); info.Xml = strXml; item.Tag = info; this.listView_amerced.Items.Add(item); return 0; }
private void button_test_loginAttack_Click(object sender, EventArgs e) { LibraryChannel channel = new LibraryChannel(); channel.Url = this.MainForm.LibraryServerUrl; channel.BeforeLogin -= new DigitalPlatform.CirculationClient.BeforeLoginEventHandle(Channel_BeforeLogin); channel.BeforeLogin += new DigitalPlatform.CirculationClient.BeforeLoginEventHandle(Channel_BeforeLogin); _stop = new DigitalPlatform.Stop(); _stop.Register(this.MainForm.stopManager, true); // 和容器关联 _stop.OnStop += new StopEventHandler(this.DoStop); _stop.Style = StopStyle.EnableHalfStop; _stop.Initial("正在试探密码 ..."); _stop.BeginLoop(); this.button_test_loginAttack.Enabled = false; this.numericUpDown_test_tryChannelCount.Enabled = false; try { for (int i = 0; i < this.numericUpDown_test_tryChannelCount.Value; i++) { Application.DoEvents(); if (_stop != null && _stop.State != 0) break; string strUserName = "******"; string strPassword = i.ToString(); string strRights = ""; string strLibraryCode = ""; string strOutputUserName = ""; string strError = ""; long lRet = channel.Login( strUserName, strPassword, "", out strOutputUserName, out strRights, out strLibraryCode, out strError); #if NO if (lRet == -1) { if (channel.ErrorCode == DigitalPlatform.CirculationClient.localhost.ErrorCode.OutofSession) break; } #endif _stop.SetMessage(i.ToString() + " username="******" password="******" lRet = " + lRet.ToString() + " " + strError); } } finally { this.numericUpDown_test_tryChannelCount.Enabled = true; this.button_test_loginAttack.Enabled = true; _stop.EndLoop(); _stop.OnStop -= new StopEventHandler(this.DoStop); _stop.Initial(""); if (_stop != null) // 脱离关联 { _stop.Unregister(); // 和容器关联 _stop = null; } } }
// parameters: // output_columns 输出列定义。如果为空,表示全部输出。这是一个数字列表,例如 "1,2,3,5" // return: // -1 出错 // 0 放弃或中断 // 1 成功 public static int ExportToExcel( Stop stop, ListView list, List<string> output_columns, List<ListViewItem> items, IXLWorksheet sheet, out string strError) { strError = ""; #if NO if (items == null || items.Count == 0) { strError = "items == null || items.Count == 0"; return -1; } #endif // ListView list = items[0].ListView; if (stop != null) stop.SetProgressRange(0, items.Count); List<int> indices = new List<int>(); if (output_columns == null && output_columns.Count == 0) { int i = 0; foreach (ColumnHeader header in list.Columns) { indices.Add(i++); } } else { foreach (string s in output_columns) { int v = 0; if (Int32.TryParse(s, out v) == false) { strError = "output_columns 数组中有非数字的字符串,格式错误"; return -1; } indices.Add(v - 1); // 从 0 开始计数 } } // 每个列的最大字符数 List<int> column_max_chars = new List<int>(); List<XLAlignmentHorizontalValues> alignments = new List<XLAlignmentHorizontalValues>(); //foreach (ColumnHeader header in list.Columns) foreach (int index in indices) { ColumnHeader header = list.Columns[index]; if (header.TextAlign == HorizontalAlignment.Center) alignments.Add(XLAlignmentHorizontalValues.Center); else if (header.TextAlign == HorizontalAlignment.Right) alignments.Add(XLAlignmentHorizontalValues.Right); else alignments.Add(XLAlignmentHorizontalValues.Left); column_max_chars.Add(0); } string strFontName = list.Font.FontFamily.Name; int nRowIndex = 1; int nColIndex = 1; // foreach (ColumnHeader header in list.Columns) foreach (int index in indices) { ColumnHeader header = list.Columns[index]; IXLCell cell = sheet.Cell(nRowIndex, nColIndex).SetValue(header.Text); cell.Style.Alignment.WrapText = true; cell.Style.Alignment.Vertical = XLAlignmentVerticalValues.Center; cell.Style.Font.Bold = true; cell.Style.Font.FontName = strFontName; cell.Style.Alignment.Horizontal = alignments[nColIndex - 1]; nColIndex++; } nRowIndex++; //if (stop != null) // stop.SetMessage(""); foreach (ListViewItem item in items) { Application.DoEvents(); if (stop != null && stop.State != 0) { strError = "用户中断"; return 0; } // List<CellData> cells = new List<CellData>(); nColIndex = 1; // foreach (ListViewItem.ListViewSubItem subitem in item.SubItems) foreach (int index in indices) { string strText = ""; ListViewItem.ListViewSubItem subitem = null; if (index < item.SubItems.Count) { subitem = item.SubItems[index]; strText = subitem.Text; } else { } // 统计最大字符数 int nChars = column_max_chars[nColIndex - 1]; if (string.IsNullOrEmpty(strText) == false && strText.Length > nChars) { column_max_chars[nColIndex - 1] = strText.Length; } IXLCell cell = sheet.Cell(nRowIndex, nColIndex).SetValue(strText); cell.Style.Alignment.WrapText = true; cell.Style.Alignment.Vertical = XLAlignmentVerticalValues.Center; cell.Style.Font.FontName = strFontName; cell.Style.Alignment.Horizontal = alignments[nColIndex - 1]; nColIndex++; } if (stop != null) stop.SetProgressValue(nRowIndex - 1); nRowIndex++; } if (stop != null) stop.SetMessage("正在调整列宽度 ..."); Application.DoEvents(); double char_width = ClosedXmlUtil.GetAverageCharPixelWidth(list); // 字符数太多的列不要做 width auto adjust const int MAX_CHARS = 30; // 60 { int i = 0; foreach (IXLColumn column in sheet.Columns()) { int nChars = column_max_chars[i]; if (nChars < MAX_CHARS) column.AdjustToContents(); else column.Width = (double)list.Columns[i].Width / char_width; // Math.Min(MAX_CHARS, nChars); i++; } } return 1; }
public static int SearchOneLocationItems( MainForm main_form, LibraryChannel channel, Stop stop, string strLocation, string strOutputStyle, out List<string> results, out string strError) { strError = ""; results = new List<string>(); long lRet = channel.SearchItem(stop, "<all>", strLocation, // -1, "馆藏地点", "left", // this.textBox_queryWord.Text == "" ? "left" : "exact", // 原来为left 2007/10/18 changed "zh", null, // strResultSetName "", // strSearchStyle "", //strOutputStyle, // (bOutputKeyCount == true ? "keycount" : ""), out strError); if (lRet == -1) return -1; long lHitCount = lRet; long lStart = 0; long lCount = lHitCount; DigitalPlatform.LibraryClient.localhost.Record[] searchresults = null; bool bOutputBiblioRecPath = false; bool bOutputItemRecPath = false; string strStyle = ""; if (strOutputStyle == "bibliorecpath") { bOutputBiblioRecPath = true; strStyle = "id,cols,format:@coldef:*/parent"; } else { bOutputItemRecPath = true; strStyle = "id"; } // 实体库名 --> 书目库名 Hashtable dbname_table = new Hashtable(); // 书目库记录路径,用于去重 Hashtable bilio_recpath_table = new Hashtable(); // 装入浏览格式 for (; ; ) { Application.DoEvents(); // 出让界面控制权 if (stop != null && stop.State != 0) { strError = "检索共命中 " + lHitCount.ToString() + " 条,已装入 " + lStart.ToString() + " 条,用户中断..."; return -1; } lRet = channel.GetSearchResult( stop, null, // strResultSetName lStart, lCount, strStyle, // bOutputKeyCount == true ? "keycount" : "id,cols", "zh", out searchresults, out strError); if (lRet == -1) { strError = "检索共命中 " + lHitCount.ToString() + " 条,已装入 " + lStart.ToString() + " 条," + strError; return -1; } if (lRet == 0) { return 0; } // 处理浏览结果 for (int i = 0; i < searchresults.Length; i++) { DigitalPlatform.LibraryClient.localhost.Record searchresult = searchresults[i]; if (bOutputBiblioRecPath == true) { string strItemDbName = Global.GetDbName(searchresult.Path); string strBiblioDbName = (string)dbname_table[strItemDbName]; if (string.IsNullOrEmpty(strBiblioDbName) == true) { strBiblioDbName = main_form.GetBiblioDbNameFromItemDbName(strItemDbName); dbname_table[strItemDbName] = strBiblioDbName; } string strBiblioRecPath = strBiblioDbName + "/" + searchresult.Cols[0]; if (bilio_recpath_table.ContainsKey(strBiblioRecPath) == false) { results.Add(strBiblioRecPath); bilio_recpath_table[strBiblioRecPath] = true; } } else if (bOutputItemRecPath == true) results.Add(searchresult.Path); } lStart += searchresults.Length; lCount -= searchresults.Length; stop.SetMessage("共命中 " + lHitCount.ToString() + " 条,已装入 " + lStart.ToString() + " 条"); if (lStart >= lHitCount || lCount <= 0) break; } return 0; }
// 为选定的行装入Full元素集的记录 public void ReloadFullElementSet() { string strError = ""; int nRet = 0; ZConnection connection = this.GetCurrentZConnection(); if (connection == null) { strError = "当前ZConnection为空"; goto ERROR1; } if (connection.VirtualItems.SelectedIndices.Count == 0) { strError = "尚未选定要装入完整格式的浏览行"; goto ERROR1; } DigitalPlatform.Stop stop = null; stop = new DigitalPlatform.Stop(); stop.Register(this.MainForm.stopManager, true); // 和容器关联 stop.BeginLoop(); this.EnableControls(false); try { List<int> selected = new List<int>(); selected.AddRange(connection.VirtualItems.SelectedIndices); stop.SetProgressRange(0, selected.Count); for (int i = 0; i < selected.Count; i++) { Application.DoEvents(); // 出让界面控制权 if (stop != null) { if (stop.State != 0) { strError = "用户中断"; goto ERROR1; } } int index = selected[i]; stop.SetMessage("正在重新装载记录 "+(index+1).ToString()+" 的详细格式..."); byte[] baTimestamp = null; string strSavePath = ""; string strOutStyle = ""; LoginInfo logininfo = null; long lVersion = 0; string strXmlFragment = ""; DigitalPlatform.Z3950.Record record = null; Encoding currentEncoding = null; string strMARC = ""; nRet = this.GetOneRecord( "marc", index, // 即将废止 "index:" + index.ToString(), "force_full", // false, out strSavePath, out strMARC, out strXmlFragment, out strOutStyle, out baTimestamp, out lVersion, out record, out currentEncoding, out logininfo, out strError); if (nRet == -1) goto ERROR1; stop.SetProgressValue(i); } return; } finally { stop.EndLoop(); stop.SetMessage(""); stop.Unregister(); // 和容器关联 stop = null; this.EnableControls(true); } // return 0; ERROR1: MessageBox.Show(this, strError); }
// 注意:上级函数RunScript()已经使用了BeginLoop()和EnableControls() // 对每个XML记录进行循环 // return: // 0 普通返回 // 1 要全部中断 int DoLoop(out string strError) { strError = ""; // int nRet = 0; // long lRet = 0; #if NO // 清除错误信息窗口中残余的内容 if (this.ErrorInfoForm != null) { try { this.ErrorInfoForm.HtmlString = "<pre>"; } catch { } } #endif // 清除错误信息窗口中残余的内容 ClearErrorInfoForm(); string strInputFileName = ""; try { strInputFileName = this.textBox_inputXmlFilename.Text; Stream file = null; try { file = File.Open(strInputFileName, FileMode.Open, FileAccess.Read); } catch (Exception ex) { strError = "打开文件 " + strInputFileName + " 失败: " + ex.Message; return(-1); } XmlTextReader reader = new XmlTextReader(file); this.progressBar_records.Minimum = 0; this.progressBar_records.Maximum = (int)file.Length; this.progressBar_records.Value = 0; /* * stop.OnStop += new StopEventHandler(this.DoStop); * stop.Initial("正在获取XML记录 ..."); * stop.BeginLoop(); * * EnableControls(false); * */ bool bRet = false; while (true) { bRet = reader.Read(); if (bRet == false) { strError = "没有根元素"; return(-1); } if (reader.NodeType == XmlNodeType.Element) { break; } } try { int nCount = 0; for (int i = 0; ; i++) { Application.DoEvents(); // 出让界面控制权 if (stop != null) { if (stop.State != 0) { DialogResult result = MessageBox.Show(this, "准备中断。\r\n\r\n确实要中断全部操作? (Yes 全部中断;No 中断循环,但是继续收尾处理;Cancel 放弃中断,继续操作)", "ReaderStatisForm", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button3); if (result == DialogResult.Yes) { strError = "用户中断"; return(-1); } if (result == DialogResult.No) { return(0); // 假装loop正常结束 } stop.Continue(); // 继续循环 } } while (true) { bRet = reader.Read(); if (bRet == false) { return(0); } if (reader.NodeType == XmlNodeType.Element) { break; } } if (bRet == false) { return(0); // 结束 } string strXml = reader.ReadOuterXml(); stop.SetMessage("正在获取第 " + (i + 1).ToString() + " 个XML记录"); this.progressBar_records.Value = (int)file.Position; // strXml中为XML记录 XmlDocument dom = new XmlDocument(); try { dom.LoadXml(strXml); } catch (Exception ex) { strError = "XML记录装入DOM发生错误: " + ex.Message; GetErrorInfoForm().WriteHtml(strError + "\r\n"); continue; } // 触发Script中OnRecord()代码 if (objStatis != null) { objStatis.Xml = strXml; objStatis.RecordDom = dom; objStatis.CurrentRecordIndex = i; StatisEventArgs args = new StatisEventArgs(); objStatis.OnRecord(this, args); if (args.Continue == ContinueType.SkipAll) { return(1); } } nCount++; } /* * Global.WriteHtml(this.webBrowser_batchAddItemPrice, * "处理结束。共增补价格字符串 " + nCount.ToString() + " 个。\r\n"); * */ } finally { /* * EnableControls(true); * * stop.EndLoop(); * stop.OnStop -= new StopEventHandler(this.DoStop); * stop.Initial(""); * */ if (file != null) { file.Close(); } } } finally { } // return 0; }
// 填充一个新的amerced行 // stop已经被外层BeginLoop()了 // TODO: Summary获得时出错,最好作为警告而不是错误。 // parameters: // item ListView事项。如果为null,表示本函数需要创建新的事项 int FillAmercedLine( ListViewItem item, Stop stop, string strXml, string strRecPath, bool bFillSummary, out string strError) { strError = ""; XmlDocument dom = new XmlDocument(); try { dom.LoadXml(strXml); } catch (Exception ex) { strError = "XML装载到DOM时发生错误: " + ex.Message; return -1; } string strItemBarcode = DomUtil.GetElementText(dom.DocumentElement, "itemBarcode"); string strItemRecPath = DomUtil.GetElementText(dom.DocumentElement, "itemRecPath"); string strSummary = ""; string strReaderBarcode = DomUtil.GetElementText(dom.DocumentElement, "readerBarcode"); string strLibraryCode = DomUtil.GetElementText(dom.DocumentElement, "libraryCode"); string strPrice = DomUtil.GetElementText(dom.DocumentElement, "price"); string strComment = DomUtil.GetElementText(dom.DocumentElement, "comment"); string strReason = DomUtil.GetElementText(dom.DocumentElement, "reason"); string strBorrowDate = DomUtil.GetElementText(dom.DocumentElement, "borrowDate"); strBorrowDate = DateTimeUtil.LocalTime(strBorrowDate, "u"); string strBorrowPeriod = DomUtil.GetElementText(dom.DocumentElement, "borrowPeriod"); string strReturnDate = DomUtil.GetElementText(dom.DocumentElement, "returnDate"); strReturnDate = DateTimeUtil.LocalTime(strReturnDate, "u"); string strID = DomUtil.GetElementText(dom.DocumentElement, "id"); string strReturnOperator = DomUtil.GetElementText(dom.DocumentElement, "returnOperator"); string strState = DomUtil.GetElementText(dom.DocumentElement, "state"); strState = GetDisplayStateText(strState); // 2009/1/29 string strAmerceOperator = DomUtil.GetElementText(dom.DocumentElement, "operator"); string strAmerceTime = DomUtil.GetElementText(dom.DocumentElement, "operTime"); strAmerceTime = DateTimeUtil.LocalTime(strAmerceTime, "u"); string strSettlementOperator = DomUtil.GetElementText(dom.DocumentElement, "settlementOperator"); string strSettlementTime = DomUtil.GetElementText(dom.DocumentElement, "settlementOperTime"); strSettlementTime = DateTimeUtil.LocalTime(strSettlementTime, "u"); if (bFillSummary == true) { // stop.OnStop += new StopEventHandler(this.DoStop); stop.SetMessage("正在获取摘要 " + strItemBarcode + " ..."); // stop.BeginLoop(); try { string strBiblioRecPath = ""; long lRet = Channel.GetBiblioSummary( stop, strItemBarcode, strItemRecPath, null, out strBiblioRecPath, out strSummary, out strError); if (lRet == -1) { strSummary = strError; // return -1; } } finally { // stop.EndLoop(); // stop.OnStop -= new StopEventHandler(this.DoStop); // stop.Initial(""); } } string strOldState = null; if (item == null) { item = new ListViewItem(strID, 0); this.listView_amerced.Items.Add(item); strOldState = null; } else { strOldState = item.SubItems[COLUMN_STATE].Text; item.SubItems.Clear(); item.Text = strID; } item.SubItems.Add(strState); item.SubItems.Add(strReaderBarcode); item.SubItems.Add(strLibraryCode); item.SubItems.Add(strPrice); item.SubItems.Add(strComment); item.SubItems.Add(strReason); item.SubItems.Add(strBorrowDate); item.SubItems.Add(strBorrowPeriod); item.SubItems.Add(strReturnDate); item.SubItems.Add(strReturnOperator); item.SubItems.Add(strItemBarcode); item.SubItems.Add(strSummary); item.SubItems.Add(strAmerceOperator); item.SubItems.Add(strAmerceTime); item.SubItems.Add(strSettlementOperator); item.SubItems.Add(strSettlementTime); item.SubItems.Add(strRecPath); SetItemIconAndColor(strOldState, item); return 0; }
int BuildCharsetTable(out string strError) { strError = ""; CharsetTable charsettable_e2u = new CharsetTable(); CharsetTable charsettable_u2e = new CharsetTable(); charsettable_e2u.Open(true); charsettable_u2e.Open(true); if (this.textBox_unihanFilenames.Text == "") { strError = "尚未指定输入文件名"; return(-1); } stop.OnStop += new StopEventHandler(this.DoStop); stop.SetMessage("正在创建码表文件 ..."); stop.BeginLoop(); EnableControls(false); this.Update(); this.MainForm.Update(); try { for (int i = 0; i < this.textBox_unihanFilenames.Lines.Length; i++) { StreamReader sr = null; try { sr = new StreamReader(this.textBox_unihanFilenames.Lines[i]); } catch (Exception ex) { strError = "文件 " + this.textBox_unihanFilenames.Lines[i] + " 打开失败: " + ex.Message; return(-1); } this.MainForm.ToolStripProgressBar.Minimum = 0; this.MainForm.ToolStripProgressBar.Maximum = (int)sr.BaseStream.Length; this.MainForm.ToolStripProgressBar.Value = 0; try { for (; ;) { Application.DoEvents(); // 出让界面控制权 if (stop != null) { if (stop.State != 0) { strError = "用户中断"; return(-1); } } string strLine = sr.ReadLine(); if (strLine == null) { break; } if (strLine.Length < 1) { goto CONTINUE; } // 注释行 if (strLine[0] == '#') { goto CONTINUE; } int nRet = strLine.IndexOf("\t", 0); if (nRet == -1) { goto CONTINUE; // 格式有问题 } string strPart1 = strLine.Substring(0, nRet).Trim(); strLine = strLine.Substring(nRet + 1); nRet = strLine.IndexOf("\t", 0); if (nRet == -1) { goto CONTINUE; // 格式有问题 } string strPart2 = strLine.Substring(0, nRet).Trim(); string strPart3 = strLine.Substring(nRet + 1).Trim(); strPart1 = strPart1.Substring(2); // 去掉'U+' if (strPart2 != "kEACC") { goto CONTINUE; // 不相关的行 } strLine = strPart1 + "\t" + strPart3; CharsetItem item = new CharsetItem(); item.Content = strLine; charsettable_u2e.Add(item); strLine = strPart3 + "\t" + strPart1; item = new CharsetItem(); item.Content = strLine; charsettable_e2u.Add(item); // ANSI字符集 stop.SetMessage(strLine); CONTINUE: // 显示进度条 this.MainForm.ToolStripProgressBar.Value = (int)sr.BaseStream.Position; } } finally { sr.Close(); } } stop.SetMessage("正在复制和排序..."); string strDataFileName = ""; string strIndexFileName = ""; if (String.IsNullOrEmpty(this.textBox_e2uFilename.Text) == false) { charsettable_e2u.Sort(); charsettable_e2u.Detach(out strDataFileName, out strIndexFileName); File.Delete(this.textBox_e2uFilename.Text); File.Move(strDataFileName, this.textBox_e2uFilename.Text); File.Delete(this.textBox_e2uFilename.Text + ".index"); File.Move(strIndexFileName, this.textBox_e2uFilename.Text + ".index"); } // if (String.IsNullOrEmpty(this.textBox_u2eFilename.Text) == false) { charsettable_u2e.Sort(); charsettable_u2e.Detach(out strDataFileName, out strIndexFileName); File.Delete(this.textBox_u2eFilename.Text); File.Move(strDataFileName, this.textBox_u2eFilename.Text); File.Delete(this.textBox_u2eFilename.Text + ".index"); File.Move(strIndexFileName, this.textBox_u2eFilename.Text + ".index"); } } finally { stop.EndLoop(); stop.OnStop -= new StopEventHandler(this.DoStop); stop.Initial(""); EnableControls(true); } return(0); }
// return: // -1 出错 // 0 未发生改变 // 1 发生了改变 int ChangeOneRecord(string strBiblioRecPath, DateTime now, out string strError) { strError = ""; int nRet = 0; stop.SetMessage("正在处理 " + strBiblioRecPath + " ..."); string[] formats = new string[1]; formats[0] = "xml"; string[] results = null; byte[] timestamp = null; long lRet = Channel.GetBiblioInfos( stop, strBiblioRecPath, "", formats, out results, out timestamp, out strError); if (lRet == 0) { return(0); // not found } if (lRet == -1) { return(-1); } if (results.Length == 0) { strError = "results length error"; return(-1); } string strXml = results[0]; XmlDocument domOrigin = new XmlDocument(); try { domOrigin.LoadXml(strXml); } catch (Exception ex) { strError = "装载XML到DOM时发生错误: " + ex.Message; return(-1); } string strMARC = ""; string strMarcSyntax = ""; string strOutMarcSyntax = ""; // 将XML格式转换为MARC格式 // 自动从数据记录中获得MARC语法 nRet = MarcUtil.Xml2Marc(strXml, true, strMarcSyntax, out strOutMarcSyntax, out strMARC, out strError); if (nRet == -1) { strError = "XML转换到MARC记录时出错: " + strError; return(-1); } // 修改 // return: // -1 出错 // 0 未发生改变 // 1 发生了改变 nRet = ModifyField998(ref strMARC, now, out strError); if (nRet == -1) { return(-1); } if (nRet == 0) { return(0); } // 转换回xml格式 XmlDocument domMarc = null; nRet = MarcUtil.Marc2Xml(strMARC, strOutMarcSyntax, out domMarc, out strError); if (nRet == -1) { return(-1); } // 合并<dprms:file>元素 XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable()); nsmgr.AddNamespace("dprms", DpNs.dprms); XmlNodeList nodes = domOrigin.DocumentElement.SelectNodes("//dprms:file", nsmgr); for (int i = 0; i < nodes.Count; i++) { XmlNode new_node = domMarc.CreateElement("dprms", "file", DpNs.dprms); domMarc.DocumentElement.AppendChild(new_node); DomUtil.SetElementOuterXml(new_node, nodes[i].OuterXml); } // 保存 byte[] baNewTimestamp = null; string strOutputPath = ""; lRet = Channel.SetBiblioInfo( stop, "change", strBiblioRecPath, "xml", domMarc.DocumentElement.OuterXml, timestamp, "", out strOutputPath, out baNewTimestamp, out strError); if (lRet == -1) { strError = "保存书目记录 '" + strBiblioRecPath + "' 时出错: " + strError; return(-1); } return(1); }
// 注意:上级函数RunScript()已经使用了BeginLoop()和EnableControls() // 对每个Iso2709Statis记录进行循环 // return: // 0 普通返回 // 1 要全部中断 int DoLoop(out string strError) { strError = ""; // int nRet = 0; // long lRet = 0; Encoding encoding = null; if (string.IsNullOrEmpty(this._openMarcFileDialog.EncodingName) == true) { strError = "尚未选定 ISO2709 文件的编码方式"; return(-1); } if (StringUtil.IsNumber(this._openMarcFileDialog.EncodingName) == true) { encoding = Encoding.GetEncoding(Convert.ToInt32(this._openMarcFileDialog.EncodingName)); } else { encoding = Encoding.GetEncoding(this._openMarcFileDialog.EncodingName); } #if NO // 清除错误信息窗口中残余的内容 if (this.ErrorInfoForm != null) { try { this.ErrorInfoForm.HtmlString = "<pre>"; } catch { } } #endif ClearErrorInfoForm(); string strInputFileName = ""; try { strInputFileName = this._openMarcFileDialog.FileName; Stream file = null; try { file = File.Open(strInputFileName, FileMode.Open, FileAccess.Read); } catch (Exception ex) { strError = "打开文件 " + strInputFileName + " 失败: " + ex.Message; return(-1); } this.progressBar_records.Minimum = 0; this.progressBar_records.Maximum = (int)file.Length; this.progressBar_records.Value = 0; /* * stop.OnStop += new StopEventHandler(this.DoStop); * stop.Initial("正在获取ISO2709记录 ..."); * stop.BeginLoop(); * * EnableControls(false); * */ try { int nCount = 0; for (int i = 0; ; i++) { Application.DoEvents(); // 出让界面控制权 if (stop != null) { if (stop.State != 0) { DialogResult result = MessageBox.Show(this, "准备中断。\r\n\r\n确实要中断全部操作? (Yes 全部中断;No 中断循环,但是继续收尾处理;Cancel 放弃中断,继续操作)", "Iso2709StatisForm", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button3); if (result == DialogResult.Yes) { strError = "用户中断"; return(-1); } if (result == DialogResult.No) { return(0); // 假装loop正常结束 } stop.Continue(); // 继续循环 } } // 从ISO2709文件中读入一条MARC记录 // return: // -2 MARC格式错 // -1 出错 // 0 正确 // 1 结束(当前返回的记录有效) // 2 结束(当前返回的记录无效) int nRet = MarcUtil.ReadMarcRecord(file, encoding, true, // bRemoveEndCrLf, true, // bForce, out string strMARC, out strError); if (nRet == -2 || nRet == -1) { DialogResult result = MessageBox.Show(this, "读入MARC记录(" + nCount.ToString() + ")出错: " + strError + "\r\n\r\n确实要中断当前批处理操作?", "Iso2709StatisForm", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (result == DialogResult.Yes) { break; } else { strError = "读入MARC记录(" + nCount.ToString() + ")出错: " + strError; GetErrorInfoForm().WriteHtml(strError + "\r\n"); continue; } } if (nRet != 0 && nRet != 1) { return(0); // 结束 } stop.SetMessage("正在获取第 " + (i + 1).ToString() + " 个 ISO2709 记录"); this.progressBar_records.Value = (int)file.Position; // 跳过太短的记录 if (string.IsNullOrEmpty(strMARC) == true || strMARC.Length <= 24) { continue; } if (this._openMarcFileDialog.Mode880 == true && (this._openMarcFileDialog.MarcSyntax == "usmarc" || this._openMarcFileDialog.MarcSyntax == "<自动>")) { MarcRecord temp = new MarcRecord(strMARC); MarcQuery.ToParallel(temp); strMARC = temp.Text; } // 触发Script中OnRecord()代码 if (objStatis != null) { objStatis.MARC = strMARC; objStatis.CurrentRecordIndex = i; StatisEventArgs args = new StatisEventArgs(); objStatis.OnRecord(this, args); if (args.Continue == ContinueType.SkipAll) { return(1); } if (args.Continue == ContinueType.Error) { strError = args.ParamString; return(-1); } } nCount++; } /* * Global.WriteHtml(this.webBrowser_batchAddItemPrice, * "处理结束。共增补价格字符串 " + nCount.ToString() + " 个。\r\n"); * */ return(0); } finally { /* * EnableControls(true); * * stop.EndLoop(); * stop.OnStop -= new StopEventHandler(this.DoStop); * stop.Initial(""); * */ if (file != null) { file.Close(); } } } finally { } // return 0; }
/// <summary> /// 设置进度条上的文字显示 /// </summary> /// <param name="strMessage">要显示的字符串</param> public void SetProgressMessage(string strMessage) { stop.SetMessage(strMessage); }
// return: // -1 出错 // 0 正常结束 // 1 中断 /// <summary> /// 处理日志文件 /// </summary> /// <param name="owner">宿主窗口</param> /// <param name="stop">停止对象</param> /// <param name="estimate">剩余时间估算器</param> /// <param name="channel">通讯通道</param> /// <param name="filenames">要参与处理的日志文件名集合</param> /// <param name="nLevel">从 dp2Library 服务器获取日志记录的详细级别</param> /// <param name="strStyle">处理风格。autocache</param> /// <param name="strCacheDir">日志本地缓存目录</param> /// <param name="param">回调对象</param> /// <param name="procDoRecord">回调函数</param> /// <param name="strError">返回出错信息</param> /// <returns> /// -1 出错 /// 0 正常结束 /// 1 中断 /// </returns> public static int ProcessFiles( IWin32Window owner, Stop stop, ProgressEstimate estimate, LibraryChannel channel, List<string> filenames, int nLevel, string strStyle, string strCacheDir, object param, Delegate_doRecord procDoRecord, out string strError) { strError = ""; int nRet = 0; bool bAccessLog = StringUtil.IsInList("accessLog", strStyle); if (string.IsNullOrEmpty(strCacheDir) == false) PathUtil.CreateDirIfNeed(strCacheDir); // ProgressEstimate estimate = new ProgressEstimate(); bool bAutoCache = StringUtil.IsInList("autocache", strStyle); if (bAutoCache == true) { long lServerFileSize = 0; long lCacheFileSize = 0; // 象征性获得一个日志文件的尺寸,主要目的是为了触发一次通道登录 // return: // -1 error // 0 file not found // 1 found nRet = GetFileSize( stop, channel, strCacheDir, "20121001.log", bAccessLog, out lServerFileSize, out lCacheFileSize, out strError); if (nRet == -1) return -1; // 检查日志文件缓存目录的版本是否和当前用户的信息一致 // return: // -1 出错 // 0 一致 // 1 不一致 nRet = DetectCacheVersionFile( strCacheDir, "version.xml", channel.LibraryCodeList, channel.Url, out strError); if (nRet == -1) return -1; if (nRet == 1) { // 清空当前缓存目录 nRet = Global.DeleteDataDir( owner, strCacheDir, out strError); if (nRet == -1) return -1; PathUtil.CreateDirIfNeed(strCacheDir); // 重新创建目录 // 创建版本文件 nRet = CreateCacheVersionFile( strCacheDir, "version.xml", channel.LibraryCodeList, channel.Url, out strError); if (nRet == -1) return -1; } } long lTotalSize = 0; List<string> lines = new List<string>(); // 经过处理后排除了不存在的文件名 List<long> sizes = new List<long>(); stop.SetMessage("正在准备获得日志文件尺寸 ..."); foreach (string strLine in filenames) { Application.DoEvents(); if (stop != null && stop.State != 0) { strError = "用户中断"; return 1; } if (String.IsNullOrEmpty(strLine) == true) continue; string strFilename = strLine.Trim(); // 去掉注释 nRet = strFilename.IndexOf("#"); if (nRet != -1) strFilename = strFilename.Substring(0, nRet).Trim(); if (String.IsNullOrEmpty(strFilename) == true) continue; string strLogFilename = ""; string strRange = ""; nRet = strFilename.IndexOf(":"); if (nRet != -1) { strLogFilename = strFilename.Substring(0, nRet).Trim(); strRange = strFilename.Substring(nRet + 1).Trim(); } else { strLogFilename = strFilename.Trim(); strRange = ""; } long lServerFileSize = 0; long lCacheFileSize = 0; // 获得一个日志文件的尺寸 // return: // -1 error // 0 file not found // 1 found nRet = GetFileSize( stop, channel, strCacheDir, strLogFilename, bAccessLog, out lServerFileSize, out lCacheFileSize, out strError); if (nRet == -1) return -1; if (nRet == 0) continue; if (lServerFileSize == 0) continue; // 0字节的文件当作不存在处理 Debug.Assert(lServerFileSize >= 0, ""); if (bAutoCache == true) { if (lCacheFileSize > 0) lTotalSize += lCacheFileSize; else lTotalSize += lServerFileSize; } else { lTotalSize += lServerFileSize; } lines.Add(strFilename); // 记忆每个文件的尺寸,后面就不用获取了? sizes.Add(lServerFileSize); } if (stop != null) stop.SetProgressRange(0, lTotalSize); estimate.SetRange(0, lTotalSize); estimate.StartEstimate(); long lDoneSize = 0; for (int i = 0; i < lines.Count; i++) { Application.DoEvents(); if (stop != null && stop.State != 0) { strError = "用户中断"; return 1; } string strLine = lines[i]; #if NO if (String.IsNullOrEmpty(strLine) == true) continue; // 去掉注释 nRet = strLine.IndexOf("#"); if (nRet != -1) strLine = strLine.Substring(0, nRet).Trim(); if (String.IsNullOrEmpty(strLine) == true) continue; #endif string strLogFilename = ""; string strRange = ""; nRet = strLine.IndexOf(":"); if (nRet != -1) { strLogFilename = strLine.Substring(0, nRet).Trim(); strRange = strLine.Substring(nRet + 1).Trim(); } else { strLogFilename = strLine.Trim(); strRange = ""; } // return: // -1 error // 0 正常结束 // 1 用户中断 nRet = ProcessFile( owner, stop, estimate, channel, strLogFilename, nLevel, sizes[i], strRange, strStyle, strCacheDir, param, procDoRecord, ref lDoneSize, ref lTotalSize, out strError); if (nRet == -1) { if (stop != null) { if (stop.State != 0) return 0; } // MessageBox.Show(this, strError); DialogResult result = MessageBox.Show(owner, strError + "\r\n\r\n是否继续处理?", "OperLogForm", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); if (result == DialogResult.No) return 1; } if (nRet == 1) return 1; } return 0; }
// strStart, // 起始路径, ""表示根 Package GetOneLevelDirPackage(string strStart) { int nRet; byte [] baPackage = null; // bool bSetDefault = false; // 表示是否使用过缺省帐户 //bool bFirstLogin = true; Package package = new Package(); // CWaitCursor cursor; if (Channel == null) { Channel = channelarray.CreateChannel(0); } Debug.Assert(Channel != null, "channel尚未初始化"); Cursor.Current = Cursors.WaitCursor; if (Stop != null) { Stop.OnStop += new StopEventHandler(this.DoStop); Stop.SetMessage("正在列目录 '" + strStart + "' ..."); Stop.BeginLoop(); } try { nRet = Channel.Dir(strStart, out baPackage); } finally { if (Stop != null) { Stop.EndLoop(); Stop.OnStop -= new StopEventHandler(this.DoStop); Stop.Initial(""); } Cursor.Current = Cursors.Default; } if (nRet == -1) { Channel.ErrorBox(this, "restree", "列目录发生错误"); goto ERROR1; } package.LoadPackage(baPackage, Channel.GetPathEncoding(strStart)); package.Parse(PackageFormat.String); return(package); ERROR1: return(null); }
// 检索出实体库全部可用的馆藏地名称 int SearchAllLocation( LibraryChannel channel, Stop stop, out string strError) { strError = ""; long lTotalCount = 0; this.listView_records.Items.Clear(); // EnableControls(false); stop.OnStop += new StopEventHandler(channel.DoStop); stop.Initial("正在列出全部馆藏地 ..."); stop.BeginLoop(); try { for (int i = 0; i < 2; i++) { long lRet = Channel.SearchItem( stop, "<all>", "", // strBatchNo -1, "馆藏地点", i == 0 ? "left" : "exact", // 第二次为检索空值 "zh", "batchno", // strResultSetName "", // "desc", "keycount", // strOutputStyle out strError); if (lRet == 0) { #if NO strError = "not found"; return 0; // not found #endif continue; } if (lRet == -1) return -1; long lHitCount = lRet; long lStart = 0; long lCount = lHitCount; DigitalPlatform.CirculationClient.localhost.Record[] searchresults = null; // 装入浏览格式 for (; ; ) { Application.DoEvents(); // 出让界面控制权 if (stop != null && stop.State != 0) { strError = "用户中断"; return -1; } lRet = channel.GetSearchResult( stop, "batchno", // strResultSetName lStart, lCount, "keycount", "zh", out searchresults, out strError); if (lRet == -1) { strError = "GetSearchResult() error: " + strError; return -1; } if (lRet == 0) { // MessageBox.Show(this, "未命中"); continue; } // 处理浏览结果 foreach (Record record in searchresults) { if (record.Cols == null) { strError = "请更新应用服务器和数据库内核到最新版本,才能使用列出馆藏地的功能"; return -1; } if (this._libraryCodeList.Count > 0 && MatchLibraryCode(this._libraryCodeList, record.Path) == false) continue; // 跳过数字为 0 的事项 if (record.Cols.Length > 0 && record.Cols[0] == "0") continue; ListViewItem item = new ListViewItem(); item.Text = string.IsNullOrEmpty(record.Path) == false ? record.Path : "[空]"; ListViewUtil.ChangeItemText(item, 1, record.Cols[0]); this.listView_records.Items.Add(item); } lStart += searchresults.Length; lCount -= searchresults.Length; stop.SetMessage("共命中 " + (lTotalCount + lHitCount).ToString() + " 条,已装入 " + (lTotalCount + lStart).ToString() + " 条"); if (lStart >= lHitCount || lCount <= 0) break; } lTotalCount += lHitCount; } if (lTotalCount == 0) { strError = "not found"; return 0; } } finally { stop.EndLoop(); stop.OnStop -= new StopEventHandler(channel.DoStop); stop.Initial(""); // EnableControls(true); } return 1; }
private void button_test_channelAttack_Click(object sender, EventArgs e) { _stop = new DigitalPlatform.Stop(); _stop.Register(this.MainForm.stopManager, true); // 和容器关联 _stop.OnStop += new StopEventHandler(this.DoStop); _stop.Style = StopStyle.EnableHalfStop; _stop.Initial("正在测试耗费通道 ..."); _stop.BeginLoop(); this.button_test_channelAttack.Enabled = false; this.numericUpDown_test_tryChannelCount.Enabled = false; try { for (int i = 0; i < this.numericUpDown_test_tryChannelCount.Value; i++ ) { Application.DoEvents(); if (_stop != null && _stop.State != 0) break; LibraryChannel channel = new LibraryChannel(); channel.Url = this.MainForm.LibraryServerUrl; channel.BeforeLogin -= new DigitalPlatform.CirculationClient.BeforeLoginEventHandle(Channel_BeforeLogin); channel.BeforeLogin += new DigitalPlatform.CirculationClient.BeforeLoginEventHandle(Channel_BeforeLogin); string strValue = ""; string strError = ""; long lRet = channel.GetSystemParameter(_stop, "library", "name", out strValue, out strError); #if NO if (lRet == -1) { if (channel.ErrorCode == DigitalPlatform.CirculationClient.localhost.ErrorCode.OutofSession) break; } #endif _stop.SetMessage(i.ToString()); } } finally { this.numericUpDown_test_tryChannelCount.Enabled = true; this.button_test_channelAttack.Enabled = true; _stop.EndLoop(); _stop.OnStop -= new StopEventHandler(this.DoStop); _stop.Initial(""); if (_stop != null) // 脱离关联 { _stop.Unregister(); // 和容器关联 _stop = null; } } }
// 获得一个日志文件的尺寸 // return: // -2 此类型的日志尚未启用 // -1 error // 0 file not found // 1 found static int GetFileSize( Stop stop, LibraryChannel channel, string strCacheDir, string strLogFileName, LogType logType, out long lServerFileSize, out long lCacheFileSize, out string strError) { strError = ""; lServerFileSize = 0; lCacheFileSize = 0; string strCacheFilename = PathUtil.MergePath(strCacheDir, strLogFileName); FileInfo fi = new FileInfo(strCacheFilename); if (fi.Exists == true) lCacheFileSize = fi.Length; stop.SetMessage("正获得日志文件 " + strLogFileName + " 的尺寸..."); string strXml = ""; long lAttachmentTotalLength = 0; byte[] attachment_data = null; string strStyle = "level-0"; if ((logType & LogType.AccessLog) != 0) strStyle += ",accessLog"; // 获得日志文件尺寸 // return: // -1 error // 0 file not found // 1 succeed // 2 超过范围 long lRet = channel.GetOperLog( stop, strLogFileName, -1, // lIndex, -1, // lHint, strStyle, "", // strFilter out strXml, out lServerFileSize, 0, // lAttachmentFragmentStart, 0, // nAttachmentFramengLength, out attachment_data, out lAttachmentTotalLength, out strError); if (lRet == 0) { lServerFileSize = 0; Debug.Assert(lServerFileSize == 0, ""); return 0; } if (lRet != 1) return -1; if (lServerFileSize == -1) { strError = "日志尚未启用"; return -2; } Debug.Assert(lServerFileSize >= 0, ""); return 1; }
// 获得日志记录 // return: // -1 出错 // 0 日志文件不存在 // 1 日志文件存在 int GetLogRecords(string strServerAddr, string strLogFileName, out string strError) { strError = ""; int nStartIndex = 0; stop.OnStop += new StopEventHandler(this.DoStop); stop.SetMessage("正在从服务器获得日志记录 ..."); stop.BeginLoop(); this.Update(); this.MainForm.Update(); try { string strPath = strServerAddr + "/log/" + strLogFileName + "/" + nStartIndex.ToString(); bool bFirst = true; string strDate = ""; int nRecID = -1; string strOffset = ""; int nStyle = 0; for (int i = nStartIndex; ; i++) { Application.DoEvents(); // 出让界面控制权 if (stop != null) { if (stop.State != 0) { strError = "用户中断"; return(-1); } } byte[] baPackage = null; if (bFirst == true) { } else { strPath = strServerAddr + "/log/" + strDate /*strLogFileName*/ + "/" + nRecID.ToString() + "@" + strOffset; } Encoding encoding = this.Channel.GetPathEncoding(strPath); stop.SetMessage("正在获得日志记录 " + strPath); int nRet = this.Channel.Search(strPath, DtlpChannel.RIZHI_STYLE | nStyle, out baPackage); if (nRet == -1) { int errorcode = this.Channel.GetLastErrno(); if (errorcode == DtlpChannel.GL_NOTEXIST) { if (bFirst == true) { break; } } // 更换新通道 if (errorcode == DtlpChannel.GL_INTR || errorcode == DtlpChannel.GL_SEND || errorcode == DtlpChannel.GL_RECV) { this.Channel = channelArray.CreateChannel(0); } strError = "获取日志记录:\r\n" + "路径: " + strPath + "\r\n" + "错误码: " + errorcode + "\r\n" + "错误信息: " + this.Channel.GetErrorString(errorcode) + "\r\n"; return(-1); } // 解析出记录 Package package = new Package(); package.LoadPackage(baPackage, encoding); package.Parse(PackageFormat.Binary); // 获得下一路径 string strNextPath = ""; strNextPath = package.GetFirstPath(); if (String.IsNullOrEmpty(strNextPath) == true) { if (this.checkBox_loop.Checked == true) { i--; continue; } if (bFirst == true) { strError = "文件 " + strLogFileName + "不存在"; return(0); } // strError = "检索 '" + strPath + "' 响应包中路径部分不存在 ..."; // return -1; break; } // 获得记录内容 byte[] baContent = null; nRet = package.GetFirstBin(out baContent); if (nRet != 1) { baContent = null; // 但是为空包 } // 处理记录 string strMARC = DtlpChannel.GetDt1000LogRecord(baContent, encoding); string strOperCode = ""; string strOperComment = ""; string strOperPath = ""; nRet = DtlpChannel.ParseDt1000LogRecord(strMARC, out strOperCode, out strOperComment, out strOperPath, out strError); if (nRet == -1) { strOperComment = strError; } LogItemInfo info = new LogItemInfo(); info.Index = i; info.Offset = GetStartOffs(strOffset); info.OriginData = baContent; info.Encoding = encoding; ListViewItem item = new ListViewItem(); item.Text = i.ToString(); item.SubItems.Add(info.Offset); item.SubItems.Add(strOperComment); item.SubItems.Add(strOperPath); item.Tag = info; this.listView_records.Items.Add(item); // 将日志记录路径解析为日期、序号、偏移 // 一个日志记录路径的例子为: // /ip/log/19991231/0@1234~5678 // parameters: // strLogPath 待解析的日志记录路径 // strDate 解析出的日期 // nRecID 解析出的记录号 // strOffset 解析出的记录偏移,例如1234~5678 // return: // -1 出错 // 0 正确 nRet = DtlpChannel.ParseLogPath(strNextPath, out strDate, out nRecID, out strOffset, out strError); if (nRet == -1) { return(-1); } // ModiOffset(ref strOffset); bFirst = false; } return(1); // 日志文件存在,已获得了记录 } finally { stop.EndLoop(); stop.OnStop -= new StopEventHandler(this.DoStop); stop.Initial(""); } }